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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
664da2f41cbb6887977b8fa72b51a5f0f21d4f36 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/group_with_zero/power.lean | 85991b81ad853044e6afdeabd9a82294632f20b3 | [
"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 | 9,335 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group_power
/-!
# Powers of elements of groups with an adjoined zero element
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
section zero
variables {M : Type*} [monoid_with_zero M]
@[simp] lemma zero_pow' : ∀ n : ℕ, n ≠ 0 → (0 : M) ^ n = 0
| 0 h := absurd rfl h
| (k+1) h := zero_mul _
lemma ne_zero_pow {a : M} {n : ℕ} (hn : n ≠ 0) : a ^ n ≠ 0 → a ≠ 0 :=
by { contrapose!, rintro rfl, exact zero_pow' n hn }
@[simp] lemma zero_pow_eq_zero [nontrivial M] {n : ℕ} : (0 : M) ^ n = 0 ↔ 0 < n :=
begin
split; intro h,
{ rw [pos_iff_ne_zero], rintro rfl, simpa using h },
{ exact zero_pow' n h.ne.symm }
end
end zero
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
section nat_pow
@[simp, field_simps] theorem inv_pow' (a : G₀) (n : ℕ) : (a⁻¹) ^ n = (a ^ n)⁻¹ :=
by induction n with n ih; [exact inv_one.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev']]
theorem pow_sub' (a : G₀) {m n : ℕ} (ha : a ≠ 0) (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a ^ (m - n) * a ^ n = a ^ m, by rw [←pow_add, h1],
by simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2
theorem pow_inv_comm' (a : G₀) (m n : ℕ) : (a⁻¹) ^ m * a ^ n = a ^ n * (a⁻¹) ^ m :=
(commute.refl a).inv_left'.pow_pow m n
end nat_pow
end group_with_zero
section int_pow
open int
variables {G₀ : Type*} [group_with_zero G₀]
/--
The power operation in a group with zero.
This extends `monoid.pow` to negative integers
with the definition `a ^ (-n) = (a ^ n)⁻¹`.
-/
def fpow (a : G₀) : ℤ → G₀
| (of_nat n) := a ^ n
| -[1+n] := (a ^ (nat.succ n))⁻¹
@[priority 10] instance : has_pow G₀ ℤ := ⟨fpow⟩
@[simp] theorem fpow_coe_nat (a : G₀) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
theorem fpow_of_nat (a : G₀) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
@[simp] theorem fpow_neg_succ_of_nat (a : G₀) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
local attribute [ematch] le_of_lt
@[simp] theorem fpow_zero (a : G₀) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem fpow_one (a : G₀) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_fpow : ∀ (n : ℤ), (1 : G₀) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G₀), by rw [one_pow, inv_one]
lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (of_nat n) h := zero_pow' _ $ by rintro rfl; exact h rfl
| -[1+n] h := show (0*0 ^ n)⁻¹ = (0 : G₀), by simp
@[simp] theorem fpow_neg (a : G₀) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := inv_one.symm
| -[1+ n] := (inv_inv' _).symm
theorem fpow_neg_one (x : G₀) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem inv_fpow (a : G₀) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow' a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow' a (n+1)
lemma fpow_add_one {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq, ha]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, fpow_neg, neg_add, neg_add_cancel_right, fpow_neg,
← int.coe_nat_succ, fpow_coe_nat, fpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev', mul_assoc,
inv_mul_cancel ha, mul_one]
lemma fpow_sub_one {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one]
... = a^n * a⁻¹ : by rw [← fpow_add_one ha, sub_add_cancel]
lemma fpow_add {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, fpow_add_one ha, ihn, mul_assoc] },
{ rw [fpow_sub_one ha, ← mul_assoc, ← ihn, ← fpow_sub_one ha, add_sub_assoc] }
end
lemma fpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) :
a ^ (m + n) = a ^ m * a ^ n :=
begin
by_cases hm : m = 0, { simp [hm] },
by_cases hn : n = 0, { simp [hn] },
by_cases ha : a = 0,
{ subst a,
simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h,
rw [zero_fpow _ h, zero_fpow _ hm, zero_mul] },
{ exact fpow_add ha m n }
end
theorem fpow_one_add {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [fpow_add h, fpow_one]
theorem semiconj_by.fpow_right {a x y : G₀} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := h.pow_right n
| -[1+n] := (h.pow_right (n + 1)).inv_right'
theorem commute.fpow_right {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) :=
h.fpow_right
theorem commute.fpow_left {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.fpow_right m).symm
theorem commute.fpow_fpow {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) :=
(h.fpow_left m).fpow_right n
theorem commute.fpow_self (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).fpow_left n
theorem commute.self_fpow (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).fpow_right n
theorem commute.fpow_fpow_self (a : G₀) (m n : ℤ) : commute (a^m) (a^n) :=
(commute.refl a).fpow_fpow m n
theorem fpow_bit0 (a : G₀) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n :=
begin
apply fpow_add', right,
by_cases hn : n = 0,
{ simp [hn] },
{ simp [← two_mul, hn, two_ne_zero] }
end
theorem fpow_bit1 (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
begin
rw [← fpow_bit0, bit1, fpow_add', fpow_one],
right, left,
apply bit1_ne_zero
end
theorem fpow_mul (a : G₀) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (fpow_neg _ (m * n.succ)).trans $
show (a ^ (m * n.succ))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (fpow_neg _ (m.succ * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow']; refl
| -[1+ m] -[1+ n] := (pow_mul a m.succ n.succ).trans $
show _ = (_⁻¹ ^ _)⁻¹, by rw [inv_pow', inv_inv']
theorem fpow_mul' (a : G₀) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, fpow_mul]
@[simp, norm_cast] lemma units.coe_gpow' (u : units G₀) :
∀ (n : ℤ), ((u ^ n : units G₀) : G₀) = u ^ n
| (n : ℕ) := u.coe_pow n
| -[1+k] := by rw [gpow_neg_succ_of_nat, fpow_neg_succ_of_nat, units.coe_inv', u.coe_pow]
lemma fpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (of_nat n) := pow_ne_zero _ ha
| -[1+n] := inv_ne_zero $ pow_ne_zero _ ha
lemma fpow_sub {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, fpow_add ha, fpow_neg, div_eq_mul_inv]
lemma commute.mul_fpow {a b : G₀} (h : commute a b) :
∀ (i : ℤ), (a * b) ^ i = (a ^ i) * (b ^ i)
| (n : ℕ) := h.mul_pow n
| -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev']
lemma mul_fpow {G₀ : Type*} [comm_group_with_zero G₀] (a b : G₀) (m : ℤ):
(a * b) ^ m = (a ^ m) * (b ^ m) :=
(commute.all a b).mul_fpow m
theorem fpow_bit0' (a : G₀) (n : ℤ) : a ^ bit0 n = (a * a) ^ n :=
(fpow_bit0 a n).trans ((commute.refl a).mul_fpow n).symm
theorem fpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a :=
by rw [fpow_bit1, (commute.refl a).mul_fpow]
lemma fpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
classical.by_contradiction $ λ hx, fpow_ne_zero_of_ne_zero hx n h
lemma fpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt fpow_eq_zero
theorem fpow_neg_mul_fpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) :
x ^ (-n) * x ^ n = 1 :=
begin
rw [fpow_neg],
exact inv_mul_cancel (fpow_ne_zero n h)
end
theorem one_div_pow {a : G₀} (n : ℕ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_pow']
theorem one_div_fpow {a : G₀} (n : ℤ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_fpow]
@[simp] lemma inv_fpow' {a : G₀} (n : ℤ) :
(a ⁻¹) ^ n = a ^ (-n) :=
by { rw [inv_fpow, ← fpow_neg_one, ← fpow_mul], simp }
end int_pow
section
variables {G₀ : Type*} [comm_group_with_zero G₀]
@[simp] theorem div_pow (a b : G₀) (n : ℕ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_pow, inv_pow']
@[simp] theorem div_fpow (a : G₀) {b : G₀} (n : ℤ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_fpow, inv_fpow]
lemma div_sq_cancel {a : G₀} (ha : a ≠ 0) (b : G₀) : a ^ 2 * b / a = a * b :=
by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
end
/-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`,
`n : ℤ`, to `(f x)^n`. -/
lemma monoid_with_zero_hom.map_fpow {G₀ G₀' : Type*} [group_with_zero G₀] [group_with_zero G₀']
(f : monoid_with_zero_hom G₀ G₀') (x : G₀) :
∀ n : ℤ, f (x ^ n) = f x ^ n
| (n : ℕ) := f.to_monoid_hom.map_pow x n
| -[1+n] := (f.map_inv' _).trans $ congr_arg _ $ f.to_monoid_hom.map_pow x _
|
fa016a2a6e7fb36748efaccf5e8ff8e6a53d655c | a9d59fc3316fcc8c227c3cbecb1202b6201ddd07 | /lean/Benchmark.lean | a3516b2378fe4246dd9d299b7414635a7abc0f27 | [] | no_license | PeterKementzey/lean-graph-benchmarking | 57db96d940c87cfe7906f1b49c8b81529b8cc905 | 00a1517cf22203f7fb89df5fb1598a2eff88bf54 | refs/heads/master | 1,686,192,971,424 | 1,625,278,683,000 | 1,625,278,683,000 | 374,718,875 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,475 | lean | import Graph.Graph
import Graph.Parser
import Graph.TopologicalSort
import Graph.Search
/-- This function ensures that the expression does not get dropped by compiler optimizations. -/
def evaluate [ToString α] (expression : α) : IO Unit := IO.FS.writeFile "/dev/null" (toString expression)
def benchmarkParsing (filePath : String) : IO (Graph Bool Nat) := do
let initial <- IO.monoMsNow
let input <- IO.FS.lines filePath
let (nodeCount, edgeList) := parseEdgeList input
let start <- IO.monoMsNow
let graph <- parse nodeCount edgeList
let stop <- IO.monoMsNow
-- IO.println ("Read from file and converted to nat in: " ++ (toString (start - initial)) ++ " ms")
-- IO.println ("Parsed graph in: " ++ (toString (stop - start)) ++ " ms")
graph
def benchmarkTopSort (graph : Graph Bool Nat) : IO Unit := do
let start <- IO.monoMsNow
let res <- graph.topSortUnsafe
let stop <- IO.monoMsNow
IO.println ((toString (stop - start)) ++ " ms")
-- IO.println ("Sorted graph in: " ++ (toString (stop - start)) ++ " ms")
evaluate res.back
def benchmarkTopSortSafe (graph : Graph Bool Nat) : IO Unit := do
let start <- IO.monoMsNow
let res <- graph.topSort
let stop <- IO.monoMsNow
IO.println ((toString (stop - start)) ++ " ms")
-- IO.println ("Safely sorted graph in: " ++ (toString (stop - start)) ++ " ms")
evaluate res.get!.back
def benchmarkReachableDepthFirst (graph : Graph Bool Nat) (source : Nat) : IO Unit := do
let start <- IO.monoMsNow
let res <- graph.reachableDepthFirst source
let stop <- IO.monoMsNow
IO.println ((toString (stop - start)) ++ " ms")
-- IO.println ("Safely sorted graph in: " ++ (toString (stop - start)) ++ " ms")
evaluate res.back
def benchmarkReachableBreadthFirst (graph : Graph Bool Nat) (source : Nat) : IO Unit := do
let start <- IO.monoMsNow
let res <- graph.reachableBreadthFirst source
let stop <- IO.monoMsNow
IO.println ((toString (stop - start)) ++ " ms")
-- IO.println ("Safely sorted graph in: " ++ (toString (stop - start)) ++ " ms")
evaluate res.back
def main (argv : List String) : IO Unit := do
let filePath := argv.head!
let benchmark := argv.get! 1
let graph <- benchmarkParsing filePath
match benchmark with
| "topsort" =>
benchmarkTopSort graph
benchmarkTopSortSafe graph
| "reachable" =>
benchmarkReachableDepthFirst graph 3
benchmarkReachableBreadthFirst graph 3
| _ => panic! "Benchmark type not recognized"
|
23e996b1555d14ec39667882663460aeb353748d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/set_theory/game/winner.lean | 093107e7d31fa26f3c75793d2663ee9b7f0f07cc | [
"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 | 3,398 | 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.pgame
/-!
# Basic definitions about who has a winning stratergy
We define `G.first_loses`, `G.first_wins`, `G.left_wins` and `G.right_wins` for a pgame `G`, which
means the second, first, left and right players have a winning strategy respectively.
These are defined by inequalities which can be unfolded with `pgame.lt_def` and `pgame.le_def`.
-/
namespace pgame
local infix ` ≈ ` := equiv
/-- The player who goes first loses -/
def first_loses (G : pgame) : Prop := G ≤ 0 ∧ 0 ≤ G
/-- The player who goes first wins -/
def first_wins (G : pgame) : Prop := 0 < G ∧ G < 0
/-- The left player can always win -/
def left_wins (G : pgame) : Prop := 0 < G ∧ 0 ≤ G
/-- The right player can always win -/
def right_wins (G : pgame) : Prop := G ≤ 0 ∧ G < 0
theorem zero_first_loses : first_loses 0 := by tidy
theorem one_left_wins : left_wins 1 :=
⟨by { rw lt_def_le, tidy }, by rw le_def; tidy⟩
theorem star_first_wins : first_wins star := ⟨zero_lt_star, star_lt_zero⟩
theorem omega_left_wins : left_wins omega :=
⟨by { rw lt_def_le, exact or.inl ⟨ulift.up 0, by tidy⟩ }, by rw le_def; tidy⟩
lemma winner_cases (G : pgame) : G.left_wins ∨ G.right_wins ∨ G.first_loses ∨ G.first_wins :=
begin
classical,
by_cases hpos : 0 < G;
by_cases hneg : G < 0;
{ try { rw not_lt at hpos },
try { rw not_lt at hneg },
try { left, exact ⟨hpos, hneg⟩ },
try { right, left, exact ⟨hpos, hneg⟩ },
try { right, right, left, exact ⟨hpos, hneg⟩ },
try { right, right, right, exact ⟨hpos, hneg⟩ } }
end
lemma first_loses_is_zero {G : pgame} : G.first_loses ↔ G ≈ 0 := by refl
lemma first_loses_of_equiv {G H : pgame} (h : G ≈ H) : G.first_loses → H.first_loses :=
λ hGp, ⟨le_of_equiv_of_le h.symm hGp.1, le_of_le_of_equiv hGp.2 h⟩
lemma first_wins_of_equiv {G H : pgame} (h : G ≈ H) : G.first_wins → H.first_wins :=
λ hGn, ⟨lt_of_lt_of_equiv hGn.1 h, lt_of_equiv_of_lt h.symm hGn.2⟩
lemma left_wins_of_equiv {G H : pgame} (h : G ≈ H) : G.left_wins → H.left_wins :=
λ hGl, ⟨lt_of_lt_of_equiv hGl.1 h, le_of_le_of_equiv hGl.2 h⟩
lemma right_wins_of_equiv {G H : pgame} (h : G ≈ H) : G.right_wins → H.right_wins :=
λ hGr, ⟨le_of_equiv_of_le h.symm hGr.1, lt_of_equiv_of_lt h.symm hGr.2⟩
lemma first_loses_of_equiv_iff {G H : pgame} (h : G ≈ H) : G.first_loses ↔ H.first_loses :=
⟨first_loses_of_equiv h, first_loses_of_equiv h.symm⟩
lemma first_wins_of_equiv_iff {G H : pgame} (h : G ≈ H) : G.first_wins ↔ H.first_wins :=
⟨first_wins_of_equiv h, first_wins_of_equiv h.symm⟩
lemma left_wins_of_equiv_iff {G H : pgame} (h : G ≈ H) : G.left_wins ↔ H.left_wins :=
⟨left_wins_of_equiv h, left_wins_of_equiv h.symm⟩
lemma right_wins_of_equiv_iff {G H : pgame} (h : G ≈ H) : G.right_wins ↔ H.right_wins :=
⟨right_wins_of_equiv h, right_wins_of_equiv h.symm⟩
lemma not_first_wins_of_first_loses {G : pgame} : G.first_loses → ¬G.first_wins :=
begin
rw first_loses_is_zero,
rintros h ⟨h₀, -⟩,
exact lt_irrefl 0 (lt_of_lt_of_equiv h₀ h)
end
lemma not_first_loses_of_first_wins {G : pgame} : G.first_wins → ¬G.first_loses :=
imp_not_comm.1 $ not_first_wins_of_first_loses
end pgame
|
87000ed10df3d49ea5d3fab531f437729d194a5b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/simp_inductive_compiler_issue.lean | 5e40fc5b26d97e7fcfb20f27e1b055429df45d72 | [
"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 | 236 | lean | structure box (α : Type) :=
(val : α)
def f1 (g h : ℕ → ℕ) (b : bool) : ℕ → ℕ :=
box.val (bool.cases_on b (box.mk g) (box.mk h))
def f2 (g h : box (ℕ → ℕ)) (b : bool) : ℕ → ℕ :=
box.val (bool.cases_on b g h)
|
05a8c279a686edd6fe167c73b9e60b93e6749924 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/obtain.lean | b87338ac371f78182a68fee84cff12fa27cd1c2e | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 709 | lean | new_frontend
macro "obtain " p:term " from " d:term "; " body:term : term =>
`(match $d:term with | $p:term => $body:term)
theorem tst1 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r :=
match h with
| ⟨h₁, ⟨h₂, h₃⟩⟩ => ⟨h₂, ⟨h₁, h₃⟩⟩
theorem tst2 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r :=
obtain ⟨h₁, ⟨h₂, h₃⟩⟩ from h;
⟨h₂, ⟨h₁, h₃⟩⟩
macro "obtain " p:term " from " d:term "; " body:tactic : tactic =>
`(tactic| match $d:term with | $p:term => _; $body)
theorem tst3 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r :=
by {
obtain ⟨h₁, ⟨h₂, h₃⟩⟩ from h;
apply And.intro;
assumption;
apply And.intro;
assumption;
assumption
}
|
71ee50dd427febe38f570316637ecc9f907c58a1 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/data/string.lean | c5eed5186909d7dd7c043dafedaa3bf817416cd8 | [
"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 | 1,716 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import data.bool
open bool
protected definition char.is_inhabited [instance] : inhabited char :=
inhabited.mk (char.mk ff ff ff ff ff ff ff ff)
protected definition string.is_inhabited [instance] : inhabited string :=
inhabited.mk string.empty
open decidable
definition decidable_eq_char [instance] : ∀ c₁ c₂ : char, decidable (c₁ = c₂) :=
begin
intro c₁ c₂,
cases c₁ with a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈,
cases c₂ with b₁ b₂ b₃ b₄ b₅ b₆ b₇ b₈,
apply (@by_cases (a₁ = b₁)), intros,
apply (@by_cases (a₂ = b₂)), intros,
apply (@by_cases (a₃ = b₃)), intros,
apply (@by_cases (a₄ = b₄)), intros,
apply (@by_cases (a₅ = b₅)), intros,
apply (@by_cases (a₆ = b₆)), intros,
apply (@by_cases (a₇ = b₇)), intros,
apply (@by_cases (a₈ = b₈)), intros,
left, congruence, repeat assumption,
repeat (intro n; right; intro h; injection h; contradiction)
end
open string
definition decidable_eq_string [instance] : ∀ s₁ s₂ : string, decidable (s₁ = s₂)
| empty empty := by left; reflexivity
| empty (str c₂ r₂) := by right; contradiction
| (str c₁ r₁) empty := by right; contradiction
| (str c₁ r₁) (str c₂ r₂) :=
match decidable_eq_char c₁ c₂ with
| inl e₁ :=
match decidable_eq_string r₁ r₂ with
| inl e₂ := by left; congruence; repeat assumption
| inr n₂ := by right; intro h; injection h; contradiction
end
| inr n₁ := by right; intro h; injection h; contradiction
end
|
0bfc2ccddd4431a8207c43d6de403108797ae050 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /test/linarith.lean | 9c609b7db1cc9eed56897bcef12dc66b8f721141 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 10,367 | lean | import tactic.linarith
import algebra.field_power
example {α : Type} (_inst : Π (a : Prop), decidable a)
[linear_ordered_field α]
{a b c : α}
(ha : a < 0)
(hb : ¬b = 0)
(hc' : c = 0)
(h : (1 - a) * (b * b) ≤ 0)
(hc : 0 ≤ 0)
(this : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b))
(h : (1 - a) * (b * b) ≤ 0) :
0 < 1 - a :=
begin
linarith
end
example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 :=
by linarith
example (u v r s t : ℚ) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u :=
by linarith
example (A B : ℚ) (h : 0 < A * B) : 0 < 8*A*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*8*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*B/8 :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A/8*B :=
begin
linarith
end
example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε :=
by linarith
example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
(h3 : 12*y - z < 0) : false :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε :=
by linarith
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith {discharger := `[ring SOP]}
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith
example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false :=
by linarith {restrict_type := ℚ}
example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 ≤ c) (h6 : c < 1) :
v ≤ V :=
by linarith
example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0)
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) :
¬ 12*y - 4* z < 0 :=
by linarith
example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0)
(h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false :=
by linarith
example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10)
(h4 : a + b - c < 3) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false :=
by linarith
example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 :=
by linarith {exfalso := ff}
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith [rat.num_pos_iff_pos.mpr hx, h]
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith only [rat.num_pos_iff_pos.mpr hx, h]
example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (h1 : (1 : ℕ) < 1) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 :=
by linarith
example (a b c : ℕ) : a + b ≥ a :=
by linarith
example (a b c : ℕ) : ¬ a + b < a :=
by linarith
example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0)
(h'' : (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (x y : ℚ)
(h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false :=
by linarith
example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false :=
by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 :=
by linarith
example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c :=
by linarith
example
(N : ℕ) (n : ℕ) (Hirrelevant : n > N)
(A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l)
(h_3 : -(A - l) < 1) : A < l + 1 := by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
d ≤ ((q : ℚ) - 1)*n :=
by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) :=
by linarith
example (a : ℚ) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a :=
by linarith
example (x : ℚ) : id x ≥ x :=
by success_if_fail {linarith}; linarith!
example (x y z : ℚ) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false :=
by linarith only [hx, hx2]
example (x y z : ℚ) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x ≤ 5 :=
by linarith only [hx]
example (x y : ℚ) (h : x < y) : x ≠ y := by linarith
example (x y : ℚ) (h : x < y) : ¬ x = y := by linarith
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
u * y + v * x + u * v < 3 * A * B :=
by nlinarith
example (u v x y A B : ℚ) : (0 < A) → (A ≤ 1) → (1 ≤ B)
→ (x ≤ B) → ( y ≤ B)
→ (0 ≤ u ) → (0 ≤ v )
→ (u < A) → ( v < A)
→ (u * y + v * x + u * v < 3 * A * B) :=
begin
intros,
nlinarith
end
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 < A * A)
-> (0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 <= A * (B - x))
-> (0 <= A * (B - y))
-> (0 <= A * u)
-> (0 <= A * v)
-> (0 < A * (A - u))
-> (0 < A * (A - v))
-> (0 <= (1 - A) * A)
-> (0 <= (1 - A) * (1 - A))
-> (0 <= (1 - A) * (B - 1))
-> (0 <= (1 - A) * (B - x))
-> (0 <= (1 - A) * (B - y))
-> (0 <= (1 - A) * u)
-> (0 <= (1 - A) * v)
-> (0 <= (1 - A) * (A - u))
-> (0 <= (1 - A) * (A - v))
-> (0 <= (B - 1) * A)
-> (0 <= (B - 1) * (1 - A))
-> (0 <= (B - 1) * (B - 1))
-> (0 <= (B - 1) * (B - x))
-> (0 <= (B - 1) * (B - y))
-> (0 <= (B - 1) * u)
-> (0 <= (B - 1) * v)
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * A)
-> (0 <= (B - x) * (1 - A))
-> (0 <= (B - x) * (B - 1))
-> (0 <= (B - x) * (B - x))
-> (0 <= (B - x) * (B - y))
-> (0 <= (B - x) * u)
-> (0 <= (B - x) * v)
-> (0 <= (B - x) * (A - u))
-> (0 <= (B - x) * (A - v))
-> (0 <= (B - y) * A)
-> (0 <= (B - y) * (1 - A))
-> (0 <= (B - y) * (B - 1))
-> (0 <= (B - y) * (B - x))
-> (0 <= (B - y) * (B - y))
-> (0 <= (B - y) * u)
-> (0 <= (B - y) * v)
-> (0 <= (B - y) * (A - u))
-> (0 <= (B - y) * (A - v))
-> (0 <= u * A)
-> (0 <= u * (1 - A))
-> (0 <= u * (B - 1))
-> (0 <= u * (B - x))
-> (0 <= u * (B - y))
-> (0 <= u * u)
-> (0 <= u * v)
-> (0 <= u * (A - u))
-> (0 <= u * (A - v))
-> (0 <= v * A)
-> (0 <= v * (1 - A))
-> (0 <= v * (B - 1))
-> (0 <= v * (B - x))
-> (0 <= v * (B - y))
-> (0 <= v * u)
-> (0 <= v * v)
-> (0 <= v * (A - u))
-> (0 <= v * (A - v))
-> (0 < (A - u) * A)
-> (0 <= (A - u) * (1 - A))
-> (0 <= (A - u) * (B - 1))
-> (0 <= (A - u) * (B - x))
-> (0 <= (A - u) * (B - y))
-> (0 <= (A - u) * u)
-> (0 <= (A - u) * v)
-> (0 < (A - u) * (A - u))
-> (0 < (A - u) * (A - v))
-> (0 < (A - v) * A)
-> (0 <= (A - v) * (1 - A))
-> (0 <= (A - v) * (B - 1))
-> (0 <= (A - v) * (B - x))
-> (0 <= (A - v) * (B - y))
-> (0 <= (A - v) * u)
-> (0 <= (A - v) * v)
-> (0 < (A - v) * (A - u))
-> (0 < (A - v) * (A - v))
->
u * y + v * x + u * v < 3 * A * B :=
begin
intros,
linarith
end
example (A B : ℚ) : (0 < A) → (1 ≤ B) → (0 < A / 8 * B) :=
begin
intros, nlinarith
end
example (x y : ℚ) : 0 ≤ x ^2 + y ^2 :=
by nlinarith
example (x y : ℚ) : 0 ≤ x*x + y*y :=
by nlinarith
example (x y : ℚ) : x = 0 → y = 0 → x*x + y*y = 0 :=
by intros; nlinarith
lemma norm_eq_zero_iff {x y : ℚ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
begin
split,
{ intro, split; nlinarith },
{ intro, nlinarith }
end
lemma norm_nonpos_right {x y : ℚ} (h1 : x * x + y * y ≤ 0) : y = 0 :=
by nlinarith
lemma norm_nonpos_left (x y : ℚ) (h1 : x * x + y * y ≤ 0) : x = 0 :=
by nlinarith
variables {E : Type*} [add_group E]
example (f : ℤ → E) (h : 0 = f 0) : 1 ≤ 2 := by nlinarith
example (a : E) (h : a = a) : 1 ≤ 2 := by nlinarith
-- test that the apply bug doesn't affect linarith preprocessing
constant α : Type
variable [fact false] -- we work in an inconsistent context below
def leα : α → α → Prop := λ a b, ∀ c : α, true
noncomputable instance : linear_ordered_field α :=
by refine_struct { le := leα }; exact false.elim _inst_2
example (a : α) (ha : a < 2) : a ≤ a :=
by linarith
example (p q r s t u v w : ℕ) (h1 : p + u = q + t) (h2 : r + w = s + v) :
p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) :=
by nlinarith
-- Tests involving a norm, including that squares in a type where `pow_two_nonneg` does not apply
-- do not cause an exception
variables {R : Type*} [ring R] (abs : R → ℚ)
lemma abs_nonneg' : ∀ r, 0 ≤ abs r := false.elim _inst_2
example (t : R) (a b : ℚ) (h : a ≤ b) : abs (t^2) * a ≤ abs (t^2) * b :=
by nlinarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : a ≤ abs (t^2) + b :=
by linarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : abs t * a ≤ abs t * b :=
by nlinarith [abs_nonneg' abs t]
constant T : Type
attribute [instance]
constant T_zero : ordered_ring T
namespace T
lemma zero_lt_one : (0 : T) < 1 := false.elim _inst_2
lemma works {a b : ℕ} (hab : a ≤ b) (h : b < a) : false :=
begin
linarith,
end
end T
example (a b c : ℚ) (h : a ≠ b) (h3 : b ≠ c) (h2 : a ≥ b) : b ≠ c :=
by linarith {split_ne := tt}
example (a b c : ℚ) (h : a ≠ b) (h2 : a ≥ b) (h3 : b ≠ c) : a > b :=
by linarith {split_ne := tt}
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x * x := by nlinarith
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x ^ 2 := by nlinarith
|
ead01fa24fe759d29282622ce084977e19a2ec54 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love13_rational_and_real_numbers_exercise_sheet.lean | f27b257ee76ff527672c3a162c9e57c816f0b801 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 3,809 | lean | /- LoVe Exercise 13: Rational and Real Numbers -/
import .love05_inductive_predicates_demo
import .love13_rational_and_real_numbers_demo
namespace LoVe
set_option pp.beta true
/- Question 1: Rationals -/
/- 1.1. Prove the following lemma.
Hint: The lemma `fraction.mk.inj_eq` might be useful. -/
#check fraction.mk.inj_eq
lemma fraction.ext (a b : fraction) (h : fraction.num a = fraction.num b)
(h': fraction.denom a = fraction.denom b) :
a = b :=
sorry
/- 1.2. Extending the `fraction.has_mul` instance from the lecture, declare
`fraction` an instance of `semigroup`.
Hint: Use the lemma `fraction.ext` above, and possibly `fraction.mul_num`, and
`fraction.mul_denom`. -/
#check fraction.ext
#check fraction.mul_num
#check fraction.mul_denom
instance fraction.semigroup : semigroup fraction :=
{ mul_assoc :=
sorry,
..fraction.has_mul }
/- 1.3. Extending the `myℚ.has_mul` instance from the lecture, declare `myℚ` an
instance of `semigroup`.
Hint: The lemma `quotient.induction_on₃` might be useful. -/
#check quotient.induction_on₃
instance myℚ.semigroup : semigroup myℚ :=
{ mul_assoc :=
sorry,
..myℚ.has_mul }
/- Question 2: Structural Induction on Paper -/
/- This and the next question will exercise your understanding of induction,
especially if you need to perform induction proofs on a whiteboard (or on paper
at the exam).
Guidelines for paper proofs:
We expect detailed, rigorous, mathematical proofs. You are welcome to use
standard mathematical notation or Lean structured commands (e.g., `assume`,
`have`, `show`, `calc`). You can also use tactical proofs (e.g., `intro`,
`apply`), but then please indicate some of the intermediate goals, so that we
can follow the chain of reasoning.
Major proof steps, including applications of induction and invocation of the
induction hypothesis, must be stated explicitly. For each case of a proof by
induction, you must list the inductive hypotheses assumed (if any) and the goal
to be proved. Minor proof steps corresponding to `refl`, `simp`, or `linarith`
need not be justified if you think they are obvious (to humans), but you should
say which key lemmas they follow from. You should be explicit whenever you use a
function definition or an introduction rule for an inductive predicate. -/
/- 2.1. Recall the following inductive datatype for binary trees from lecture 4:
inductive btree (α : Type) : Type
| empty {} : btree
| node : α → btree → btree → btree
We defined a function `mirror` on these binary trees as follows:
def mirror {α : Type} : btree α → btree α
| empty := empty
| (node a l r) := node a (mirror r) (mirror l)
Prove the following lemma by structural induction, as a paper proof:
lemma mirror_mirror {α : Type} :
∀t : btree α, mirror (mirror t) = t -/
-- enter your "paper" proof here
/- 2.2. Prove the same lemma in Lean and compare it with your paper proof. -/
lemma mirror_mirror₂ {α : Type} :
∀t : btree α, mirror (mirror t) = t :=
sorry
/- Question 3: Rule Induction on Paper -/
/- 3.1. Recall the following inductive predicate from lecture 5:
inductive even : ℕ → Prop
| zero : even 0
| add_two : ∀n, even n → even (n + 2)
Prove the following lemma by rule induction, as a paper proof, following the
guidelines given at the beginning of question 2. This is a good exercise to
develop a deeper understanding of how rule induction works (and is good
practice for the final exam).
lemma exists_of_even (n : ℕ) (h : even n) :
∃k : ℕ, n = 2 * k -/
-- enter your "paper" proof here
/- 3.2. Prove the same lemma in Lean and compare it with your paper proof. -/
lemma exists_of_even (n : ℕ) (h : even n) :
∃k : ℕ, n = 2 * k :=
sorry
end LoVe
|
5fc43142fde7a230a28e24db6b03617e0cee63de | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/compact_open.lean | 4aa530e886677c0e9b6935d11400ff2f0f5d3f69 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,802 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
Type of continuous maps and the compact-open topology on them.
-/
import topology.subset_properties
import topology.continuous_map
import tactic.tidy
open set
open_locale topological_space
namespace continuous_map
section compact_open
variables {α : Type*} {β : Type*} {γ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
def compact_open.gen (s : set α) (u : set β) : set C(α,β) := {f | f '' s ⊆ u}
-- The compact-open topology on the space of continuous maps α → β.
instance compact_open : topological_space C(α, β) :=
topological_space.generate_from
{m | ∃ (s : set α) (hs : is_compact s) (u : set β) (hu : is_open u), m = compact_open.gen s u}
private lemma is_open_gen {s : set α} (hs : is_compact s) {u : set β} (hu : is_open u) :
is_open (compact_open.gen s u) :=
topological_space.generate_open.basic _ (by dsimp [mem_set_of_eq]; tauto)
section functorial
variables {g : β → γ} (hg : continuous g)
def induced (f : C(α, β)) : C(α, γ) := ⟨g ∘ f, hg.comp f.continuous⟩
private lemma preimage_gen {s : set α} (hs : is_compact s) {u : set γ} (hu : is_open u) :
continuous_map.induced hg ⁻¹' (compact_open.gen s u) = compact_open.gen s (g ⁻¹' u) :=
begin
ext ⟨f, _⟩,
change g ∘ f '' s ⊆ u ↔ f '' s ⊆ g ⁻¹' u,
rw [image_comp, image_subset_iff]
end
/-- C(α, -) is a functor. -/
lemma continuous_induced : continuous (continuous_map.induced hg : C(α, β) → C(α, γ)) :=
continuous_generated_from $ assume m ⟨s, hs, u, hu, hm⟩,
by rw [hm, preimage_gen hg hs hu]; exact is_open_gen hs (hg _ hu)
end functorial
section ev
variables (α β)
def ev (p : C(α, β) × α) : β := p.1 p.2
variables {α β}
-- The evaluation map C(α, β) × α → β is continuous if α is locally compact.
lemma continuous_ev [locally_compact_space α] : continuous (ev α β) :=
continuous_iff_continuous_at.mpr $ assume ⟨f, x⟩ n hn,
let ⟨v, vn, vo, fxv⟩ := mem_nhds_sets_iff.mp hn in
have v ∈ 𝓝 (f x), from mem_nhds_sets vo fxv,
let ⟨s, hs, sv, sc⟩ :=
locally_compact_space.local_compact_nhds x (f ⁻¹' v)
(f.continuous.tendsto x this) in
let ⟨u, us, uo, xu⟩ := mem_nhds_sets_iff.mp hs in
show (ev α β) ⁻¹' n ∈ 𝓝 (f, x), from
let w := set.prod (compact_open.gen s v) u in
have w ⊆ ev α β ⁻¹' n, from assume ⟨f', x'⟩ ⟨hf', hx'⟩, calc
f' x' ∈ f' '' s : mem_image_of_mem f' (us hx')
... ⊆ v : hf'
... ⊆ n : vn,
have is_open w, from (is_open_gen sc vo).prod uo,
have (f, x) ∈ w, from ⟨image_subset_iff.mpr sv, xu⟩,
mem_nhds_sets_iff.mpr ⟨w, by assumption, by assumption, by assumption⟩
end ev
section coev
variables (α β)
def coev (b : β) : C(α, β × α) := ⟨λ a, (b, a), continuous.prod_mk continuous_const continuous_id⟩
variables {α β}
lemma image_coev {y : β} (s : set α) : (coev α β y) '' s = set.prod {y} s := by tidy
-- The coevaluation map β → C(α, β × α) is continuous (always).
lemma continuous_coev : continuous (coev α β) :=
continuous_generated_from $ begin
rintros _ ⟨s, sc, u, uo, rfl⟩,
rw is_open_iff_forall_mem_open,
intros y hy,
change (coev α β y) '' s ⊆ u at hy,
rw image_coev s at hy,
rcases generalized_tube_lemma compact_singleton sc uo hy
with ⟨v, w, vo, wo, yv, sw, vwu⟩,
refine ⟨v, _, vo, singleton_subset_iff.mp yv⟩,
intros y' hy',
change (coev α β y') '' s ⊆ u,
rw image_coev s,
exact subset.trans (prod_mono (singleton_subset_iff.mpr hy') sw) vwu
end
end coev
end compact_open
end continuous_map
|
a5521c67ea1d7ef5ce168fe43af199022dc3238f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/test/102/lakefile.lean | 998c16955e7966fc7cce0421f40c0bb980af098a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 175 | lean | import Lake
open Lake DSL
package tba {
-- add package configuration options here
}
@[default_target]
lean_lib TBA := {
name := `TBA
globs := #[.andSubmodules `TBA]
}
|
2996285d2d04f3cdf102900968d0e80011b6d05c | 46125763b4dbf50619e8846a1371029346f4c3db | /src/order/bounds.lean | 2d064f8716d8d6772fe006e5c9e2403f94b8cf77 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 24,582 | 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 Kudryashov
-/
import algebra.order_functions data.set.intervals.basic
/-!
# Upper / lower bounds
In this file we define:
* `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set;
* `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper
(resp., lower) bounds of `s` is nonempty;
* `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`;
for a partial order, it is unique if exists;
* `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound)
of `s`; for a partial order, it is unique if exists.
We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide
formulas for `∅`, `univ`, and intervals.
-/
open set lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section
variables [preorder α] [preorder β] {s t : set α} {a b : α}
/-!
### Definitions
-/
/-- The set of upper bounds of a set. -/
def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x }
/-- The set of lower bounds of a set. -/
def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a }
/-- A set is bounded above if there exists an upper bound. -/
def bdd_above (s : set α) := (upper_bounds s).nonempty
/-- A set is bounded below if there exists a lower bound. -/
def bdd_below (s : set α) := (lower_bounds s).nonempty
/-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/
def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
/-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/
def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
/-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/
def is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
/-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/
def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
/-!
### Monotonicity
-/
lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
upper_bounds t ⊆ upper_bounds s :=
λ b hb x h, hb $ hst h
lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
lower_bounds t ⊆ lower_bounds s :=
λ b hb x h, hb $ hst h
lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s :=
λ ha x h, le_trans (ha h) hab
lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s :=
λ hb x h, le_trans hab (hb h)
lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
a ∈ upper_bounds t → b ∈ upper_bounds s :=
λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha
lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
b ∈ lower_bounds t → a ∈ lower_bounds s :=
λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb
/-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/
lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s :=
nonempty.mono $ upper_bounds_mono_set h
/-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/
lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s :=
nonempty.mono $ lower_bounds_mono_set h
/-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a :=
⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩
/-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a :=
@is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp
/-!
### Conversions
-/
lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a :=
set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩
lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a :=
@is_lub.upper_bounds_eq (order_dual α) _ _ _ h
lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a :=
h.is_glb.lower_bounds_eq
lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a :=
h.is_lub.upper_bounds_eq
/-- If `s` has a least upper bound, then it is bounded above. -/
lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩
/-- If `s` has a greatest lower bound, then it is bounded below. -/
lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩
/-- If `s` has a greatest element, then it is bounded above. -/
lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩
/-- If `s` has a least element, then it is bounded below. -/
lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩
lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩
lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩
/-!
### Union and intersection
-/
@[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t :=
subset.antisymm
(λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩)
(λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht))
@[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t :=
@upper_bounds_union (order_dual α) _ s t
lemma union_upper_bounds_subset_upper_bounds_inter :
upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) :=
union_subset
(upper_bounds_mono_set $ inter_subset_left _ _)
(upper_bounds_mono_set $ inter_subset_right _ _)
lemma union_lower_bounds_subset_lower_bounds_inter :
lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) :=
@union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t
lemma is_least_union_iff {a : α} {s t : set α} :
is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) :=
by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc]
lemma is_greatest_union_iff :
is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨
a ∈ upper_bounds s ∧ is_greatest t a) :=
@is_least_union_iff (order_dual α) _ a s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/
lemma bdd_above.union [semilattice_sup γ] {s t : set γ} :
bdd_above s → bdd_above t → bdd_above (s ∪ t) :=
begin
rintros ⟨bs, hs⟩ ⟨bt, ht⟩,
use bs ⊔ bt,
rw upper_bounds_union,
exact ⟨upper_bounds_mono_mem le_sup_left hs,
upper_bounds_mono_mem le_sup_right ht⟩
end
/-- The union of two sets is bounded above if and only if each of the sets is. -/
lemma bdd_above_union [semilattice_sup γ] {s t : set γ} :
bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t :=
⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩,
λ h, h.1.union h.2⟩
lemma bdd_below.union [semilattice_inf γ] {s t : set γ} :
bdd_below s → bdd_below t → bdd_below (s ∪ t) :=
@bdd_above.union (order_dual γ) _ s t
/--The union of two sets is bounded above if and only if each of the sets is.-/
lemma bdd_below_union [semilattice_inf γ] {s t : set γ} :
bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t :=
@bdd_above_union (order_dual γ) _ s t
/-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`,
then `a ⊔ b` is the least upper bound of `s ∪ t`. -/
lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ}
(hs : is_lub s a) (ht : is_lub t b) :
is_lub (s ∪ t) (a ⊔ b) :=
⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h),
assume c hc, sup_le
(hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩
/-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`,
then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/
lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ}
(hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
@is_lub.union (order_dual γ) _ _ _ _ _ hs ht
/-- If `a` is the least element of `s` and `b` is the least element of `t`,
then `min a b` is the least element of `s ∪ t`. -/
lemma is_least.union [decidable_linear_order γ] {a b : γ} {s t : set γ}
(ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_glb.union hb.is_glb).1⟩
/-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`,
then `max a b` is the greatest element of `s ∪ t`. -/
lemma is_greatest.union [decidable_linear_order γ] {a b : γ} {s t : set γ}
(ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_lub.union hb.is_lub).1⟩
/-!
### Specific sets
#### Unbounded intervals
-/
lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩
lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩
lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub
lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb
lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq
lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq
lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above
lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below
lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩
lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩
section
variables [linear_order γ] [densely_ordered γ]
lemma is_lub_Iio {a : γ} : is_lub (Iio a) a :=
⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩
lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a
lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq
lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq
end
/-!
#### Singleton
-/
lemma is_greatest_singleton : is_greatest {a} a :=
⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩
lemma is_least_singleton : is_least {a} a :=
@is_greatest_singleton (order_dual α) _ a
lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub
lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb
lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above
lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below
lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq
lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq
/-!
#### Bounded intervals
-/
lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩
lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self
lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self
lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self
lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b :=
⟨right_mem_Icc.2 h, λ x, and.right⟩
lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub
lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b :=
(is_lub_Icc h).upper_bounds_eq
lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a :=
⟨left_mem_Icc.2 h, λ x, and.left⟩
lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb
lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a :=
(is_glb_Icc h).lower_bounds_eq
lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b :=
⟨right_mem_Ioc.2 h, λ x, and.right⟩
lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b :=
(is_greatest_Ioc h).is_lub
lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b :=
(is_lub_Ioc h).upper_bounds_eq
lemma is_least_Ico (h : a < b) : is_least (Ico a b) a :=
⟨left_mem_Ico.2 h, λ x, and.left⟩
lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a :=
(is_least_Ico h).is_glb
lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a :=
(is_glb_Ico h).lower_bounds_eq
section
variables [linear_order γ] [densely_ordered γ]
lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a :=
begin
refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩,
letI := classical.DLO γ,
have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ },
rcases dense this with ⟨z, az, zy⟩,
rw lt_min_iff at zy,
exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2)
end
lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a :=
(is_glb_Ioo hab).lower_bounds_eq
lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a :=
(is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab)
Ioo_subset_Ioc_self Ioc_subset_Icc_self
lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a :=
(is_glb_Ioc hab).lower_bounds_eq
lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b :=
by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab
lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b :=
(is_lub_Ioo hab).upper_bounds_eq
lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b :=
by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab
lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b :=
(is_lub_Ico hab).upper_bounds_eq
end
lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl
lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl
lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b :=
by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici,
bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right]
/-!
### Univ
-/
lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} :=
set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩
mem_singleton_iff.symm
lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ :=
by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and]
lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ :=
is_greatest_univ.is_lub
lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} :=
@order_top.upper_bounds_univ (order_dual γ) _
lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ :=
@is_greatest_univ (order_dual γ) _
lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ :=
is_least_univ.is_glb
lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ :=
eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in
not_le_of_lt hx (hb trivial)
lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ :=
@no_top_order.upper_bounds_univ (order_dual α) _ _
/-!
### Empty set
-/
@[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ :=
by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff]
@[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ :=
by simp only [lower_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff]
@[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) :=
by simp only [bdd_above, upper_bounds_empty, univ_nonempty]
@[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) :=
by simp only [bdd_below, lower_bounds_empty, univ_nonempty]
lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) :=
by simp only [is_glb, lower_bounds_empty, is_greatest_univ]
lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) :=
@is_glb_empty (order_dual γ) _
lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty :=
let ⟨a', ha'⟩ := no_bot a in
ne_empty_iff_nonempty.1 $ assume h,
have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty],
not_le_of_lt ha' this
lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty :=
@is_lub.nonempty (order_dual α) _ _ _ _ hs
/-!
### insert
-/
/-- Adding a point to a set preserves its boundedness above. -/
@[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} :
bdd_above (insert a s) ↔ bdd_above s :=
by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and]
lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) :
bdd_above (insert a s) :=
(bdd_above_insert a).2 hs
/--Adding a point to a set preserves its boundedness below.-/
@[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} :
bdd_below (insert a s) ↔ bdd_below s :=
by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and]
lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) :
bdd_below (insert a s) :=
(bdd_below_insert a).2 hs
lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) :
is_lub (insert a s) (a ⊔ b) :=
by { rw insert_eq, exact is_lub_singleton.union hs }
lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) :
is_glb (insert a s) (a ⊓ b) :=
by { rw insert_eq, exact is_glb_singleton.union hs }
lemma is_greatest.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) :
is_greatest (insert a s) (max a b) :=
by { rw insert_eq, exact is_greatest_singleton.union hs }
lemma is_least.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) :
is_least (insert a s) (min a b) :=
by { rw insert_eq, exact is_least_singleton.union hs }
lemma upper_bounds_insert (a : α) (s : set α) :
upper_bounds (insert a s) = Ici a ∩ upper_bounds s :=
by rw [insert_eq, upper_bounds_union, upper_bounds_singleton]
lemma lower_bounds_insert (a : α) (s : set α) :
lower_bounds (insert a s) = Iic a ∩ lower_bounds s :=
by rw [insert_eq, lower_bounds_union, lower_bounds_singleton]
/-- When there is a global maximum, every set is bounded above. -/
@[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s :=
⟨⊤, assume a ha, order_top.le_top a⟩
/-- When there is a global minimum, every set is bounded below. -/
@[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s :=
⟨⊥, assume a ha, order_bot.bot_le a⟩
/-!
### Pair
-/
lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) :=
by { rw sup_comm, exact is_lub_singleton.insert _}
lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) :=
by { rw inf_comm, exact is_glb_singleton.insert _ }
lemma is_least_pair [decidable_linear_order γ] {a b : γ} : is_least {a, b} (min a b) :=
by { rw min_comm, exact is_least_singleton.insert _ }
lemma is_greatest_pair [decidable_linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) :=
by { rw max_comm, exact is_greatest_singleton.insert _ }
end
/-!
### (In)equalities with the least upper bound and the greatest lower bound
-/
section preorder
variables [preorder α] {s : set α} {a b : α}
lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) :
s.nonempty → a ≤ b
| ⟨c, hc⟩ := le_trans (ha hc) (hb hc)
lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b :=
lower_bounds_le_upper_bounds ha.1 hb.1 hs
lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b :=
⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩
lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c :=
@is_lub_lt_iff (order_dual α) _ s _ _ ha
end preorder
section partial_order
variables [partial_order α] {s : set α} {a b : α}
lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b :=
le_antisymm (Ha.right Hb.left) (Hb.right Ha.left)
lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b :=
le_antisymm (Hb.right Ha.left) (Ha.right Hb.left)
lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b :=
Ha.unique Hb
lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b :=
Ha.unique Hb
lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s :=
by { rw h.upper_bounds_eq, refl }
lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s :=
by { rw h.lower_bounds_eq, refl }
end partial_order
section linear_order
variables [linear_order α] {s : set α} {a b : α}
lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c :=
by haveI := classical.dec;
simpa [upper_bounds, not_ball] using
not_congr (@is_lub_le_iff _ _ _ _ b h)
lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b :=
@lt_is_lub_iff (order_dual α) _ _ _ _ h
end linear_order
/-!
### Images of upper/lower bounds under monotone functions
-/
namespace monotone
variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α}
lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) :
f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) :
f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
/-- The image under a monotone function of a set which is bounded above is bounded above. -/
lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩
/-- The image under a monotone function of a set which is bounded below is bounded below. -/
lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩
/-- A monotone map sends a least element of a set to a least element of its image. -/
lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩
/-- A monotone map sends a greatest element of a set to a greatest element of its image. -/
lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩
lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) :
b ≤ f a :=
Hb.2 (Hf.mem_upper_bounds_image Ha.1)
lemma le_is_glb_image_le (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) :
f a ≤ b :=
Hb.2 (Hf.mem_lower_bounds_image Ha.1)
end monotone
|
916711ab7d7f703a80d79e0a16f6331a3f348481 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/category_theory/eq_to_hom.lean | a3bd236b32a8c2748443641591cc8e59ed2b0ab2 | [
"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 | 2,675 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison
-/
import category_theory.isomorphism
import category_theory.functor_category
import category_theory.opposites
import tactic.reassoc_axiom
universes v v' u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
open opposite
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _
@[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl
@[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) :
eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) :=
by cases p; cases q; simp
def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y :=
⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩
@[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p :=
rfl
@[simp] lemma eq_to_iso_refl (X : C) (p : X = X) : eq_to_iso p = iso.refl X := rfl
@[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) :
eq_to_iso p ≪≫ eq_to_iso q = eq_to_iso (p.trans q) :=
by ext; simp
@[simp] lemma eq_to_hom_op (X Y : C) (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) :=
begin
cases h,
refl
end
variables {D : Type u'} [𝒟 : category.{v'} D]
include 𝒟
namespace functor
/-- Proving equality between functors. This isn't an extensionality lemma,
because usually you don't really want to do this. -/
lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X)
(h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) :
F = G :=
begin
cases F with F_obj _ _ _, cases G with G_obj _ _ _,
have : F_obj = G_obj, by ext X; apply h_obj,
subst this,
congr,
funext X Y f,
simpa using h_map X Y f
end
-- Using equalities between functors.
lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X :=
by subst h
lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) :
F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm :=
by subst h; simp
end functor
lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) :
F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) :=
by cases p; simp
lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) :
F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) :=
by ext; cases p; simp
lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) :
(eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) :=
by subst h; refl
end category_theory
|
a300a089a3b08ce154cabb44eb843d97fc8a77be | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/group_theory/group_action.lean | 128ab00b6ca3597dbac76d66e6db2f5ad41a9c4c | [
"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,117 | 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.set.finite group_theory.coset
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ)
infixr ` • `:73 := has_scalar.smul
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Typeclass for multiplictive actions by monoids. This generalizes group actions. -/
class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β :=
(one_smul : ∀ b : β, (1 : α) • b = b)
(mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b)
end prio
section
variables [monoid α] [mul_action α β]
theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _
lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm
lemma smul_comm {α : Type u} {β : Type v} [comm_monoid α] [mul_action α β] (a₁ a₂ : α) (b : β) :
a₁ • a₂ • b = a₂ • a₁ • b := by rw [←mul_smul, ←mul_smul, mul_comm]
variable (α)
@[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _
variables {α} (p : Prop) [decidable p]
lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) :=
by split_ifs; refl
lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) :=
by split_ifs; refl
end
namespace mul_action
variables (α) [monoid α] [mul_action α β]
def orbit (b : β) := set.range (λ x : α, x • b)
variable {α}
@[simp] lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ :=
iff.rfl
@[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b :=
⟨x, rfl⟩
@[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b :=
⟨1, by simp [mul_action.one_smul]⟩
instance orbit_fintype (b : β) [fintype α] [decidable_eq β] :
fintype (orbit α b) := set.fintype_range _
variable (α)
def stabilizer (b : β) : set α :=
{x : α | x • b = b}
variable {α}
@[simp] lemma mem_stabilizer_iff {b : β} {x : α} :
x ∈ stabilizer α b ↔ x • b = b := iff.rfl
variables (α) (β)
def fixed_points : set β := {b : β | ∀ x, x ∈ stabilizer α b}
variables {α} (β)
@[simp] lemma mem_fixed_points {b : β} :
b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl
lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔
(∀ b', b' ∈ orbit α b → b' = b) :=
⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x,
λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩
def comp_hom [monoid γ] (g : γ → α) [is_monoid_hom g] :
mul_action γ β :=
{ smul := λ x b, (g x) • b,
one_smul := by simp [is_monoid_hom.map_one g, mul_action.one_smul],
mul_smul := by simp [is_monoid_hom.map_mul g, mul_action.mul_smul] }
instance (b : β) : is_submonoid (stabilizer α b) :=
{ one_mem := one_smul b,
mul_mem := λ a a' (ha : a • b = b) (hb : a' • b = b),
by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] }
end mul_action
namespace mul_action
variables [group α] [mul_action α β]
section
open mul_action quotient_group
variables (α) (β)
def to_perm (g : α) : equiv.perm β :=
{ to_fun := (•) g,
inv_fun := (•) g⁻¹,
left_inv := λ a, by rw [← mul_action.mul_smul, inv_mul_self, mul_action.one_smul],
right_inv := λ a, by rw [← mul_action.mul_smul, mul_inv_self, mul_action.one_smul] }
variables {α} {β}
instance : is_group_hom (to_perm α β) :=
{ map_mul := λ x y, equiv.ext _ _ (λ a, mul_action.mul_smul x y a) }
lemma bijective (g : α) : function.bijective (λ b : β, g • b) :=
(to_perm α β g).bijective
lemma orbit_eq_iff {a b : β} :
orbit α a = orbit α b ↔ a ∈ orbit α b:=
⟨λ h, h ▸ mem_orbit_self _,
λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x,
show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩,
λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹,
show (y * x⁻¹) • a = c, by
conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc,
mul_action.mul_smul, hx]}⟩⟩)⟩
instance (b : β) : is_subgroup (stabilizer α b) :=
{ one_mem := mul_action.one_smul _,
mul_mem := λ x y (hx : x • b = b) (hy : y • b = b),
show (x * y) • b = b, by rw mul_action.mul_smul; simp *,
inv_mem := λ x (hx : x • b = b), show x⁻¹ • b = b,
by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx] }
variables (α) (β)
def orbit_rel : setoid β :=
{ r := λ a b, a ∈ orbit α b,
iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm],
λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ }
variables {β}
open quotient_group
noncomputable def orbit_equiv_quotient_stabilizer (b : β) :
orbit α b ≃ quotient (stabilizer α b) :=
equiv.symm (@equiv.of_bijective _ _
(λ x : quotient (stabilizer α b), quotient.lift_on' x
(λ x, (⟨x • b, mem_orbit _ _⟩ : orbit α b))
(λ g h (H : _ = _), subtype.eq $ (mul_action.bijective (g⁻¹)).1
$ show g⁻¹ • (g • b) = g⁻¹ • (h • b),
by rw [← mul_action.mul_smul, ← mul_action.mul_smul,
H, inv_mul_self, mul_action.one_smul]))
⟨λ g h, quotient.induction_on₂' g h (λ g h H, quotient.sound' $
have H : g • b = h • b := subtype.mk.inj H,
show (g⁻¹ * h) • b = b,
by rw [mul_action.mul_smul, ← H, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul]),
λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩)
end
open quotient_group mul_action is_subgroup
def mul_left_cosets (H : set α) [is_subgroup H]
(x : α) (y : quotient H) : quotient H :=
quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y))
(λ a b (hab : _ ∈ H), quotient_group.eq.2
(by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one]))
instance (H : set α) [is_subgroup H] : mul_action α (quotient H) :=
{ smul := mul_left_cosets H,
one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2
(by simp [is_submonoid.one_mem])),
mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2
(by simp [mul_inv_rev, is_submonoid.one_mem, mul_assoc])) }
instance mul_left_cosets_comp_subtype_val (H I : set α) [is_subgroup H] [is_subgroup I] :
mul_action I (quotient H) :=
mul_action.comp_hom (quotient H) (subtype.val : I → α)
end mul_action
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/
class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β :=
(smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y)
(smul_zero : ∀(r : α), r • (0 : β) = 0)
end prio
section
variables [monoid α] [add_monoid β] [distrib_mul_action α β]
theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ :=
distrib_mul_action.smul_add _ _ _
@[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 :=
distrib_mul_action.smul_zero _
instance distrib_mul_action.is_add_monoid_hom (r : α) :
is_add_monoid_hom ((•) r : β → β) :=
{ map_zero := smul_zero r,
map_add := smul_add r }
lemma list.smul_sum {r : α} {l : list β} :
r • l.sum = (l.map ((•) r)).sum :=
(list.sum_hom _ _).symm
end
section
variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β]
lemma multiset.smul_sum {r : α} {s : multiset β} :
r • s.sum = (s.map ((•) r)).sum :=
(multiset.sum_hom _ _).symm
lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} :
r • s.sum f = s.sum (λ x, r • f x) :=
(finset.sum_hom _ _).symm
end
|
cd8ec5f560c3cd24cb8c02007ed49a70ec311b38 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/algebra/algebra/basic.lean | d84eb9352c739769436245250f561ec0a7e78a40 | [
"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 | 52,967 | 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 algebra.iterate_hom
import data.equiv.ring_aut
import algebra.module.basic
import linear_algebra.basic
/-!
# Algebras over commutative semirings
In this file we define `algebra`s over commutative (semi)rings, algebra homomorphisms `alg_hom`,
and algebra equivalences `alg_equiv`.
We also define the usual operations on `alg_hom`s (`id`, `comp`).
`subalgebra`s are defined in `algebra.algebra.subalgebra`.
If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used
to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now
deprecated and replaced with `is_scalar_tower`.
For the category of `R`-algebras, denoted `Algebra R`, see the file
`algebra/category/Algebra/basic.lean`.
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
-/
universes u v w u₁ v₁
open_locale big_operators
section prio
-- We set this priority to 0 later in this file
set_option extends_priority 200 /- control priority of
`instance [algebra R A] : has_scalar R A` -/
/--
Given a commutative (semi)ring `R`, an `R`-algebra is a (possibly noncommutative)
(semi)ring `A` endowed with a morphism of rings `R →+* A` which lands in the
center of `A`.
For convenience, this typeclass extends `has_scalar R A` where the scalar action must
agree with left multiplication by the image of the structure morphism.
Given an `algebra R A` instance, the structure morphism `R →+* A` is denoted `algebra_map R A`.
-/
@[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,
to_ring_hom := 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 _
lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S]
(i : R →+* S) :
@algebra_map R S _ _ i.to_algebra = i :=
rfl
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w} {B : Type*}
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `module 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`.
See note [reducible non-instances]. -/
@[reducible]
def of_module' [comm_semiring R] [semiring A] [module 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 `module 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`.
See note [reducible non-instances]. -/
@[reducible]
def of_module [comm_semiring R] [semiring A] [module 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_module' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one])
section semiring
variables [comm_semiring R] [comm_semiring S]
variables [semiring A] [algebra R A] [semiring B] [algebra R B]
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
/--
To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree,
it suffices to check the `algebra_map`s agree.
-/
-- We'll later use this to show `algebra ℤ M` is a subsingleton.
@[ext]
lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A)
(w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } =
by { haveI := Q, exact algebra_map R A r }) :
P = Q :=
begin
unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ },
congr,
{ funext r a,
replace w := congr_arg (λ s, s * a) (w r),
simp only [←algebra.smul_def''] at w,
apply w, },
{ ext r,
exact w r, },
{ apply proof_irrel_heq, },
{ apply proof_irrel_heq, },
end
@[priority 200] -- see Note [lower instance priority]
instance to_module : module 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
lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 :=
calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm
... = r • 1 : (algebra.smul_def r 1).symm
lemma algebra_map_eq_smul_one' : ⇑(algebra_map R A) = λ r, r • (1 : A) :=
funext algebra_map_eq_smul_one
/-- `mul_comm` for `algebra`s when one element is from the base ring. -/
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
/-- `mul_left_comm` for `algebra`s when one element is from the base ring. -/
theorem left_comm (x : A) (r : R) (y : A) :
x * (algebra_map R A r * y) = algebra_map R A r * (x * y) :=
by rw [← mul_assoc, ← commutes, mul_assoc]
/-- `mul_right_comm` for `algebra`s when one element is from the base ring. -/
theorem right_comm (x : A) (r : R) (y : A) :
(x * algebra_map R A r) * y = (x * y) * algebra_map R A r :=
by rw [mul_assoc, commutes, ←mul_assoc]
instance _root_.is_scalar_tower.right : is_scalar_tower R A A :=
⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, smul_def, smul_def, mul_assoc]⟩
/-- This is just a special case of the global `mul_smul_comm` lemma that requires less typeclass
search (and was here first). -/
@[simp] protected lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
-- TODO: set up `is_scalar_tower.smul_comm_class` earlier so that we can actually prove this using
-- `mul_smul_comm s x y`.
by rw [smul_def, smul_def, left_comm]
/-- This is just a special case of the global `smul_mul_assoc` lemma that requires less typeclass
search (and was here first). -/
@[simp] protected lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
smul_mul_assoc r x y
section
variables {r : R} {a : A}
@[simp] lemma bit0_smul_one : bit0 r • (1 : A) = bit0 (r • (1 : A)) :=
by simp [bit0, add_smul]
lemma bit0_smul_one' : bit0 r • (1 : A) = r • 2 :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit1_smul_one : bit1 r • (1 : A) = bit1 (r • (1 : A)) :=
by simp [bit1, add_smul]
lemma bit1_smul_one' : bit1 r • (1 : A) = r • 2 + 1 :=
by simp [bit1, bit0, add_smul, smul_add]
@[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a :=
by simp [bit1, add_smul, smul_add]
@[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a :=
by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel }
end
variables (R A)
/--
The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`,
packaged as an `R`-linear map.
-/
protected def linear_map : R →ₗ[R] A :=
{ map_smul' := λ x y, by simp [algebra.smul_def],
..algebra_map R A }
@[simp]
lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl
instance id : algebra R R := (ring_hom.id R).to_algebra
variables {R A}
namespace id
@[simp] lemma map_eq_id : algebra_map R R = ring_hom.id _ := rfl
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
section prod
variables (R A B)
instance : algebra R (A × B) :=
{ commutes' := by { rintro r ⟨a, b⟩, dsimp, rw [commutes r a, commutes r b] },
smul_def' := by { rintro r ⟨a, b⟩, dsimp, rw [smul_def r a, smul_def r b] },
.. prod.module,
.. ring_hom.prod (algebra_map R A) (algebra_map R B) }
variables {R A B}
@[simp] lemma algebra_map_prod_apply (r : R) :
algebra_map R (A × B) r = (algebra_map R A r, algebra_map R B r) := rfl
end prod
/-- Algebra over a subsemiring. This builds upon `subsemiring.module`. -/
instance of_subsemiring (S : subsemiring R) : algebra S A :=
{ smul := (•),
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp S.subtype }
/-- Algebra over a subring. This builds upon `subring.module`. -/
instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A]
(S : subring R) : algebra S A :=
{ smul := (•),
.. algebra.of_subsemiring S.to_subsemiring,
.. (algebra_map R A).comp S.subtype }
lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S →+* R) = subring.subtype S := rfl
lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S → R) = subtype.val := rfl
lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) :
algebra_map S R x = x := rfl
/-- Explicit characterization of the submonoid map in the case of an algebra.
`S` is made explicit to help with type inference -/
def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S]
(M : submonoid R) : (submonoid S) :=
submonoid.map (algebra_map R S : R →* S) M
lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) :
(algebra_map R S x) ∈ algebra_map_submonoid S M :=
set.mem_image_of_mem (algebra_map R S) x.2
end semiring
section ring
variables [comm_ring R]
variables (R)
/-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure.
See note [reducible non-instances]. -/
@[reducible]
def semiring_to_ring [semiring A] [algebra R A] : ring A := {
..module.add_comm_monoid_to_add_comm_group R,
..(infer_instance : semiring A) }
variables {R}
lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) :
x * (x - algebra_map R A r) = (x - algebra_map R A r) * x :=
by rw [mul_sub, ←commutes, sub_mul]
lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) :
x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x :=
begin
induction n with n ih,
{ simp },
{ rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes,
mul_assoc, ih, ←mul_assoc], }
end
end ring
end algebra
namespace no_zero_smul_divisors
variables {R A : Type*}
open algebra
section ring
variables [comm_ring R]
/-- If `algebra_map R A` is injective and `A` has no zero divisors,
`R`-multiples in `A` are zero only if one of the factors is zero.
Cannot be an instance because there is no `injective (algebra_map R A)` typeclass.
-/
lemma of_algebra_map_injective
[semiring A] [algebra R A] [no_zero_divisors A]
(h : function.injective (algebra_map R A)) : no_zero_smul_divisors R A :=
⟨λ c x hcx, (mul_eq_zero.mp ((smul_def c x).symm.trans hcx)).imp_left
((algebra_map R A).injective_iff.mp h _)⟩
variables (R A)
lemma algebra_map_injective [ring A] [nontrivial A]
[algebra R A] [no_zero_smul_divisors R A] :
function.injective (algebra_map R A) :=
suffices function.injective (λ (c : R), c • (1 : A)),
by { convert this, ext, rw [algebra.smul_def, mul_one] },
smul_left_injective R one_ne_zero
variables {R A}
lemma iff_algebra_map_injective [ring A] [domain A] [algebra R A] :
no_zero_smul_divisors R A ↔ function.injective (algebra_map R A) :=
⟨@@no_zero_smul_divisors.algebra_map_injective R A _ _ _ _,
no_zero_smul_divisors.of_algebra_map_injective⟩
end ring
section field
variables [field R] [semiring A] [algebra R A]
@[priority 100] -- see note [lower instance priority]
instance algebra.no_zero_smul_divisors [nontrivial A] [no_zero_divisors A] :
no_zero_smul_divisors R A :=
no_zero_smul_divisors.of_algebra_map_injective (algebra_map R A).injective
end field
end no_zero_smul_divisors
namespace opposite
variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A]
instance : algebra R Aᵒᵖ :=
{ to_ring_hom := (algebra_map R A).to_opposite $ λ x y, algebra.commutes _ _,
smul_def' := λ c x, unop_injective $
by { dsimp, simp only [op_mul, algebra.smul_def, algebra.commutes, op_unop] },
commutes' := λ r, opposite.rec $ λ x, by dsimp; simp only [← op_mul, algebra.commutes],
..opposite.has_scalar A R }
@[simp] lemma algebra_map_apply (c : R) : algebra_map R Aᵒᵖ c = op (algebra_map R A c) := rfl
end opposite
namespace module
variables (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [module R M]
instance : algebra R (module.End R M) :=
algebra.of_module smul_mul_assoc (λ r f g, (smul_comm r f g).symm)
lemma algebra_map_End_eq_smul_id (a : R) :
(algebra_map R (End R M)) a = a • linear_map.id := rfl
@[simp] lemma algebra_map_End_apply (a : R) (m : M) :
(algebra_map R (End R M)) a m = a • m := rfl
@[simp] lemma ker_algebra_map_End (K : Type u) (V : Type v)
[field K] [add_comm_group V] [module K V] (a : K) (ha : a ≠ 0) :
((algebra_map K (End K V)) a).ker = ⊥ :=
linear_map.ker_smul _ _ ha
end module
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⟩
initialize_simps_projections alg_hom (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl
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
-- make the coercion the simp-normal form
@[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn :=
by { intros φ₁ φ₂ H, cases φ₁, cases φ₂, congr, exact H }
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x := H ▸ rfl
protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y := h ▸ rfl
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
coe_fn_injective $ funext H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x :=
⟨alg_hom.congr_fun, ext⟩
@[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) :
(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : (φ : A →+* B).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 ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) :=
φ.to_ring_hom.map_sum f s
lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.sum g) = f.sum (λ i a, φ (g i a)) :=
φ.map_sum _ _
@[simp] lemma map_nat_cast (n : ℕ) : φ n = n :=
φ.to_ring_hom.map_nat_cast n
@[simp] lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) :=
φ.to_ring_hom.map_bit0 x
@[simp] lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) :=
φ.to_ring_hom.map_bit1 x
/-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/
def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B :=
{ to_fun := f,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one],
.. f }
@[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
@[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl
@[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl
end
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 coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl
lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) :
⇑(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := 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
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ[R] B :=
{ to_fun := φ,
map_add' := φ.map_add,
map_smul' := φ.map_smul }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) :=
λ φ₁ φ₂ h, ext $ linear_map.congr_fun 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
@[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id :=
linear_map.ext $ λ _, rfl
/-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/
@[simps]
def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) :
A →ₐ[R] B :=
{ to_fun := f,
map_one' := map_one,
map_mul' := map_mul,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one],
.. f.to_add_monoid_hom }
@[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) :
of_linear_map φ.to_linear_map map_one map_mul = φ :=
by { ext, refl }
@[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) :
to_linear_map (of_linear_map f map_one map_mul) = f :=
by { ext, refl }
@[simp] lemma of_linear_map_id (map_one) (map_mul) :
of_linear_map linear_map.id map_one map_mul = alg_hom.id R A :=
ext $ λ _, rfl
lemma map_list_prod (s : list A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_list_prod s
section prod
/-- First projection as `alg_hom`. -/
def fst : A × B →ₐ[R] A :=
{ commutes' := λ r, rfl, .. ring_hom.fst A B}
/-- Second projection as `alg_hom`. -/
def snd : A × B →ₐ[R] B :=
{ commutes' := λ r, rfl, .. ring_hom.snd A B}
end prod
lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) :
algebra_map R B y = f x :=
h ▸ (f.commutes _).symm
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
lemma map_multiset_prod (s : multiset A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_multiset_prod s
lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) :=
φ.to_ring_hom.map_prod f s
lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.prod g) = f.prod (λ i a, φ (g i a)) :=
φ.map_prod _ _
end comm_semiring
section ring
variables [comm_semiring R] [ring A] [ring B]
variables [algebra R A] [algebra R B] (φ : 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
@[simp] lemma map_int_cast (n : ℤ) : φ n = n :=
φ.to_ring_hom.map_int_cast n
end ring
section division_ring
variables [comm_ring R] [division_ring A] [division_ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
@[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ :=
φ.to_ring_hom.map_inv x
@[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y :=
φ.to_ring_hom.map_div x y
end division_ring
theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B]
[algebra R A] [algebra R B] (f : A →ₐ[R] B) :
function.injective f ↔ (∀ x, f x = 0 → x = 0) :=
ring_hom.injective_iff (f : A →+* B)
end alg_hom
@[simp] lemma rat.smul_one_eq_coe {A : Type*} [division_ring A] [algebra ℚ A] (m : ℚ) :
m • (1 : A) = ↑m :=
by rw [algebra.smul_def, mul_one, ring_hom.eq_rat_cast]
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₁}
section semiring
variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃]
variables [algebra R A₁] [algebra R A₂] [algebra R A₃]
variables (e : A₁ ≃ₐ[R] A₂)
instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩
@[ext]
lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
protected lemma congr_arg {f : A₁ ≃ₐ[R] A₂} : Π {x x' : A₁}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x := h ▸ rfl
lemma ext_iff {f g : A₁ ≃ₐ[R] A₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) :=
begin
intros f g w,
ext,
exact congr_fun w a,
end
instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩
@[simp] lemma coe_mk {to_fun inv_fun left_inv right_inv map_mul map_add commutes} :
⇑(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = to_fun :=
rfl
@[simp] theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) :
(⟨e, e', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e := ext $ λ _, rfl
@[simp] lemma to_fun_eq_coe (e : A₁ ≃ₐ[R] A₂) : e.to_fun = e := rfl
-- TODO: decide on a simp-normal form so that only one of these two lemmas is needed
@[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl
@[simp] lemma coe_ring_equiv' : (e.to_ring_equiv : A₁ → A₂) = e := rfl
lemma coe_ring_equiv_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ ≃+* A₂)) :=
λ e₁ e₂ h, ext $ ring_equiv.congr_fun h
@[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add
@[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero
@[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul
@[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one
@[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r :=
e.commutes'
lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∑ x in s, f x) = ∑ x in s, e (f x) :=
e.to_add_equiv.map_sum f s
lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) :
e (f.sum g) = f.sum (λ i b, e (g i b)) :=
e.map_sum _ _
/-- Interpret an algebra equivalence as an algebra homomorphism.
This definition is included for symmetry with the other `to_*_hom` projections.
The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/
def to_alg_hom : A₁ →ₐ[R] A₂ :=
{ map_one' := e.map_one, map_zero' := e.map_zero, ..e }
instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) :=
⟨to_alg_hom⟩
@[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl
@[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e :=
rfl
lemma coe_alg_hom_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ →ₐ[R] A₂)) :=
λ e₁ e₂ h, ext $ alg_hom.congr_fun h
/-- The two paths coercion can take to a `ring_hom` are equivalent -/
lemma coe_ring_hom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) :=
rfl
@[simp] lemma map_pow : ∀ (x : A₁) (n : ℕ), e (x ^ n) = (e x) ^ n := e.to_alg_hom.map_pow
lemma injective : function.injective e := e.to_equiv.injective
lemma surjective : function.surjective e := e.to_equiv.surjective
lemma bijective : 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
@[simp] lemma refl_to_alg_hom : ↑(refl : A₁ ≃ₐ[R] A₁) = alg_hom.id R A₁ := rfl
@[simp] lemma coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id := rfl
/-- 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, }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ := e.symm
initialize_simps_projections alg_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp] lemma inv_fun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.inv_fun = e.symm := rfl
@[simp] lemma symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e :=
by { ext, refl, }
lemma symm_bijective : function.bijective (symm : (A₁ ≃ₐ[R] A₂) → (A₂ ≃ₐ[R] A₁)) :=
equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) :
(⟨f, e, h₁, h₂, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) :
(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm =
{ to_fun := f', inv_fun := f,
..(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm } := rfl
/-- 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
@[simp] lemma symm_trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₃) :
(e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl
@[simp] lemma coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) :
⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ :=
by { ext, simp }
@[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ :=
by { ext, simp }
theorem left_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.left_inverse e.symm e := e.left_inv
theorem right_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.right_inverse e.symm e := e.right_inv
/-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps
`A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/
def arrow_congr {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂']
(e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') :=
{ to_fun := λ f, (e₂.to_alg_hom.comp f).comp e₁.symm.to_alg_hom,
inv_fun := λ f, (e₂.symm.to_alg_hom.comp f).comp e₁.to_alg_hom,
left_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, symm_comp],
simp only [←alg_hom.comp_assoc, symm_comp, alg_hom.id_comp, alg_hom.comp_id] },
right_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, comp_symm],
simp only [←alg_hom.comp_assoc, comp_symm, alg_hom.id_comp, alg_hom.comp_id] } }
lemma arrow_congr_comp {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃']
[algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂')
(e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) :
arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) :=
by { ext, simp only [arrow_congr, equiv.coe_fn_mk, alg_hom.comp_apply],
congr, exact (e₂.symm_apply_apply _).symm }
@[simp] lemma arrow_congr_refl :
arrow_congr alg_equiv.refl alg_equiv.refl = equiv.refl (A₁ →ₐ[R] A₂) :=
by { ext, refl }
@[simp] lemma arrow_congr_trans {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃']
[algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂')
(e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
by { ext, refl }
@[simp] lemma arrow_congr_symm {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂']
[algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
by { ext, refl }
/-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/
def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂)
(h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ :=
{ to_fun := f,
inv_fun := g,
left_inv := alg_hom.ext_iff.1 h₂,
right_inv := alg_hom.ext_iff.1 h₁,
..f }
lemma coe_alg_hom_of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
↑(of_alg_hom f g h₁ h₂) = f := alg_hom.ext $ λ _, rfl
@[simp]
lemma of_alg_hom_coe_alg_hom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
of_alg_hom ↑f g h₁ h₂ = f := ext $ λ _, rfl
lemma of_alg_hom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
(of_alg_hom f g h₁ h₂).symm = of_alg_hom g f h₂ h₁ := rfl
/-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/
noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ :=
{ .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f }
/-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/
@[simps apply] def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ :=
{ to_fun := e,
map_smul' := λ r x, by simp [algebra.smul_def''],
inv_fun := e.symm,
.. e }
@[simp] lemma to_linear_equiv_refl :
(alg_equiv.refl : A₁ ≃ₐ[R] A₁).to_linear_equiv = linear_equiv.refl R A₁ := rfl
@[simp] lemma to_linear_equiv_symm (e : A₁ ≃ₐ[R] A₂) :
e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_linear_equiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) :
(e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := rfl
theorem to_linear_equiv_injective : function.injective (to_linear_equiv : _ → (A₁ ≃ₗ[R] A₂)) :=
λ e₁ e₂ h, ext $ linear_equiv.congr_fun h
/-- Interpret an algebra equivalence as a linear map. -/
def to_linear_map : A₁ →ₗ[R] A₂ :=
e.to_alg_hom.to_linear_map
@[simp] lemma to_alg_hom_to_linear_map :
(e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_equiv_to_linear_map :
e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl
theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A₁ →ₗ[R] A₂)) :=
λ e₁ e₂ h, ext $ linear_map.congr_fun h
@[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) :
(f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
section of_linear_equiv
variables (l : A₁ ≃ₗ[R] A₂)
(map_mul : ∀ x y : A₁, l (x * y) = l x * l y)
(commutes : ∀ r : R, l (algebra_map R A₁ r) = algebra_map R A₂ r)
/--
Upgrade a linear equivalence to an algebra equivalence,
given that it distributes over multiplication and action of scalars.
-/
@[simps apply]
def of_linear_equiv : A₁ ≃ₐ[R] A₂ :=
{ to_fun := l,
inv_fun := l.symm,
map_mul' := map_mul,
commutes' := commutes,
..l }
@[simp]
lemma of_linear_equiv_symm :
(of_linear_equiv l map_mul commutes).symm = of_linear_equiv l.symm
((of_linear_equiv l map_mul commutes).symm.map_mul)
((of_linear_equiv l map_mul commutes).symm.commutes) :=
rfl
@[simp] lemma of_linear_equiv_to_linear_equiv (map_mul) (commutes) :
of_linear_equiv e.to_linear_equiv map_mul commutes = e :=
by { ext, refl }
@[simp] lemma to_linear_equiv_of_linear_equiv :
to_linear_equiv (of_linear_equiv l map_mul commutes) = l :=
by { ext, refl }
end of_linear_equiv
instance aut : group (A₁ ≃ₐ[R] A₁) :=
{ mul := λ ϕ ψ, ψ.trans ϕ,
mul_assoc := λ ϕ ψ χ, rfl,
one := 1,
one_mul := λ ϕ, by { ext, refl },
mul_one := λ ϕ, by { ext, refl },
inv := symm,
mul_left_inv := λ ϕ, by { ext, exact symm_apply_apply ϕ a } }
@[simp] lemma mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) := rfl
/-- An algebra isomorphism induces a group isomorphism between automorphism groups -/
@[simps apply]
def aut_congr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* (A₂ ≃ₐ[R] A₂) :=
{ to_fun := λ ψ, ϕ.symm.trans (ψ.trans ϕ),
inv_fun := λ ψ, ϕ.trans (ψ.trans ϕ.symm),
left_inv := λ ψ, by { ext, simp_rw [trans_apply, symm_apply_apply] },
right_inv := λ ψ, by { ext, simp_rw [trans_apply, apply_symm_apply] },
map_mul' := λ ψ χ, by { ext, simp only [mul_apply, trans_apply, symm_apply_apply] } }
@[simp] lemma aut_congr_refl : aut_congr (alg_equiv.refl) = mul_equiv.refl (A₁ ≃ₐ[R] A₁) :=
by { ext, refl }
@[simp] lemma aut_congr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (aut_congr ϕ).symm = aut_congr ϕ.symm := rfl
@[simp] lemma aut_congr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) :
(aut_congr ϕ).trans (aut_congr ψ) = aut_congr (ϕ.trans ψ) := rfl
/-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`.
This generalizes `function.End.apply_mul_action`. -/
instance apply_mul_semiring_action : mul_semiring_action (A₁ ≃ₐ[R] A₁) A₁ :=
{ smul := ($),
smul_zero := alg_equiv.map_zero,
smul_add := alg_equiv.map_add,
smul_one := alg_equiv.map_one,
smul_mul := alg_equiv.map_mul,
one_smul := λ _, rfl,
mul_smul := λ _ _ _, rfl }
@[simp] protected lemma smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a := rfl
instance apply_has_faithful_scalar : has_faithful_scalar (A₁ ≃ₐ[R] A₁) A₁ :=
⟨λ _ _, alg_equiv.ext⟩
instance apply_smul_comm_class : smul_comm_class R (A₁ ≃ₐ[R] A₁) A₁ :=
{ smul_comm := λ r e a, (e.to_linear_equiv.map_smul r a).symm }
instance apply_smul_comm_class' : smul_comm_class (A₁ ≃ₐ[R] A₁) R A₁ :=
{ smul_comm := λ e r a, (e.to_linear_equiv.map_smul r a) }
@[simp] lemma algebra_map_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} :
(algebra_map R A₂ y = e x) ↔ (algebra_map R A₁ y = x) :=
⟨λ h, by simpa using e.symm.to_alg_hom.algebra_map_eq_apply h,
λ h, e.to_alg_hom.algebra_map_eq_apply h⟩
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
lemma map_prod {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∏ x in s, f x) = ∏ x in s, e (f x) :=
e.to_alg_hom.map_prod f s
lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) :
e (f.prod g) = f.prod (λ i a, e (g i a)) :=
e.to_alg_hom.map_finsupp_prod f g
end comm_semiring
section ring
variables [comm_ring R] [ring A₁] [ring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
@[simp] lemma map_neg (x) : e (-x) = -e x :=
e.to_alg_hom.map_neg x
@[simp] lemma map_sub (x y) : e (x - y) = e x - e y :=
e.to_alg_hom.map_sub x y
end ring
section division_ring
variables [comm_ring R] [division_ring A₁] [division_ring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
@[simp] lemma map_inv (x) : e (x⁻¹) = (e x)⁻¹ :=
e.to_alg_hom.map_inv x
@[simp] lemma map_div (x y) : e (x / y) = e x / e y :=
e.to_alg_hom.map_div x y
end division_ring
end alg_equiv
namespace mul_semiring_action
variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A]
section
variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A]
/-- Each element of the monoid defines a algebra homomorphism.
This is a stronger version of `mul_semiring_action.to_ring_hom` and
`distrib_mul_action.to_linear_map`. -/
@[simps]
def to_alg_hom (m : M) : A →ₐ[R] A :=
alg_hom.mk' (mul_semiring_action.to_ring_hom _ _ m) (smul_comm _)
theorem to_alg_hom_injective [has_faithful_scalar M A] :
function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r
end
section
variables [group G] [mul_semiring_action G A] [smul_comm_class G R A]
/-- Each element of the group defines a algebra equivalence.
This is a stronger version of `mul_semiring_action.to_ring_equiv` and
`distrib_mul_action.to_linear_equiv`. -/
@[simps]
def to_alg_equiv (g : G) : A ≃ₐ[R] A :=
{ .. mul_semiring_action.to_ring_equiv _ _ g,
.. mul_semiring_action.to_alg_hom R A g }
theorem to_alg_equiv_injective [has_faithful_scalar G A] :
function.injective (mul_semiring_action.to_alg_equiv R A : G → A ≃ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_equiv.ext_iff.1 h r
end
end mul_semiring_action
section nat
variables {R : Type*} [semiring R]
-- Lower the priority so that `algebra.id` is picked most of the time when working with
-- `ℕ`-algebras. This is only an issue since `algebra.id` and `algebra_nat` are not yet defeq.
-- TODO: fix this by adding an `of_nat` field to semirings.
/-- Semiring ⥤ ℕ-Alg -/
@[priority 99] instance algebra_nat : algebra ℕ R :=
{ commutes' := nat.cast_commute,
smul_def' := λ _ _, nsmul_eq_mul _ _,
to_ring_hom := nat.cast_ring_hom R }
instance nat_algebra_subsingleton : subsingleton (algebra ℕ R) :=
⟨λ P Q, by { ext, simp, }⟩
end nat
namespace ring_hom
variables {R S : Type*}
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) :
R →ₐ[ℕ] S :=
{ to_fun := f, commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) :
R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp, .. f }
@[simp] lemma map_rat_algebra_map [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S)
(r : ℚ) :
f (algebra_map ℚ R r) = algebra_map ℚ S r :=
ring_hom.ext_iff.1 (subsingleton.elim (f.comp (algebra_map ℚ R)) (algebra_map ℚ S)) r
/-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. -/
def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) :
R →ₐ[ℚ] S :=
{ commutes' := f.map_rat_algebra_map, .. f }
end ring_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x
@[simp] theorem algebra_map_rat_rat : algebra_map ℚ ℚ = ring_hom.id ℚ :=
subsingleton.elim _ _
-- TODO[gh-6025]: make this an instance once safe to do so
lemma algebra_rat_subsingleton {α} [semiring α] :
subsingleton (algebra ℚ α) :=
⟨λ x y, algebra.algebra_ext x y $ ring_hom.congr_fun $ subsingleton.elim _ _⟩
end rat
namespace char_zero
variables {R : Type*} (S : Type*) [comm_semiring R] [semiring S] [algebra R S]
lemma of_algebra [char_zero S] : char_zero R :=
⟨begin
suffices : function.injective (algebra_map R S ∘ coe),
{ exact this.of_comp },
convert char_zero.cast_injective,
ext n,
rw [function.comp_app, ← (algebra_map ℕ _).eq_nat_cast, ← ring_hom.comp_apply,
ring_hom.eq_nat_cast],
all_goals { apply_instance }
end⟩
end char_zero
namespace algebra
open module
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
/-- `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
section int
variables (R : Type*) [ring R]
-- Lower the priority so that `algebra.id` is picked most of the time when working with
-- `ℤ`-algebras. This is only an issue since `algebra.id ℤ` and `algebra_int ℤ` are not yet defeq.
-- TODO: fix this by adding an `of_int` field to rings.
/-- Ring ⥤ ℤ-Alg -/
@[priority 99] instance algebra_int : algebra ℤ R :=
{ commutes' := int.cast_commute,
smul_def' := λ _ _, gsmul_eq_mul _ _,
to_ring_hom := int.cast_ring_hom R }
variables {R}
instance int_algebra_subsingleton : subsingleton (algebra ℤ R) :=
⟨λ P Q, by { ext, simp, }⟩
end int
/-!
The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra.
We couldn't set this up back in `algebra.pi_instances` because this file imports it.
-/
namespace pi
variable {I : Type u} -- The indexing type
variable {R : Type*} -- The scalar type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
variables (I f)
instance algebra {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] :
algebra R (Π i : I, f i) :=
{ commutes' := λ a f, begin ext, simp [algebra.commutes], end,
smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end,
..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) }
@[simp] lemma algebra_map_apply {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) :
algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl
-- One could also build a `Π i, R i`-algebra structure on `Π i, A i`,
-- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful.
variables {I} (R) (f)
/-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`,
etc. -/
@[simps]
def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) :
(Π i, f i) →ₐ[R] f i :=
{ to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i}
variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B]
/-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`,
etc. -/
@[simps]
def const_alg_hom : B →ₐ[R] (A → B) :=
{ to_fun := function.const _,
commutes' := λ r, rfl,
.. pi.const_ring_hom A B}
/-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that
map. -/
@[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) :=
rfl
@[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) :=
rfl
end pi
section is_scalar_tower
variables {R : Type*} [comm_semiring R]
variables (A : Type*) [semiring A] [algebra R A]
variables {M : Type*} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M]
variables {N : Type*} [add_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N]
lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m :=
by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul]
@[simp] lemma algebra_map_smul (r : R) (m : M) : ((algebra_map R A) r) • m = r • m :=
(algebra_compatible_smul A r m).symm
variable {A}
@[priority 100] -- see Note [lower instance priority]
instance is_scalar_tower.to_smul_comm_class : smul_comm_class R A M :=
⟨λ r a m, by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul,
←algebra_compatible_smul]⟩
@[priority 100] -- see Note [lower instance priority]
instance is_scalar_tower.to_smul_comm_class' : smul_comm_class A R M :=
smul_comm_class.symm _ _ _
lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m :=
smul_comm _ _ _
namespace linear_map
instance coe_is_scalar_tower : has_coe (M →ₗ[A] N) (M →ₗ[R] N) :=
⟨restrict_scalars R⟩
variables (R) {A M N}
@[simp, norm_cast squash] lemma coe_restrict_scalars_eq_coe (f : M →ₗ[A] N) :
(f.restrict_scalars R : M → N) = f := rfl
@[simp, norm_cast squash] lemma coe_coe_is_scalar_tower (f : M →ₗ[A] N) :
((f : M →ₗ[R] N) : M → N) = f := rfl
/-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over
a commutative semiring `R` and `M` a module over `R`. -/
def lto_fun (R : Type u) (M : Type v) (A : Type w)
[comm_semiring R] [add_comm_monoid M] [module R M] [comm_ring A] [algebra R A] :
(M →ₗ[R] A) →ₗ[A] (M → A) :=
{ to_fun := linear_map.to_fun,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
end linear_map
end is_scalar_tower
/-! TODO: The following lemmas no longer involve `algebra` at all, and could be moved closer
to `algebra/module/submodule.lean`. Currently this is tricky because `ker`, `range`, `⊤`, and `⊥`
are all defined in `linear_algebra/basic.lean`. -/
section module
open module
variables (R S M N : Type*) [semiring R] [semiring S] [has_scalar R S]
variables [add_comm_monoid M] [module R M] [module S M] [is_scalar_tower R S M]
variables [add_comm_monoid N] [module R N] [module S N] [is_scalar_tower R S N]
variables {S M N}
namespace submodule
variables (R S M)
/-- If `S` is an `R`-algebra, then the `R`-module generated by a set `X` is included in the
`S`-module generated by `X`. -/
lemma span_le_restrict_scalars (X : set M) : span R (X : set M) ≤ restrict_scalars R (span S X) :=
submodule.span_le.mpr submodule.subset_span
end submodule
@[simp]
lemma linear_map.ker_restrict_scalars (f : M →ₗ[S] N) :
(f.restrict_scalars R).ker = f.ker.restrict_scalars R :=
rfl
end module
namespace submodule
variables (R A M : Type*)
variables [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M]
variables [module R M] [module A M] [is_scalar_tower R A M]
/-- If `A` is an `R`-algebra such that the induced morhpsim `R →+* A` is surjective, then the
`R`-module generated by a set `X` equals the `A`-module generated by `X`. -/
lemma span_eq_restrict_scalars (X : set M) (hsur : function.surjective (algebra_map R A)) :
span R X = restrict_scalars R (span A X) :=
begin
apply (span_le_restrict_scalars R A M X).antisymm (λ m hm, _),
refine span_induction hm subset_span (zero_mem _) (λ _ _, add_mem _) (λ a m hm, _),
obtain ⟨r, rfl⟩ := hsur a,
simpa [algebra_map_smul] using smul_mem _ r hm
end
end submodule
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {I : Type*}
variables [comm_semiring R] [semiring A] [semiring B]
variables [algebra R A] [algebra R B]
/-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an
`R`-algebra homomorphism `f` between `A` and `B`. -/
@[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) :=
{ to_fun := λ h, f ∘ h,
commutes' := λ c, by { ext, exact f.commutes' c },
.. f.to_ring_hom.comp_left I }
end alg_hom
|
7f84155f1ca1ac388286fdeb418886f7f7bf16f5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/calculus/fderiv_analytic.lean | 59431d132384c12ed4988e893149aa771d63073c | [
"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,315 | 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.analytic.basic
import analysis.calculus.deriv.basic
import analysis.calculus.cont_diff_def
/-!
# Frechet derivatives of analytic functions.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A function expressible as a power series at a point has a Frechet derivative there.
Also the special case in terms of `deriv` when the domain is 1-dimensional.
-/
open filter asymptotics
open_locale ennreal
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
section fderiv
variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞}
variables {f : E → F} {x : E} {s : set E}
lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) :
has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
begin
refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _),
refine is_o_iff_exists_eq_mul.2 ⟨λ y, ‖y - (x, x)‖, _, eventually_eq.rfl⟩,
refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _,
rw [_root_.id, sub_self, norm_zero]
end
lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
h.has_strict_fderiv_at.has_fderiv_at
lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x
| ⟨p, hp⟩ := hp.differentiable_at
lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma has_fpower_series_at.fderiv_eq (h : has_fpower_series_at f p x) :
fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) :=
h.has_fderiv_at.fderiv
lemma has_fpower_series_on_ball.differentiable_on [complete_space F]
(h : has_fpower_series_on_ball f p x r) :
differentiable_on 𝕜 f (emetric.ball x r) :=
λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at
lemma analytic_on.differentiable_on (h : analytic_on 𝕜 f s) :
differentiable_on 𝕜 f s :=
λ y hy, (h y hy).differentiable_within_at
lemma has_fpower_series_on_ball.has_fderiv_at [complete_space F]
(h : has_fpower_series_on_ball f p x r) {y : E} (hy : (‖y‖₊ : ℝ≥0∞) < r) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1)) (x + y) :=
(h.change_origin hy).has_fpower_series_at.has_fderiv_at
lemma has_fpower_series_on_ball.fderiv_eq [complete_space F]
(h : has_fpower_series_on_ball f p x r) {y : E} (hy : (‖y‖₊ : ℝ≥0∞) < r) :
fderiv 𝕜 f (x + y) = continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1) :=
(h.has_fderiv_at hy).fderiv
/-- If a function has a power series on a ball, then so does its derivative. -/
lemma has_fpower_series_on_ball.fderiv [complete_space F]
(h : has_fpower_series_on_ball f p x r) :
has_fpower_series_on_ball (fderiv 𝕜 f)
((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F))
.comp_formal_multilinear_series (p.change_origin_series 1)) x r :=
begin
suffices A : has_fpower_series_on_ball
(λ z, continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin (z - x) 1))
((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F))
.comp_formal_multilinear_series (p.change_origin_series 1)) x r,
{ apply A.congr,
assume z hz,
dsimp,
rw [← h.fderiv_eq, add_sub_cancel'_right],
simpa only [edist_eq_coe_nnnorm_sub, emetric.mem_ball] using hz},
suffices B : has_fpower_series_on_ball (λ z, p.change_origin (z - x) 1)
(p.change_origin_series 1) x r,
from (continuous_multilinear_curry_fin1 𝕜 E F).to_continuous_linear_equiv
.to_continuous_linear_map.comp_has_fpower_series_on_ball B,
simpa using ((p.has_fpower_series_on_ball_change_origin 1 (h.r_pos.trans_le h.r_le)).mono
h.r_pos h.r_le).comp_sub x,
end
/-- If a function is analytic on a set `s`, so is its Fréchet derivative. -/
lemma analytic_on.fderiv [complete_space F] (h : analytic_on 𝕜 f s) :
analytic_on 𝕜 (fderiv 𝕜 f) s :=
begin
assume y hy,
rcases h y hy with ⟨p, r, hp⟩,
exact hp.fderiv.analytic_at,
end
/-- If a function is analytic on a set `s`, so are its successive Fréchet derivative. -/
lemma analytic_on.iterated_fderiv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) :
analytic_on 𝕜 (iterated_fderiv 𝕜 n f) s :=
begin
induction n with n IH,
{ rw iterated_fderiv_zero_eq_comp,
exact ((continuous_multilinear_curry_fin0 𝕜 E F).symm : F →L[𝕜] (E [×0]→L[𝕜] F))
.comp_analytic_on h },
{ rw iterated_fderiv_succ_eq_comp_left,
apply (continuous_multilinear_curry_left_equiv 𝕜 (λ (i : fin (n + 1)), E) F)
.to_continuous_linear_equiv.to_continuous_linear_map.comp_analytic_on,
exact IH.fderiv }
end
/-- An analytic function is infinitely differentiable. -/
lemma analytic_on.cont_diff_on [complete_space F] (h : analytic_on 𝕜 f s) {n : ℕ∞} :
cont_diff_on 𝕜 n f s :=
begin
let t := {x | analytic_at 𝕜 f x},
suffices : cont_diff_on 𝕜 n f t, from this.mono h,
have H : analytic_on 𝕜 f t := λ x hx, hx,
have t_open : is_open t := is_open_analytic_at 𝕜 f,
apply cont_diff_on_of_continuous_on_differentiable_on,
{ assume m hm,
apply (H.iterated_fderiv m).continuous_on.congr,
assume x hx,
exact iterated_fderiv_within_of_is_open _ t_open hx },
{ assume m hm,
apply (H.iterated_fderiv m).differentiable_on.congr,
assume x hx,
exact iterated_fderiv_within_of_is_open _ t_open hx }
end
end fderiv
section deriv
variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞}
variables {f : 𝕜 → F} {x : 𝕜} {s : set 𝕜}
protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) :
has_strict_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_fderiv_at.has_strict_deriv_at
protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) :
has_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_deriv_at.has_deriv_at
protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) :
deriv f x = p 1 (λ _, 1) :=
h.has_deriv_at.deriv
/-- If a function is analytic on a set `s`, so is its derivative. -/
lemma analytic_on.deriv [complete_space F] (h : analytic_on 𝕜 f s) :
analytic_on 𝕜 (deriv f) s :=
(continuous_linear_map.apply 𝕜 F (1 : 𝕜)).comp_analytic_on h.fderiv
/-- If a function is analytic on a set `s`, so are its successive derivatives. -/
lemma analytic_on.iterated_deriv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) :
analytic_on 𝕜 (deriv^[n] f) s :=
begin
induction n with n IH,
{ exact h },
{ simpa only [function.iterate_succ', function.comp_app] using IH.deriv }
end
end deriv
|
c82a8878956b3ed6f53c0e0243ef194ce2225831 | 274748215b6d042f0d9c9a505f9551fa8e0c5f38 | /src/topology/noetherian.lean | 4c8176da053346861024b24f06e04a0d7e9958ad | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/M4P33 | 878ecb515c77d20cc799ff1ebd78f1bf4fd65c12 | 1a179372db71ad6802d11eacbc1f02f327d55f8f | refs/heads/master | 1,607,519,867,193 | 1,583,344,297,000 | 1,583,344,297,000 | 233,316,107 | 59 | 4 | Apache-2.0 | 1,579,285,778,000 | 1,578,788,367,000 | Lean | UTF-8 | Lean | false | false | 10,236 | lean | /-
Noetherian topological spaces
-/
-- this import gives us irreducible topological spaces
import topology.subset_properties
-- this gives us the type of open sets in a top space
import topology.opens
open set
open_locale classical
@[simp]
lemma irred_iff_not_union_closed {X : Type*} [topological_space X] (Y : set X) :
is_irreducible Y ↔ Y.nonempty ∧ ∀ C₁ C₂ : set X,
is_closed C₁ → is_closed C₂ → Y ⊆ C₁ ∪ C₂ → Y ⊆ C₁ ∨ Y ⊆ C₂ :=
begin
split,
{ rintro ⟨h0, h⟩,
split, exact h0,
rwa ←is_preirreducible_iff_closed_union_closed,
},
{ rintro ⟨h0, h⟩,
split, assumption,
rwa is_preirreducible_iff_closed_union_closed,
}
end
/-- A non-empty Y is irreducible iff every non-empty open subset of Y is dense -/
lemma irred_iff_nonempty_open_dense {X : Type*} [topological_space X] (Y : set X):
is_irreducible Y ↔ Y.nonempty ∧
∀ U₁ U₂ : set X, is_open U₁ → is_open U₂ →
(Y ∩ U₁).nonempty → (Y ∩ U₂).nonempty → (Y ∩ (U₁ ∩ U₂)).nonempty := iff.rfl
/-
Corollary 5.3. Let S be a irreducible topological space and U ⊆ S a non-empty
open subset. Then U is irreducible (in the subspace topology).
-/
lemma open_irred {X : Type*} [topological_space X]
(S : set X) (hiS : is_irreducible S) (V : set X) (hV : is_open V) :
(V ∩ S).nonempty → is_irreducible (V ∩ S) :=
begin
rintro ⟨x, hx⟩,
rw irred_iff_nonempty_open_dense,
split, use x, assumption,
intros U₁ U₂ oU₁ oU₂ hne₁ hne₂,
rw irred_iff_nonempty_open_dense at hiS,
rcases hiS with ⟨h3, h4⟩,
replace h4 := h4 (V ∩ U₁) (V ∩ U₂)
(is_open_inter hV oU₁) (is_open_inter hV oU₂),
convert h4 (by convert hne₁ using 1; ac_refl) (by convert hne₂ using 1; ac_refl) using 1,
ext, split; finish,
end
/-
A topological space is Noetherian if it satisfies the descending chain
condition for open subsets
Alternatively, we have upwards induction on closed sets.
-/
namespace topological_space
open_locale classical
variables {X : Type*} [topological_space X]
instance for_ken : partial_order (closeds X) := subtype.partial_order _
def is_noetherian (X : Type*) [topological_space X] : Prop :=
well_founded ((<) : closeds X → closeds X → Prop)
-- factorises means expressable as finite union of closed irreducibles.
def factorises {X : Type*} [topological_space X] (C : closeds X) :=
∃ ι : finset (set X), sUnion (↑ι : set _) = C.1 ∧
(∀ Ci ∈ ι, is_irreducible Ci) ∧ (∀ Ci ∈ ι, is_closed Ci)
lemma inter_ssubet_of_not_subset {X : Type*} {A B : set X}
(A_not_sub_B : ¬ A ⊆ B) : A ∩ B ⊂ A := ⟨inter_subset_left _ _,
not_subset.2 $ let ⟨a,a_in_A,a_not_in_B⟩ := not_subset.1 A_not_sub_B in
⟨a,a_in_A, λ a_in_A_inter_B, a_not_in_B a_in_A_inter_B.2⟩
⟩
lemma eq_union_inter_of_subset_union {X : Type*} {A B C : set X}
(A_subset_B_union_C : A ⊆ B ∪ C) : A = (A ∩ B) ∪ (A ∩ C) :=
inter_distrib_left A B C ▸ eq_of_subset_of_subset
(subset_inter (subset.refl _) (A_subset_B_union_C))
(inter_subset_left _ _)
lemma induction_step {X : Type*} [topological_space X]
{Y : set X} (Y_closed : is_closed Y)
(Y_not_irreducible : ¬ is_irreducible Y) :
Y = ∅ ∨
∃ C1 C2 : set X, is_closed C1 ∧ is_closed C2 ∧ Y = C1 ∪ C2 ∧ C1 < Y ∧ C2 < Y
:= begin
cases (classical.em (Y.nonempty)) with Y_nonempty Y_not_nonempty,
-- Case of Y nonempty,
apply or.inr,
simp at Y_not_irreducible, -- Tell lean to expand on Y not irreducible.
have not_forall, from Y_not_irreducible Y_nonempty,
push_neg at not_forall, -- Makes the not forall statement usable.
rcases not_forall with ⟨X1, X2, X1_closed, X2_closed,
Y_subset_X1_union_X2, not_Y_subset_X1, not_Y_subset_X2⟩,
use Y ∩ X1, use Y ∩ X2, -- These are the desired two closed sets.
split, exact (is_closed_inter Y_closed X1_closed), -- Y ∩ X1 closed
split, exact (is_closed_inter Y_closed X2_closed), -- Y ∩ X2 closed
split, exact eq_union_inter_of_subset_union Y_subset_X1_union_X2, -- Y = Y ∩ X1 ∪ Y ∩ X2
split, exact (inter_ssubet_of_not_subset not_Y_subset_X1), -- Y ∩ X1 ⊂ Y
exact (inter_ssubet_of_not_subset not_Y_subset_X2), -- Y ∩ X2 ⊂ Y
-- Case of Y empty
apply or.inl,
apply eq_empty_iff_forall_not_mem.2,
apply forall_not_of_not_exists Y_not_nonempty,
end
/-- In a Noetherian top space X,
every closed subset C can be "factorised",
that is expressable as a finite union of irreducible closed subsets C_i.
Note that emptyset has a factorisation, the empty union,
analogous to 1 being empty product of primes. --/
theorem finite_union_irreducibles {X : Type*} [topological_space X]
(X_noetherian : is_noetherian X) :
∀ C : closeds X, factorises C :=
-- We prove factorisation of closed sets by induction.
@well_founded.fix _ (λ C : closeds X, factorises C) _ X_noetherian $
-- Let Y be a closed set of X, and assume the induction hypothesis,
-- all closed sets strictly smaller than Y factorises.
λ Y : closeds X, λ induction_hypothesis,
-- We do cases on whether Y is irreducible.
or.elim (classical.em (is_irreducible Y.1))
(-- Case of Y being irreducible.
λ Y_irreducible,
-- Since Y is irreducible, Y gives a factorisation of Y.
⟨{Y.1}, -- The finset containing only
sUnion_singleton Y.1, -- Proof that union of sets in {Y} is Y.
-- Proof that everything in {Y} is irreducible.
λ (Y1 : set X) Y1_in_finset, -- Take a set in {Y}
have Y1_eq_Y : Y1 = Y.1, from eq_of_mem_singleton Y1_in_finset,
Y1_eq_Y.symm ▸ Y_irreducible, -- Y1 = Y is irreducible, so done.
-- Proof that everything in {Y} is irreducible.
λ (Y1 : set X) Y1_in_finset, -- Take a set in {Y}
have Y1_eq_Y : Y1 = Y.1, from eq_of_mem_singleton Y1_in_finset,
Y1_eq_Y.symm ▸ Y.2, -- Y1 = Y is closed, so done.
⟩
)
(-- Case of Y being not irreducible.
λ Y_not_irreducible,
-- If Y is not irreducible,
-- it is empty or union of two strictly smaller closed sets.
or.elim (induction_step Y.2 Y_not_irreducible)
(λ Y_empty, -- If Y is empty, empty union works.
⟨ ∅,
Y_empty.symm ▸ sUnion_empty, -- Empty union is empty
λ C C_in_empty_finset, -- Everything in empty set is irreducible
begin cases C_in_empty_finset, end,
λ C C_in_empty_finset, -- Everything in empty set is closed
begin cases C_in_empty_finset, end,
⟩)
(-- Let C1, C2 be two closed sets that union to Y,
-- but are strictly smaller than Y.
λ ⟨C1, C2, C1_closed, C2_closed, Y_eq_C1_union_C2,
C1_ssub_Y, C2_ssub_Y⟩,
have C1_factorises : factorises ⟨C1,C1_closed⟩,
from induction_hypothesis ⟨C1,C1_closed⟩ C1_ssub_Y,
have C2_factorises : factorises ⟨C2,C2_closed⟩,
from induction_hypothesis ⟨C2,C2_closed⟩ C2_ssub_Y,
let ⟨ι1, union_ι1_eq_C1, ι1_irr, ι1_closed⟩ := C1_factorises in
let ⟨ι2, union_ι2_eq_C2, ι2_irr, ι2_closed⟩ := C2_factorises in
⟨-- the factorisation of Y is the union of factorisation of C1, C2.
ι1 ∪ ι2, -- the factorisation
calc ⋃₀ (↑(ι1 ∪ ι2) : set _)-- Proof of union of factorisations is Y
= ⋃₀ ( (↑ι1 : set _) ∪ (↑ι2 : set _) ) : by simp
... = ⋃₀ ι1.to_set ∪ ⋃₀ ι2.to_set : sUnion_union _ _
... = C1 ∪ ⋃₀ finset.to_set ι2 : union_ι1_eq_C1.symm ▸ rfl
... = C1 ∪ C2 : union_ι2_eq_C2.symm ▸ rfl
... = Y.1 : Y_eq_C1_union_C2.symm,
λ (Ci : set X) (Ci_in_ι1_union_ι2), -- Proof of "factors" irreducible
or.elim (finset.mem_union.1 Ci_in_ι1_union_ι2)
(λ Ci_in_ι1, ι1_irr Ci Ci_in_ι1)
(λ Ci_in_ι2, ι2_irr Ci Ci_in_ι2),
λ (Ci : set X) (Ci_in_ι1_union_ι2), -- Proof of "factors" closed
or.elim (finset.mem_union.1 Ci_in_ι1_union_ι2)
(λ Ci_in_ι1, ι1_closed Ci Ci_in_ι1)
(λ Ci_in_ι2, ι2_closed Ci Ci_in_ι2)
⟩
)
)
end topological_space
/-
Hartshorne 1.5: in a Noetherian top space X, every nonempty closed subset Y
can be expressed as a finite union of irred closed subsets Y_i. If we
require that Y_i ¬⊆ Y_j for i ≠ j then the Y_i are uniquely determined.
They're called the irred cpts of Y.
-/
/-
Proof: existence: the set of non-empty closed subsets which can't be written
as a finite union of irreds is empty because it can't have a minimal
member.
Throwing away some Y_i we can assume i ≠ j → ¬ Y_i ⊆ Y_j.
Now say we have 2 reps . Then Z_1 ⊆ ∪ Y_j so Z_1 = ∪ (Z_1 ∩ Y_j), but
Z_1 is irred so Z_1 ⊆ Y_j for some j. Similarly Y_j ⊆ Z_k so k=1
and now replacing Y by the closure of Y - Z_1 we're done by induction on
the number of Z_i
-/
namespace topological_space
def closeds.compl {X : Type*} [topological_space X] : closeds X → opens X :=
λ C, ⟨-C.1, is_open_compl_iff.2 C.2⟩
def opens.compl {X : Type*} [topological_space X] : opens X → closeds X :=
λ C, ⟨-C.1, is_closed_compl_iff.2 C.2⟩
lemma continuous.subtype {X : Type*} [topological_space X] {Y : set X} :
continuous (subtype.val : Y → X) := λ U hU, ⟨U, hU, rfl⟩
def closeds.comap {X : Type*} [topological_space X] (Y : set X) :
closeds X → closeds Y :=
λ C, (continuous.subtype.comap (C.compl)).compl
lemma is_noetherian_subset (X : Type*) [topological_space X]
(hX : is_noetherian X) (Y : set X) : is_noetherian Y :=
begin
sorry
end
end topological_space
/-
Proposition 5.4. Let V be an affine algebraic set. Then:
(1) The union of the irreducible components of V is all of V .
(2) V has only finitely many irreducible components.
Lemma 5.5. Every affine algebraic set can be written as a union of finitely many
irreducible closed subsets.
Proposition 5.6. Let V be an affine algebraic set. Write V = V 1 ∪ · · · ∪ V r , where
the V i are irreducible closed subsets and ¬ V i ⊆ V j for ¬ i = j.
Then V 1 , . . . , V r are precisely the irreducible components of V .
-/
|
62e1d7aa785453f47380f4e4fa65b668f448237a | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world05/level05.lean | f7baab4ce47e12a97badfc9d2c8f9a9ac5833f42 | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 79 | lean | example (P Q : Type) : P → (Q → P) :=
begin
intro p,
intro q,
exact p,
end
|
33d7a4dfce0fc3066595b8d569fe3aeca9229319 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/sheaves/sheaf_condition/unique_gluing.lean | 2a57389de3247ea8c5dea4ebb708a99502c3dcd4 | [
"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 | 11,612 | lean | /-
Copyright (c) 2021 Justus Springer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Justus Springer
-/
import topology.sheaves.forget
import category_theory.limits.shapes.types
import topology.sheaves.sheaf
import category_theory.types
/-!
# The sheaf condition in terms of unique gluings
We provide an alternative formulation of the sheaf condition in terms of unique gluings.
We work with sheaves valued in a concrete category `C` admitting all limits, whose forgetful
functor `C ⥤ Type` preserves limits and reflects isomorphisms. The usual categories of algebraic
structures, such as `Mon`, `AddCommGroup`, `Ring`, `CommRing` etc. are all examples of this kind of
category.
A presheaf `F : presheaf C X` satisfies the sheaf condition if and only if, for every
compatible family of sections `sf : Π i : ι, F.obj (op (U i))`, there exists a unique gluing
`s : F.obj (op (supr U))`.
Here, the family `sf` is called compatible, if for all `i j : ι`, the restrictions of `sf i`
and `sf j` to `U i ⊓ U j` agree. A section `s : F.obj (op (supr U))` is a gluing for the
family `sf`, if `s` restricts to `sf i` on `U i` for all `i : ι`
We show that the sheaf condition in terms of unique gluings is equivalent to the definition
in terms of equalizers. Our approach is as follows: First, we show them to be equivalent for
`Type`-valued presheaves. Then we use that composing a presheaf with a limit-preserving and
isomorphism-reflecting functor leaves the sheaf condition invariant, as shown in
`topology/sheaves/forget.lean`.
-/
noncomputable theory
open Top
open Top.presheaf
open Top.presheaf.sheaf_condition_equalizer_products
open category_theory
open category_theory.limits
open topological_space
open topological_space.opens
open opposite
universes u v
variables {C : Type u} [category.{v} C] [concrete_category.{v} C]
namespace Top
namespace presheaf
section
local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun
variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X)
/--
A family of sections `sf` is compatible, if the restrictions of `sf i` and `sf j` to `U i ⊓ U j`
agree, for all `i` and `j`
-/
def is_compatible (sf : Π i : ι, F.obj (op (U i))) : Prop :=
∀ i j : ι, F.map (inf_le_left (U i) (U j)).op (sf i) = F.map (inf_le_right (U i) (U j)).op (sf j)
/--
A section `s` is a gluing for a family of sections `sf` if it restricts to `sf i` on `U i`,
for all `i`
-/
def is_gluing (sf : Π i : ι, F.obj (op (U i))) (s : F.obj (op (supr U))) : Prop :=
∀ i : ι, F.map (opens.le_supr U i).op s = sf i
/--
The sheaf condition in terms of unique gluings. A presheaf `F : presheaf C X` satisfies this sheaf
condition if and only if, for every compatible family of sections `sf : Π i : ι, F.obj (op (U i))`,
there exists a unique gluing `s : F.obj (op (supr U))`.
We prove this to be equivalent to the usual one below in
`is_sheaf_iff_is_sheaf_unique_gluing`
-/
def is_sheaf_unique_gluing : Prop :=
∀ ⦃ι : Type v⦄ (U : ι → opens X) (sf : Π i : ι, F.obj (op (U i))),
is_compatible F U sf → ∃! s : F.obj (op (supr U)), is_gluing F U sf s
end
section type_valued
variables {X : Top.{v}} (F : presheaf (Type v) X) {ι : Type v} (U : ι → opens X)
/--
For presheaves of types, terms of `pi_opens F U` are just families of sections.
-/
def pi_opens_iso_sections_family : pi_opens F U ≅ Π i : ι, F.obj (op (U i)) :=
limits.is_limit.cone_point_unique_up_to_iso
(limit.is_limit (discrete.functor (λ i : ι, F.obj (op (U i)))))
((types.product_limit_cone (λ i : ι, F.obj (op (U i)))).is_limit)
/--
Under the isomorphism `pi_opens_iso_sections_family`, compatibility of sections is the same
as being equalized by the arrows `left_res` and `right_res` of the equalizer diagram.
-/
lemma compatible_iff_left_res_eq_right_res (sf : pi_opens F U) :
is_compatible F U ((pi_opens_iso_sections_family F U).hom sf)
↔ left_res F U sf = right_res F U sf :=
begin
split ; intros h,
{ ext ⟨i, j⟩,
rw [left_res, types.limit.lift_π_apply', fan.mk_π_app,
right_res, types.limit.lift_π_apply', fan.mk_π_app],
exact h i j, },
{ intros i j,
convert congr_arg (limits.pi.π (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) (i,j)) h,
{ rw [left_res, types.pi_lift_π_apply], refl },
{ rw [right_res, types.pi_lift_π_apply], refl } }
end
/--
Under the isomorphism `pi_opens_iso_sections_family`, being a gluing of a family of
sections `sf` is the same as lying in the preimage of `res` (the leftmost arrow of the
equalizer diagram).
-/
@[simp]
lemma is_gluing_iff_eq_res (sf : pi_opens F U) (s : F.obj (op (supr U))):
is_gluing F U ((pi_opens_iso_sections_family F U).hom sf) s ↔ res F U s = sf :=
begin
split ; intros h,
{ ext ⟨i⟩,
rw [res, types.limit.lift_π_apply', fan.mk_π_app],
exact h i, },
{ intro i,
convert congr_arg (limits.pi.π (λ i : ι, F.obj (op (U i))) i) h,
rw [res, types.pi_lift_π_apply],
refl },
end
/--
The "equalizer" sheaf condition can be obtained from the sheaf condition
in terms of unique gluings.
-/
lemma is_sheaf_of_is_sheaf_unique_gluing_types (Fsh : F.is_sheaf_unique_gluing) :
F.is_sheaf :=
begin
rw is_sheaf_iff_is_sheaf_equalizer_products,
intros ι U,
refine ⟨fork.is_limit.mk' _ _⟩,
intro s,
have h_compatible : ∀ x : s.X,
F.is_compatible U ((F.pi_opens_iso_sections_family U).hom (s.ι x)),
{ intro x,
rw compatible_iff_left_res_eq_right_res,
convert congr_fun s.condition x, },
choose m m_spec m_uniq using
λ x : s.X, Fsh U ((pi_opens_iso_sections_family F U).hom (s.ι x)) (h_compatible x),
refine ⟨m, _, _⟩,
{ ext ⟨i⟩ x,
simp [res],
exact m_spec x i, },
{ intros l hl,
ext x,
apply m_uniq,
rw is_gluing_iff_eq_res,
exact congr_fun hl x },
end
/--
The sheaf condition in terms of unique gluings can be obtained from the usual
"equalizer" sheaf condition.
-/
lemma is_sheaf_unique_gluing_of_is_sheaf_types (Fsh : F.is_sheaf) :
F.is_sheaf_unique_gluing :=
begin
rw is_sheaf_iff_is_sheaf_equalizer_products at Fsh,
intros ι U sf hsf,
let sf' := (pi_opens_iso_sections_family F U).inv sf,
have hsf' : left_res F U sf' = right_res F U sf',
{ rwa [← compatible_iff_left_res_eq_right_res F U sf', inv_hom_id_apply] },
choose s s_spec s_uniq using types.unique_of_type_equalizer _ _ (Fsh U).some sf' hsf',
use s,
dsimp,
split,
{ convert (is_gluing_iff_eq_res F U sf' _).mpr s_spec,
rw inv_hom_id_apply },
{ intros y hy,
apply s_uniq,
rw ← is_gluing_iff_eq_res F U,
convert hy,
rw inv_hom_id_apply, },
end
/--
For type-valued presheaves, the sheaf condition in terms of unique gluings is equivalent to the
usual sheaf condition in terms of equalizer diagrams.
-/
lemma is_sheaf_iff_is_sheaf_unique_gluing_types :
F.is_sheaf ↔ F.is_sheaf_unique_gluing :=
iff.intro (is_sheaf_unique_gluing_of_is_sheaf_types F)
(is_sheaf_of_is_sheaf_unique_gluing_types F)
end type_valued
section
local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun
variables [has_limits C] [reflects_isomorphisms (forget C)] [preserves_limits (forget C)]
variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X)
/--
For presheaves valued in a concrete category, whose forgetful functor reflects isomorphisms and
preserves limits, the sheaf condition in terms of unique gluings is equivalent to the usual one
in terms of equalizer diagrams.
-/
lemma is_sheaf_iff_is_sheaf_unique_gluing :
F.is_sheaf ↔ F.is_sheaf_unique_gluing :=
iff.trans (is_sheaf_iff_is_sheaf_comp (forget C) F)
(is_sheaf_iff_is_sheaf_unique_gluing_types (F ⋙ forget C))
end
end presheaf
namespace sheaf
open presheaf
open category_theory
section
local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun
variables [has_limits C] [reflects_isomorphisms (concrete_category.forget C)]
variables [preserves_limits (concrete_category.forget C)]
variables {X : Top.{v}} (F : sheaf C X) {ι : Type v} (U : ι → opens X)
/--
A more convenient way of obtaining a unique gluing of sections for a sheaf.
-/
lemma exists_unique_gluing (sf : Π i : ι, F.1.obj (op (U i)))
(h : is_compatible F.1 U sf ) :
∃! s : F.1.obj (op (supr U)), is_gluing F.1 U sf s :=
(is_sheaf_iff_is_sheaf_unique_gluing F.1).mp F.cond U sf h
/--
In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user,
which can be more convenient in practice.
-/
lemma exists_unique_gluing' (V : opens X) (iUV : Π i : ι, U i ⟶ V) (hcover : V ≤ supr U)
(sf : Π i : ι, F.1.obj (op (U i))) (h : is_compatible F.1 U sf) :
∃! s : F.1.obj (op V), ∀ i : ι, F.1.map (iUV i).op s = sf i :=
begin
have V_eq_supr_U : V = supr U := le_antisymm hcover (supr_le (λ i, (iUV i).le)),
obtain ⟨gl, gl_spec, gl_uniq⟩ := F.exists_unique_gluing U sf h,
refine ⟨F.1.map (eq_to_hom V_eq_supr_U).op gl, _, _⟩,
{ intro i,
rw [← comp_apply, ← F.1.map_comp],
exact gl_spec i },
{ intros gl' gl'_spec,
convert congr_arg _ (gl_uniq (F.1.map (eq_to_hom V_eq_supr_U.symm).op gl') (λ i,_)) ;
rw [← comp_apply, ← F.1.map_comp],
{ rw [eq_to_hom_op, eq_to_hom_op, eq_to_hom_trans, eq_to_hom_refl,
F.1.map_id, id_apply] },
{ convert gl'_spec i } }
end
@[ext]
lemma eq_of_locally_eq (s t : F.1.obj (op (supr U)))
(h : ∀ i, F.1.map (opens.le_supr U i).op s = F.1.map (opens.le_supr U i).op t) :
s = t :=
begin
let sf : Π i : ι, F.1.obj (op (U i)) := λ i, F.1.map (opens.le_supr U i).op s,
have sf_compatible : is_compatible _ U sf,
{ intros i j, simp_rw [← comp_apply, ← F.1.map_comp], refl },
obtain ⟨gl, -, gl_uniq⟩ := F.exists_unique_gluing U sf sf_compatible,
transitivity gl,
{ apply gl_uniq, intro i, refl },
{ symmetry, apply gl_uniq, intro i, rw ← h },
end
/--
In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user,
which can be more convenient in practice.
-/
lemma eq_of_locally_eq' (V : opens X) (iUV : Π i : ι, U i ⟶ V) (hcover : V ≤ supr U)
(s t : F.1.obj (op V))
(h : ∀ i, F.1.map (iUV i).op s = F.1.map (iUV i).op t) : s = t :=
begin
have V_eq_supr_U : V = supr U := le_antisymm hcover (supr_le (λ i, (iUV i).le)),
suffices : F.1.map (eq_to_hom V_eq_supr_U.symm).op s =
F.1.map (eq_to_hom V_eq_supr_U.symm).op t,
{ convert congr_arg (F.1.map (eq_to_hom V_eq_supr_U).op) this ;
rw [← comp_apply, ← F.1.map_comp, eq_to_hom_op, eq_to_hom_op, eq_to_hom_trans,
eq_to_hom_refl, F.1.map_id, id_apply] },
apply eq_of_locally_eq,
intro i,
rw [← comp_apply, ← comp_apply, ← F.1.map_comp],
convert h i,
end
lemma eq_of_locally_eq₂ {U₁ U₂ V : opens X}
(i₁ : U₁ ⟶ V) (i₂ : U₂ ⟶ V) (hcover : V ≤ U₁ ⊔ U₂)
(s t : F.1.obj (op V))
(h₁ : F.1.map i₁.op s = F.1.map i₁.op t)
(h₂ : F.1.map i₂.op s = F.1.map i₂.op t) : s = t :=
begin
classical,
fapply F.eq_of_locally_eq' (λ t : ulift bool, if t.1 then U₁ else U₂),
{ exact λ i, if h : i.1 then (eq_to_hom (if_pos h)) ≫ i₁ else (eq_to_hom (if_neg h)) ≫ i₂ },
{ refine le_trans hcover _, rw sup_le_iff, split,
{ convert le_supr (λ t : ulift bool, if t.1 then U₁ else U₂) (ulift.up true) },
{ convert le_supr (λ t : ulift bool, if t.1 then U₁ else U₂) (ulift.up false) } },
{ rintro ⟨_|_⟩; simp [h₁, h₂] }
end
end
end sheaf
end Top
|
6a5493cf118289f3495d950bc12b001bf6e4fcba | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /test/norm_cast_lemma_order.lean | 4ce15a39c8483c33c495e54494759ccefd20981f | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 647 | lean | import data.nat.cast tactic.norm_cast
constant ℝ : Type
@[instance] constant real.add_monoid : add_monoid ℝ
@[instance] constant real.has_one : has_one ℝ
-- set_option trace.simplify.rewrite true
set_option pp.notation false
set_option pp.numerals false
-- should work
#eval norm_cast.numeral_to_coe `(0 : ℝ)
#eval norm_cast.numeral_to_coe `(1 : ℝ)
#eval norm_cast.numeral_to_coe `(2 : ℝ)
#eval norm_cast.numeral_to_coe `(3 : ℝ)
#eval norm_cast.coe_to_numeral `((0 : ℕ) : ℝ)
#eval norm_cast.coe_to_numeral `((1 : ℕ) : ℝ)
#eval norm_cast.coe_to_numeral `((2 : ℕ) : ℝ)
#eval norm_cast.coe_to_numeral `((3 : ℕ) : ℝ)
|
263bf1c7bed5f56bbe9aca8ae549b77ef9908702 | 3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a | /leanpkg/leanpkg/resolve.lean | 60a1bc0d1f0f51feb576221a8c63bb716a7dadbe | [
"Apache-2.0"
] | permissive | praveenmunagapati/lean | 00c3b4496cef8e758396005013b9776bb82c4f56 | fc760f57d20e0a486d14bc8a08d89147b60f530c | refs/heads/master | 1,630,692,342,183 | 1,515,626,222,000 | 1,515,626,222,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,956 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
-/
import leanpkg.manifest system.io leanpkg.proc leanpkg.git
variable [io.interface]
namespace leanpkg
def assignment := list (string × string)
namespace assignment
def empty : assignment := []
def find : assignment → string → option string
| [] s := none
| ((k, v) :: kvs) s :=
if k = s then some v else find kvs s
def contains (a : assignment) (s : string) : bool :=
(a.find s).is_some
def insert (a : assignment) (k v : string) : assignment :=
if a.contains k then a else (k, v) :: a
def fold {α} (i : α) (f : α → string → string → α) : assignment → α :=
list.foldl (λ a ⟨k, v⟩, f a k v) i
end assignment
@[reducible] def solver := state_t assignment io
instance {α : Type} : has_coe (io α) (solver α) := ⟨state_t.lift⟩
def not_yet_assigned (d : string) : solver bool := do
assg ← state_t.read,
return $ ¬ assg.contains d
def resolved_path (d : string) : solver string := do
assg ← state_t.read,
some path ← return (assg.find d) | io.fail "",
return path
-- TODO(gabriel): directory existence testing
def dir_exists (d : string) : io bool := do
ch ← io.proc.spawn { cmd := "test", args := ["-d", d] },
ev ← io.proc.wait ch,
return $ ev = 0
-- TODO(gabriel): windows?
def resolve_dir (abs_or_rel : string) (base : string) : string :=
if abs_or_rel.front = '/' then
abs_or_rel -- absolute
else
base ++ "/" ++ abs_or_rel
def materialize (relpath : string) (dep : dependency) : solver unit :=
match dep.src with
| (source.path dir) := do
let depdir := resolve_dir dir relpath,
io.put_str_ln $ dep.name ++ ": using local path " ++ depdir,
state_t.modify $ λ assg, assg.insert dep.name depdir
| (source.git url rev) := do
let depdir := "_target/deps/" ++ dep.name,
already_there ← dir_exists depdir,
let checkout_action := (do
hash ← git_parse_origin_revision depdir rev,
exec_cmd {cmd := "git", args := ["checkout", "--detach", hash], cwd := depdir}),
(do guard already_there,
io.put_str_ln $ dep.name ++ ": trying to update " ++ depdir ++ " to revision " ++ rev,
checkout_action) <|>
(do guard already_there,
exec_cmd {cmd := "git", args := ["fetch"], cwd := depdir},
checkout_action) <|>
(do io.put_str_ln $ dep.name ++ ": cloning " ++ url ++ " to " ++ depdir,
exec_cmd {cmd := "rm", args := ["-rf", depdir]},
exec_cmd {cmd := "mkdir", args := ["-p", depdir]},
exec_cmd {cmd := "git", args := ["clone", url, depdir]},
checkout_action),
state_t.modify $ λ assg, assg.insert dep.name depdir
end
def solve_deps_core : ∀ (rel_path : string) (d : manifest) (max_depth : ℕ), solver unit
| _ _ 0 := io.fail "maximum dependency resolution depth reached"
| relpath d (max_depth + 1) := do
deps ← monad.filter (not_yet_assigned ∘ dependency.name) d.dependencies,
deps.mmap' (materialize relpath),
deps.mmap' $ λ dep, do
p ← resolved_path dep.name,
d' ← manifest.from_file $ p ++ "/" ++ "leanpkg.toml",
when (d'.name ≠ dep.name) $
io.fail $ d.name ++ " (in " ++ relpath ++ ") depends on " ++ d'.name ++
", but resolved dependency has name " ++ dep.name ++ " (in " ++ p ++ ")",
solve_deps_core p d' max_depth
def solve_deps (d : manifest) : io assignment := do
(_, assg) ← solve_deps_core "." d 1024 $ assignment.empty.insert d.name ".",
return assg
def construct_path_core (depname : string) (dirname : string) : io (list string) :=
list.map (λ relpath, dirname ++ "/" ++ relpath) <$>
manifest.effective_path <$> (manifest.from_file $ dirname ++ "/" ++ leanpkg_toml_fn)
def construct_path (assg : assignment) : io (list string) := do
let assg := assg.fold [] (λ xs depname dirname, (depname, dirname) :: xs),
list.join <$> (assg.mmap $ λ ⟨depname, dirname⟩, construct_path_core depname dirname)
end leanpkg
|
9ef71401a769b098e9633697ee23dcb9f22f5423 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Compiler/IR/Borrow.lean | 71c49ebc3985ad7da109275d98201ddfea9b7151 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 11,063 | 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.Compiler.ExportAttr
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.NormIds
namespace Lean
namespace IR
namespace Borrow
namespace OwnedSet
abbrev Key := FunId × Index
def beq : Key → Key → Bool
| (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂
instance : BEq Key := ⟨beq⟩
def getHash : Key → UInt64
| (f, x) => mixHash (hash f) (hash x)
instance : Hashable Key := ⟨getHash⟩
end OwnedSet
open OwnedSet (Key) in
abbrev OwnedSet := Std.HashMap Key Unit
def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := Std.HashMap.insert s k ()
def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := Std.HashMap.contains s k
/- We perform borrow inference in a block of mutually recursive functions.
Join points are viewed as local functions, and are identified using
their local id + the name of the surrounding function.
We keep a mapping from function and joint points to parameters (`Array Param`).
Recall that `Param` contains the field `borrow`. -/
namespace ParamMap
inductive Key where
| decl (name : FunId)
| jp (name : FunId) (jpid : JoinPointId)
deriving BEq
def getHash : Key → UInt64
| Key.decl n => hash n
| Key.jp n id => mixHash (hash n) (hash id)
instance : Hashable Key := ⟨getHash⟩
end ParamMap
open ParamMap (Key)
abbrev ParamMap := Std.HashMap Key (Array Param)
def ParamMap.fmt (map : ParamMap) : Format :=
let fmts := map.fold (fun fmt k ps =>
let k := match k with
| ParamMap.Key.decl n => format n
| ParamMap.Key.jp n id => format n ++ ":" ++ format id
fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps)
Format.nil
"{" ++ (Format.nest 1 fmts) ++ "}"
instance : ToFormat ParamMap := ⟨ParamMap.fmt⟩
instance : ToString ParamMap := ⟨fun m => Format.pretty (format m)⟩
namespace InitParamMap
/- Mark parameters that take a reference as borrow -/
def initBorrow (ps : Array Param) : Array Param :=
ps.map $ fun p => { p with borrow := p.ty.isObj }
/- We do perform borrow inference for constants marked as `export`.
Reason: we current write wrappers in C++ for using exported functions.
These wrappers use smart pointers such as `object_ref`.
When writing a new wrapper we need to know whether an argument is a borrow
inference or not.
We can revise this decision when we implement code for generating
the wrappers automatically. -/
def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param :=
if exported then ps else initBorrow ps
partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit
| FnBody.jdecl j xs v b => do
modify fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs)
visitFnBody fnid v
visitFnBody fnid b
| FnBody.case _ _ _ alts => alts.forM fun alt => visitFnBody fnid alt.body
| e => do
unless e.isTerminal do
let (instr, b) := e.split
visitFnBody fnid b
def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit :=
decls.forM fun decl => match decl with
| Decl.fdecl (f := f) (xs := xs) (body := b) .. => do
let exported := isExport env f
modify fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs)
visitFnBody f b
| _ => pure ()
end InitParamMap
def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap :=
(InitParamMap.visitDecls env decls *> get).run' {}
/- Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually
recursive functions. -/
namespace ApplyParamMap
partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody
| FnBody.jdecl j xs v b =>
let v := visitFnBody fn paramMap v
let b := visitFnBody fn paramMap b
match paramMap.find? (ParamMap.Key.jp fn j) with
| some ys => FnBody.jdecl j ys v b
| none => unreachable!
| FnBody.case tid x xType alts =>
FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody (visitFnBody fn paramMap)
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split
let b := visitFnBody fn paramMap b
instr.setBody b
def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl :=
decls.map fun decl => match decl with
| Decl.fdecl f xs ty b info =>
let b := visitFnBody f paramMap b
match paramMap.find? (ParamMap.Key.decl f) with
| some xs => Decl.fdecl f xs ty b info
| none => unreachable!
| other => other
end ApplyParamMap
def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl :=
-- dbgTrace ("applyParamMap " ++ toString map) $ fun _ =>
ApplyParamMap.visitDecls decls map
structure BorrowInfCtx where
env : Environment
currFn : FunId := arbitrary -- Function being analyzed.
paramSet : IndexSet := {} -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams`
structure BorrowInfState where
/- Set of variables that must be `owned`. -/
owned : OwnedSet := {}
modified : Bool := false
paramMap : ParamMap
abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState)
def getCurrFn : M FunId := do
let ctx ← read
pure ctx.currFn
def markModified : M Unit :=
modify fun s => { s with modified := true }
def ownVar (x : VarId) : M Unit := do
-- dbgTrace ("ownVar " ++ toString x) $ fun _ =>
let currFn ← getCurrFn
modify fun s =>
if s.owned.contains (currFn, x.idx) then s
else { s with owned := s.owned.insert (currFn, x.idx), modified := true }
def ownArg (x : Arg) : M Unit :=
match x with
| Arg.var x => ownVar x
| _ => pure ()
def ownArgs (xs : Array Arg) : M Unit :=
xs.forM ownArg
def isOwned (x : VarId) : M Bool := do
let currFn ← getCurrFn
let s ← get
pure $ s.owned.contains (currFn, x.idx)
/- Updates `map[k]` using the current set of `owned` variables. -/
def updateParamMap (k : ParamMap.Key) : M Unit := do
let currFn ← getCurrFn
let s ← get
match s.paramMap.find? k with
| some ps => do
let ps ← ps.mapM fun (p : Param) => do
if !p.borrow then pure p
else if (← isOwned p.x) then
markModified
pure { p with borrow := false }
else
pure p
modify fun s => { s with paramMap := s.paramMap.insert k ps }
| none => pure ()
def getParamInfo (k : ParamMap.Key) : M (Array Param) := do
let s ← get
match s.paramMap.find? k with
| some ps => pure ps
| none =>
match k with
| ParamMap.Key.decl fn => do
let ctx ← read
match findEnvDecl ctx.env fn with
| some decl => pure decl.params
| none => unreachable!
| _ => unreachable!
/- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/
def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit :=
xs.size.forM fun i => do
let x := xs[i]
let p := ps[i]
unless p.borrow do ownArg x
/- For each xs[i], if xs[i] is owned, then mark ps[i] as owned.
We use this action to preserve tail calls. That is, if we have
a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned
we would have to insert a `dec xs[i]` after `f xs` and consequently
"break" the tail call. -/
def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit :=
xs.size.forM fun i => do
let x := xs[i]
let p := ps[i]
match x with
| Arg.var x => if (← isOwned x) then ownVar p.x
| _ => pure ()
/- Mark `xs[i]` as owned if it is one of the parameters `ps`.
We use this action to mark function parameters that are being "packed" inside constructors.
This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization.
It is useful for code such as
```
def f (x y : obj) :=
let z := ctor_1 x y;
ret z
```
-/
def ownArgsIfParam (xs : Array Arg) : M Unit := do
let ctx ← read
xs.forM fun x => do
match x with
| Arg.var x => if ctx.paramSet.contains x.idx then ownVar x
| _ => pure ()
def collectExpr (z : VarId) : Expr → M Unit
| Expr.reset _ x => ownVar z *> ownVar x
| Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys
| Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs
| Expr.proj _ x => do
if (← isOwned x) then ownVar z
if (← isOwned z) then ownVar x
| Expr.fap g xs => do
let ps ← getParamInfo (ParamMap.Key.decl g)
ownVar z *> ownArgsUsingParams xs ps
| Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys
| Expr.pap _ xs => ownVar z *> ownArgs xs
| other => pure ()
def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do
let ctx ← read
match v, b with
| (Expr.fap g ys), (FnBody.ret (Arg.var z)) =>
if ctx.currFn == g && x == z then
-- dbgTrace ("preserveTailCall " ++ toString b) $ fun _ => do
let ps ← getParamInfo (ParamMap.Key.decl g)
ownParamsUsingArgs ys ps
| _, _ => pure ()
def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx :=
{ ctx with paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet }
partial def collectFnBody : FnBody → M Unit
| FnBody.jdecl j ys v b => do
withReader (fun ctx => updateParamSet ctx ys) (collectFnBody v)
let ctx ← read
updateParamMap (ParamMap.Key.jp ctx.currFn j)
collectFnBody b
| FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b
| FnBody.jmp j ys => do
let ctx ← read
let ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j)
ownArgsUsingParams ys ps -- for making sure the join point can reuse
ownParamsUsingArgs ys ps -- for making sure the tail call is preserved
| FnBody.case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body
| e => do unless e.isTerminal do collectFnBody e.body
partial def collectDecl : Decl → M Unit
| Decl.fdecl (f := f) (xs := ys) (body := b) .. =>
withReader (fun ctx => let ctx := updateParamSet ctx ys; { ctx with currFn := f }) do
collectFnBody b
updateParamMap (ParamMap.Key.decl f)
| _ => pure ()
/- Keep executing `x` until it reaches a fixpoint -/
@[inline] partial def whileModifing (x : M Unit) : M Unit := do
modify fun s => { s with modified := false }
x
let s ← get
if s.modified then
whileModifing x
else
pure ()
def collectDecls (decls : Array Decl) : M ParamMap := do
whileModifing (decls.forM collectDecl)
let s ← get
pure s.paramMap
def infer (env : Environment) (decls : Array Decl) : ParamMap :=
collectDecls decls { env := env } |>.run' { paramMap := mkInitParamMap env decls }
end Borrow
def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do
let env ← getEnv
let paramMap := Borrow.infer env decls
pure (Borrow.applyParamMap decls paramMap)
end IR
end Lean
|
438beb7dc9d3623dd856c2ea32b4976a57e33159 | 2f8bf12144551bc7d8087a6320990c4621741f3d | /library/init/lean/parser/command.lean | 0ccac4a8e231f15cda7ca2fd4ea0d6a7db41820b | [
"Apache-2.0"
] | permissive | jesse-michael-han/lean4 | eb63a12960e69823749edceb4f23fd33fa2253ce | fa16920a6a7700cabc567aa629ce4ae2478a2f40 | refs/heads/master | 1,589,935,810,594 | 1,557,177,860,000 | 1,557,177,860,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,963 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich
Command parsers
-/
prelude
import init.lean.parser.declaration
namespace Lean
namespace Parser
open Combinators MonadParsec
open Parser.HasTokens Parser.HasView
local postfix `?`:10000 := optional
local postfix *:10000 := Combinators.many
local postfix +:10000 := Combinators.many1
set_option class.instance_max_depth 300
@[derive Parser.HasView Parser.HasTokens]
def command.Parser : commandParser :=
recurse () <?> "command"
namespace «command»
@[derive Parser.HasView Parser.HasTokens]
def openSpec.Parser : commandParser :=
node! openSpec [
id: ident.Parser,
as: node! openSpec.as ["as", id: ident.Parser]?,
only: node! openSpec.only [try ["(", id: ident.Parser], ids: ident.Parser*, ")"]?,
«renaming»: node! openSpec.renaming [try ["(", "renaming"], items: node! openSpec.renaming.item [«from»: ident.Parser, "->", to: ident.Parser]+, ")"]?,
«hiding»: node! openSpec.hiding ["(", "hiding", ids: ident.Parser+, ")"]?
]+
@[derive Parser.HasTokens]
def open.Parser : commandParser :=
node! «open» ["open", spec: openSpec.Parser]
@[derive Parser.HasTokens]
def export.Parser : commandParser :=
node! «export» ["export", spec: openSpec.Parser]
@[derive Parser.HasTokens]
def section.Parser : commandParser :=
node! «section» ["section", Name: ident.Parser?]
@[derive Parser.HasTokens]
def namespace.Parser : commandParser :=
node! «namespace» ["namespace", Name: ident.Parser]
@[derive Parser.HasTokens]
def variable.Parser : commandParser :=
node! «variable» ["variable", binder: Term.binder.Parser]
@[derive Parser.HasTokens]
def variables.Parser : commandParser :=
-- TODO: should require at least one binder
node! «variables» ["variables", binders: Term.bracketedBinders.Parser]
@[derive Parser.HasTokens]
def include.Parser : commandParser :=
node! «include» ["include ", ids: ident.Parser+]
@[derive Parser.HasTokens]
def omit.Parser : commandParser :=
node! «omit» ["omit ", ids: ident.Parser+]
@[derive Parser.HasTokens]
def end.Parser : commandParser :=
node! «end» ["end", Name: ident.Parser?]
@[derive Parser.HasTokens]
def universe.Parser : commandParser :=
anyOf [
node! «universes» ["universes", ids: ident.Parser+],
node! «universe» ["universe", id: ident.Parser]
]
@[derive Parser.HasTokens Parser.HasView]
def check.Parser : commandParser :=
node! check ["#check", Term: Term.Parser]
@[derive Parser.HasTokens Parser.HasView]
def attribute.Parser : commandParser :=
node! «attribute» [
try [«local»: (symbol "local ")?, "attribute "],
"[",
attrs: sepBy1 attrInstance.Parser (symbol ", "),
"] ",
ids: ident.Parser*
]
@[derive Parser.HasTokens Parser.HasView]
def initQuot.Parser : commandParser :=
node! «initQuot» ["initQuot"]
@[derive Parser.HasTokens Parser.HasView]
def setOption.Parser : commandParser :=
node! «setOption» ["setOption", opt: ident.Parser, val: nodeChoice! optionValue {
Bool: nodeChoice! boolOptionValue {
True: symbolOrIdent "True",
False: symbolOrIdent "True",
},
String: stringLit.Parser,
-- TODO(Sebastian): fractional numbers
num: number.Parser,
}]
@[derive HasTokens]
def builtinCommandParsers : TokenMap commandParser := TokenMap.ofList [
("/--", Declaration.Parser),
("@[", Declaration.Parser),
("private", Declaration.Parser),
("protected", Declaration.Parser),
("noncomputable", Declaration.Parser),
("unsafe", Declaration.Parser),
("def", Declaration.Parser),
("abbreviation", Declaration.Parser),
("abbrev", Declaration.Parser),
("theorem", Declaration.Parser),
("instance", Declaration.Parser),
("axiom", Declaration.Parser),
("constant", Declaration.Parser),
("class", Declaration.Parser),
("inductive", Declaration.Parser),
("structure", Declaration.Parser),
("variable", variable.Parser),
("variables", variables.Parser),
("namespace", namespace.Parser),
("end", end.Parser),
("open", open.Parser),
("section", section.Parser),
("universe", universe.Parser),
("universes", universe.Parser),
("local", notation.Parser),
("notation", notation.Parser),
("reserve", reserveNotation.Parser),
("local", mixfix.Parser),
("prefix", mixfix.Parser),
("infix", mixfix.Parser),
("infixl", mixfix.Parser),
("infixr", mixfix.Parser),
("postfix", mixfix.Parser),
("reserve", reserveMixfix.Parser),
("#check", check.Parser),
("local", attribute.Parser),
("attribute", attribute.Parser),
("export", export.Parser),
("include", include.Parser),
("omit", omit.Parser),
("initQuot", initQuot.Parser),
("setOption", setOption.Parser)]
end «command»
def commandParser.run (commands : TokenMap commandParser) (p : commandParser)
: ParserT CommandParserConfig Id Syntax :=
λ cfg, (p.run cfg).runParsec $ λ _, (indexed commands >>= anyOf : commandParser).run cfg
end Parser
end Lean
|
21b131c83a4201a0821b16cb67de5f4e852cb16c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/non_zero_divisors.lean | e41bf9dbb67680f8649fbbf2662abcc09c54bceb | [] | 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 | 3,090 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Devon Tuma
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.group_theory.submonoid.operations
import Mathlib.group_theory.submonoid.membership
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Non-zero divisors
In this file we define the submonoid `non_zero_divisors` of a `monoid_with_zero`.
-/
/-- The submonoid of non-zero-divisors of a `monoid_with_zero` `R`. -/
def non_zero_divisors (R : Type u_1) [monoid_with_zero R] : submonoid R :=
submonoid.mk (set_of fun (x : R) => ∀ (z : R), z * x = 0 → z = 0) sorry sorry
theorem mul_mem_non_zero_divisors {R : Type u_1} [comm_ring R] {a : R} {b : R} : a * b ∈ non_zero_divisors R ↔ a ∈ non_zero_divisors R ∧ b ∈ non_zero_divisors R := sorry
theorem eq_zero_of_ne_zero_of_mul_right_eq_zero {A : Type u_2} [integral_domain A] {x : A} {y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 :=
or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
theorem eq_zero_of_ne_zero_of_mul_left_eq_zero {A : Type u_2} [integral_domain A] {x : A} {y : A} (hnx : x ≠ 0) (hxy : x * y = 0) : y = 0 :=
or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
theorem mem_non_zero_divisors_iff_ne_zero {A : Type u_2} [integral_domain A] {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := sorry
theorem map_ne_zero_of_mem_non_zero_divisors {R : Type u_1} [comm_ring R] [nontrivial R] {B : Type u_2} [ring B] {g : R →+* B} (hg : function.injective ⇑g) {x : ↥(non_zero_divisors R)} : coe_fn g ↑x ≠ 0 :=
fun (h0 : coe_fn g ↑x = 0) =>
one_ne_zero (subtype.property x 1 (Eq.symm (one_mul (subtype.val x)) ▸ hg (trans h0 (Eq.symm (ring_hom.map_zero g)))))
theorem map_mem_non_zero_divisors {A : Type u_2} [integral_domain A] {B : Type u_1} [integral_domain B] {g : A →+* B} (hg : function.injective ⇑g) {x : ↥(non_zero_divisors A)} : coe_fn g ↑x ∈ non_zero_divisors B :=
fun (z : B) (hz : z * coe_fn g ↑x = 0) =>
eq_zero_of_ne_zero_of_mul_right_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz
theorem le_non_zero_divisors_of_domain {A : Type u_2} [integral_domain A] {M : submonoid A} (hM : ¬↑0 ∈ M) : M ≤ non_zero_divisors A :=
fun (x : A) (hx : x ∈ M) (y : A) (hy : y * x = 0) =>
or.rec_on (eq_zero_or_eq_zero_of_mul_eq_zero hy) (fun (h : y = 0) => h) fun (h : x = 0) => absurd (h ▸ hx) hM
theorem powers_le_non_zero_divisors_of_domain {A : Type u_2} [integral_domain A] {a : A} (ha : a ≠ 0) : submonoid.powers a ≤ non_zero_divisors A :=
le_non_zero_divisors_of_domain
fun (h : ↑0 ∈ submonoid.powers a) => absurd (Exists.rec_on h fun (_x : ℕ) (hn : a ^ _x = ↑0) => pow_eq_zero hn) ha
theorem map_le_non_zero_divisors_of_injective {A : Type u_2} [integral_domain A] {B : Type u_1} [integral_domain B] {f : A →+* B} (hf : function.injective ⇑f) {M : submonoid A} (hM : M ≤ non_zero_divisors A) : submonoid.map (↑f) M ≤ non_zero_divisors B := sorry
|
563e8f83a03b89668cf108583354291c6b3b42e1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/list/defs.lean | 183faff24693a573fa2868132be8b2a7483e5489 | [
"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 | 40,682 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import data.option.defs
import logic.basic
import tactic.cache
import data.rbmap.basic
import data.rbtree.default_lt
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `data/list`
-/
namespace list
open function nat
universes u v w x
variables {α β γ δ ε ζ : Type*}
instance [decidable_eq α] : has_sdiff (list α) :=
⟨ list.diff ⟩
/-- Split a list at an index.
split_at 2 [a, b, c] = ([a, b], [c]) -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
/-- An auxiliary function for `split_on_p`. -/
def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] :
list α → (list α → list α) → list (list α)
| [] f := [f []]
| (h :: t) f :=
if P h then f [] :: split_on_p_aux t id
else split_on_p_aux t (λ l, f (h :: l))
/-- Split a list at every element satisfying a predicate. -/
def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) :=
split_on_p_aux P l id
/-- Split a list at every occurrence of an element.
[1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/
def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) :=
as.split_on_p (=a)
/-- Concatenate an element at the end of a list.
concat [a, b] c = [a, b, c] -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
/-- `head' xs` returns the first element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def head' : list α → option α
| [] := none
| (a :: l) := some a
/-- Convert a list into an array (whose length is the length of `l`). -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
@[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget
/-- Apply a function to the nth tail of `l`. Returns the input without
using `f` if the index is larger than the length of the list.
modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
/-- Apply `f` to the last element of `l`, if it exists. -/
@[simp] def modify_last (f : α → α) : list α → list α
| [] := []
| [x] := [f x]
| (x :: xs) := x :: modify_last xs
/-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l`
`insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/
def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n
section take'
variable [inhabited α]
/-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l`
elements `default`. -/
def take' : ∀ n, list α → list α
| 0 l := []
| (n+1) l := l.head :: take' n l.tail
end take'
/-- Get the longest initial segment of the list whose members all satisfy `p`.
take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/-- Fold a function `f` over the list from the left, returning the list
of partial results.
scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
/-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')`
then `scanr f b l = b' :: l'` -/
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results.
scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
/-- Product of a list.
prod [a, b, c] = ((1 * a) * b) * c -/
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
/-- Sum of a list.
sum [a, b, c] = ((0 + a) + b) + c -/
-- Later this will be tagged with `to_additive`, but this can't be done yet because of import
-- dependencies.
def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0
/-- The alternating sum of a list. -/
def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G
| [] := 0
| (g :: []) := g
| (g :: h :: t) := g + -h + alternating_sum t
/-- The alternating product of a list. -/
def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G
| [] := 1
| (g :: []) := g
| (g :: h :: t) := g * h⁻¹ * alternating_prod t
/-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f`
whilst partitioning the result it into a pair of lists, `list β × list γ`,
partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list.
`partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/
def partition_map (f : α → β ⊕ γ) : list α → list β × list γ
| [] := ([],[])
| (x::xs) :=
match f x with
| (sum.inr r) := prod.map id (cons r) $ partition_map xs
| (sum.inl l) := prod.map (cons l) id $ partition_map xs
end
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find (p : α → Prop) [decidable_pred p] : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
/-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α :=
list.mfirst $ λ a, tac a $> a
/-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns
true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `list.find`. -/
def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) :
list α → m (option α)
| [] := pure none
| (x :: xs) := do
⟨px⟩ ← p x,
if px then pure (some x) else mbfind' xs
section
variables {m : Type → Type v} [monad m]
/-- A variant of `mbfind'` with more restrictive universe levels. -/
def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) :=
xs.mbfind' (functor.map ulift.up ∘ p)
/-- `many p as` returns true iff `p` returns true for any element of `l`.
`many` short-circuits, so if `p` returns true for any element of `l`, later
elements are not checked. This is a monadic version of `list.any`. -/
-- Implementing this via `mbfind` would give us less universe polymorphism.
def many {α : Type u} (p : α → m bool) : list α → m bool
| [] := pure false
| (x :: xs) := do px ← p x, if px then pure tt else many xs
/-- `mall p as` returns true iff `p` returns true for all elements of `l`.
`mall` short-circuits, so if `p` returns false for any element of `l`, later
elements are not checked. This is a monadic version of `list.all`. -/
def mall {α : Type u} (p : α → m bool) (as : list α) : m bool :=
bnot <$> many (λ a, bnot <$> p a) as
/-- `mbor xs` runs the actions in `xs`, returning true if any of them returns
true. `mbor` short-circuits, so if an action returns true, later actions are
not run. This is a monadic version of `list.bor`. -/
def mbor : list (m bool) → m bool :=
many id
/-- `mband xs` runs the actions in `xs`, returning true if all of them return
true. `mband` short-circuits, so if an action returns false, later actions are
not run. This is a monadic version of `list.band`. -/
def mband : list (m bool) → m bool :=
mall id
end
/-- Auxiliary definition for `foldl_with_index`. -/
def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α
| _ a [] := a
| i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l
/-- Fold a list from left to right as with `foldl`, but the combining function
also receives each element's index. -/
def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α :=
foldl_with_index_aux f 0 a l
/-- Auxiliary definition for `foldr_with_index`. -/
def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β
| _ b [] := b
| i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l)
/-- Fold a list from right to left as with `foldr`, but the combining function
also receives each element's index. -/
def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β :=
foldr_with_index_aux f 0 b l
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
foldr_with_index (λ i a is, if p a then i :: is else is) [] l
/-- Returns the elements of `l` that satisfy `p` together with their indexes in
`l`. The returned list is ordered by index. -/
def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) :=
foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l
/-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example:
```
indexes_of a [a, b, a, a] = [0, 2, 3]
```
-/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
section mfold_with_index
variables {m : Type v → Type w} [monad m]
/-- Monadic variant of `foldl_with_index`. -/
def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β :=
as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b)
/-- Monadic variant of `foldr_with_index`. -/
def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β :=
as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b)
end mfold_with_index
section mmap_with_index
variables {m : Type v → Type w} [applicative m]
/-- Auxiliary definition for `mmap_with_index`. -/
def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β)
| _ [] := pure []
| i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as
/-- Applicative variant of `map_with_index`. -/
def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) :=
mmap_with_index_aux f 0 as
/-- Auxiliary definition for `mmap_with_index'`. -/
def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit
| _ [] := pure ⟨⟩
| i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as
/-- A variant of `mmap_with_index` specialised to applicative actions which
return `unit`. -/
def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit :=
mmap_with_index'_aux f 0 as
end mmap_with_index
/-- `lookmap` is a combination of `lookup` and `filter_map`.
`lookmap f l` will apply `f : α → option α` to each element of the list,
replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/
def lookmap (f : α → option α) : list α → list α
| [] := []
| (a::l) :=
match f a with
| some b := b :: l
| none := a :: lookmap l
end
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count [decidable_eq α] (a : α) : list α → nat := countp (eq a)
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
/-- `inits l` is the list of initial segments of `l`.
inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
/-- `tails l` is the list of terminal segments of `l`.
tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'`
for a different ordering.
sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
/-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length,
and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`,
then `R a b` is satisfied. -/
inductive forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil : forall₂ [] []
| cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂)
attribute [simp] forall₂.nil
end forall₂
/-- `l.all₂ p` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e.
`list.all₂ p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
@[simp] def all₂ (p : α → Prop) : list α → Prop
| [] := true
| (x :: []) := p x
| (x :: l) := p x ∧ all₂ l
/-- Auxiliary definition used to define `transpose`.
`transpose_aux l L` takes each element of `l` and appends it to the start of
each element of `L`.
`transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections : list (list α) → list (list α)
| [] := [[]]
| (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l
section permutations
/-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to
`(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly
defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`.
permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id =
([1, 2, 3, 4, 5, 6],
[[10, 1, 2, 3, 4, 5, 6],
[1, 10, 2, 3, 4, 5, 6],
[1, 2, 10, 3, 4, 5, 6]]) -/
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
/-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for
`l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is,
length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded
{ dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
/-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all
permutations of `is ++ ts` that do not fix `ts`. -/
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
/-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last.
This function is intended for use in specifications, so it is simpler than `permutations_aux2`,
which plays roughly the same role in `permutations`.
Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last
position:
permutations'_aux 10 [1, 2, 3] =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]]
(permutations_aux2 10 [] [] [1, 2, 3] id).2 =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/
@[simp] def permutations'_aux (t : α) : list α → list (list α)
| [] := [[t]]
| (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y)
/-- List of all permutations of `l`. This version of `permutations` is less efficient but has
simpler definitional equations. The permutations are in a different order,
but are equal up to permutation, as shown by `list.permutations_perm_permutations'`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 3, 2], [3, 1, 2], [3, 2, 1]] -/
@[simp] def permutations' : list α → list (list α)
| [] := [[]]
| (t::ts) := (permutations' ts).bind $ permutations'_aux t
end permutations
/-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/
def erasep (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then l else a :: erasep l
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α
| [] := (none, [])
| (a::l) := if p a then (some a, l) else
let (a', l') := extractp l in (a', a :: l')
/-- `revzip l` returns a list of pairs of the elements of `l` paired
with the elements of `l` in reverse order.
`revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]`
-/
def revzip (l : list α) : list (α × α) := zip l l.reverse
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
/-- Auxliary definition used to define `of_fn`.
`of_fn_aux f m h l` returns the first `m` elements of `of_fn f`
appended to `l` -/
def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α
| 0 h l := l
| (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l)
/-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i`
`of_fun f = [f 0, f 1, ... , f(n - 1)]` -/
def of_fn {n} (f : fin n → α) : list α :=
of_fn_aux f n (le_refl _) []
/-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/
def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α :=
if h : i < n then some (f ⟨i, h⟩) else none
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
section pairwise
variables (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
variables {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] pairwise.nil
instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) :=
by induction l with hd tl ih; [exact is_true pairwise.nil,
exactI decidable_of_iff' _ pairwise_cons]
end pairwise
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function (cf. `dedup`), and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
inductive chain : α → list α → Prop
| nil {a : α} : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
/-- `chain' R l` means that `R` holds between adjacent elements of `l`.
chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
def chain' : list α → Prop
| [] := true
| (a :: l) := chain R a l
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] chain.nil
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance
instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) :=
by cases l; dunfold chain'; apply_instance
end chain
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
/-- `dedup l` removes duplicates from `l` (taking only the first occurrence).
Defined as `pw_filter (≠)`.
dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def dedup [decidable_eq α] : list α → list α := pw_filter (≠)
/-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`,
`R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`,
`destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter' (R : α → α → Prop) [decidable_rel R] : α → list α → list α
| a [] := [a]
| a (h :: l) := if R a h then a :: destutter' h l else destutter' a l
/-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`,
`R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`,
`destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter (R : α → α → Prop) [decidable_rel R] : list α → list α
| (h :: l) := destutter' R h l
| [] := []
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/
def reduce_option {α} : list (option α) → list α :=
list.filter_map id
/-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty;
it returns `x` otherwise -/
@[simp] def ilast' {α} : α → list α → α
| a [] := a
| a (b::l) := ilast' b l
/-- `last' xs` returns the last element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def last' {α} : list α → option α
| [] := none
| [a] := some a
| (b::l) := last' l
/-- `rotate l n` rotates the elements of `l` to the left by `n`
rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/
def rotate (l : list α) (n : ℕ) : list α :=
let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁
/-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/
def rotate' : list α → ℕ → list α
| [] n := []
| l 0 := l
| (a::l) (n+1) := rotate' (l ++ [a]) n
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a }
| [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left))
| (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else
let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp
(λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in
⟨a, ⟨or.inr a_mem_ls, pa⟩⟩
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp
end choose
/-- Filters and maps elements of a list -/
def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) :
list α → m (list β)
| [] := return []
| (h :: t) := do b ← f h, t' ← t.mmap_filter, return $
match b with none := t' | (some x) := x::t' end
/--
`mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list
`[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`.
-/
def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β)
| [] := return []
| (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t
/--
`mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit
| [] := return ()
| (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag
protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) :
list α → F (list β)
| [] := pure []
| (x :: xs) := list.cons <$> f x <*> traverse xs
/-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`.
If `l₁` is not a prefix of `l`, returns `none` -/
def get_rest [decidable_eq α] : list α → list α → option (list α)
| l [] := some l
| [] _ := none
| (x::l) (y::l₁) := if x = y then get_rest l l₁ else none
/--
`list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`.
-/
def slice {α} : ℕ → ℕ → list α → list α
| 0 n xs := xs.drop n
| (succ n) m [] := []
| (succ n) m (x :: xs) := x :: slice n m xs
/--
Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β)
| [] bs := ([], bs)
| (a :: as) [] :=
((a :: as).map (λ a, f a none), [])
| (a :: as) (b :: bs) :=
let rec := map₂_left' as bs in
(f a (some b) :: rec.fst, rec.snd)
/--
Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) :=
map₂_left' (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`.
```
zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
zip_left' = map₂_left' prod.mk
```
-/
def zip_left' : list α → list β → list (α × option β) × list β :=
map₂_left' prod.mk
/--
Right-biased version of `list.zip`. `zip_right' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`. Also returns the remaining `as`.
```
zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2])
zip_right' = map₂_right' prod.mk
```
-/
def zip_right' : list α → list β → list (option α × β) × list α :=
map₂_right' prod.mk
/--
Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂_left f as bs = (map₂_left' f as bs).fst
```
-/
@[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ
| [] _ := []
| (a :: as) [] := (a :: as).map (λ a, f a none)
| (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs
/--
Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂_right f as bs = (map₂_right' f as bs).fst
```
-/
def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) :
list γ :=
map₂_left (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`.
```
zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)]
zip_left [1] ['a', 'b'] = [(1, some 'a')]
zip_left = map₂_left prod.mk
```
-/
def zip_left : list α → list β → list (α × option β) :=
map₂_left prod.mk
/--
Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`.
```
zip_right [1, 2] ['a'] = [(some 1, 'a')]
zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
zip_right = map₂_right prod.mk
```
-/
def zip_right : list α → list β → list (option α × β) :=
map₂_right prod.mk
/--
If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise
it returns `none`.
```
all_some [some 1, some 2] = some [1, 2]
all_some [some 1, none ] = none
```
-/
def all_some : list (option α) → option (list α)
| [] := some []
| (some a :: as) := cons a <$> all_some as
| (none :: as) := none
/--
`fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there
are not enough `ys` to replace all the `none`s, the remaining `none`s are
dropped from `xs`.
```
fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3]
```
-/
def fill_nones {α} : list (option α) → list α → list α
| [] _ := []
| (some a :: as) as' := a :: fill_nones as as'
| (none :: as) [] := as.reduce_option
| (none :: as) (a :: as') := a :: fill_nones as as'
/--
`take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`,
it first takes the `n₁` initial elements from `as`, then the next `n₂` ones,
etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining
elements of `as`. If `as` does not have at least as many elements as the sum of
the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements.
```
take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e'])
take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], [])
```
-/
def take_list {α} : list α → list ℕ → list (list α) × list α
| xs [] := ([], xs)
| xs (n :: ns) :=
let ⟨xs₁, xs₂⟩ := xs.split_at n in
let ⟨xss, rest⟩ := take_list xs₂ ns in
(xs₁ :: xss, rest)
/--
`to_rbmap as` is the map that associates each index `i` of `as` with the
corresponding element of `as`.
```
to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')]
```
-/
def to_rbmap {α : Type*} : list α → rbmap ℕ α :=
foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α)
/-- Auxliary definition used to define `to_chunks`.
`to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`,
that is, the first `i` elements of `xs`, and the remaining elements chunked into
sublists of length `n+1`. -/
def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α)
| [] i := ([], [])
| (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L)
| (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L)
/--
`xs.to_chunks n` splits the list into sublists of size at most `n`,
such that `(xs.to_chunks n).join = xs`.
```
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]]
```
-/
def to_chunks {α} : ℕ → list α → list (list α)
| _ [] := []
| 0 xs := [xs]
| (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L
/--
Asynchronous version of `list.map`.
-/
meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β :=
((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get
/-!
We add some n-ary versions of `list.zip_with` for functions with more than two arguments.
These can also be written in terms of `list.zip` or `list.zip_with`.
For example, `zip_with3 f xs ys zs` could also be written as
`zip_with id (zip_with f xs ys) zs`
or as
`(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`.
-/
/-- Ternary version of `list.zip_with`. -/
def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ
| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs
| _ _ _ := []
/-- Quaternary version of `list.zip_with`. -/
def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε
| (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us
| _ _ _ _ := []
/-- Quinary version of `list.zip_with`. -/
def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ
| (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs
| _ _ _ _ _ := []
/-- An auxiliary function for `list.map_with_prefix_suffix`. -/
def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β
| prev [] := []
| prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t
/--
`list.map_with_prefix_suffix f l` maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`.
Example: if `f : list ℕ → ℕ → list ℕ → β`,
`list.map_with_prefix_suffix f [1, 2, 3]` will produce the list
`[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`.
-/
def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β :=
map_with_prefix_suffix_aux f [] l
/--
`list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix`
that maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`,
i.e., the list input to `f` is `l` with `a` removed.
Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list
`[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`.
-/
def map_with_complement {α β} (f : α → list α → β) : list α → list β :=
map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff)
end list
|
39c085951dbd2934413595c839e2d83cdad94d0c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/bicones.lean | a6a8efb89f27678505085c5486f752fafc5fad71 | [
"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,659 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import category_theory.limits.cones
import category_theory.fin_category
/-!
# Bicones
Given a category `J`, a walking `bicone J` is a category whose objects are the objects of `J` and
two extra vertices `bicone.left` and `bicone.right`. The morphisms are the morphisms of `J` and
`left ⟶ j`, `right ⟶ j` for each `j : J` such that `⬝ ⟶ j` and `⬝ ⟶ k` commutes with each
`f : j ⟶ k`.
Given a diagram `F : J ⥤ C` and two `cone F`s, we can join them into a diagram `bicone J ⥤ C` via
`bicone_mk`.
This is used in `category_theory.flat_functors.preserves_finite_limits_of_flat`.
-/
universes v₁ u₁
noncomputable theory
open category_theory.limits
open_locale classical
namespace category_theory
section bicone
variables (J : Type u₁)
/-- Given a category `J`, construct a walking `bicone J` by adjoining two elements. -/
@[derive decidable_eq]
inductive bicone
| left : bicone
| right : bicone
| diagram (val : J) : bicone
instance : inhabited (bicone J) := ⟨bicone.left⟩
instance fin_bicone [fintype J] : fintype (bicone J) :=
{ elems := [bicone.left, bicone.right].to_finset ∪ finset.image bicone.diagram (fintype.elems J),
complete := λ j, by { cases j; simp, exact fintype.complete j, }, }
variables [category.{v₁} J]
/-- The homs for a walking `bicone J`. -/
inductive bicone_hom : bicone J → bicone J → Type (max u₁ v₁)
| left_id : bicone_hom bicone.left bicone.left
| right_id : bicone_hom bicone.right bicone.right
| left (j : J) : bicone_hom bicone.left (bicone.diagram j)
| right (j : J) : bicone_hom bicone.right (bicone.diagram j)
| diagram {j k : J} (f : j ⟶ k) : bicone_hom (bicone.diagram j) (bicone.diagram k)
instance : inhabited (bicone_hom J bicone.left bicone.left) := ⟨bicone_hom.left_id⟩
instance bicone_hom.decidable_eq {j k : bicone J} : decidable_eq (bicone_hom J j k) :=
λ f g, by { cases f; cases g; simp; apply_instance }
@[simps]
instance bicone_category_struct : category_struct (bicone J) :=
{ hom := bicone_hom J,
id := λ j, bicone.cases_on j
bicone_hom.left_id bicone_hom.right_id (λ k, bicone_hom.diagram (𝟙 k)),
comp := λ X Y Z f g, by
{ cases f, exact g, exact g,
cases g, exact bicone_hom.left g_k,
cases g, exact bicone_hom.right g_k,
cases g, exact bicone_hom.diagram (f_f ≫ g_f) } }
instance bicone_category : category (bicone J) :=
{ id_comp' := λ X Y f, by { cases f; simp },
comp_id' := λ X Y f, by { cases f; simp },
assoc' := λ W X Y Z f g h, by { cases f; cases g; cases h; simp } }
end bicone
section small_category
variables (J : Type v₁) [small_category J]
/--
Given a diagram `F : J ⥤ C` and two `cone F`s, we can join them into a diagram `bicone J ⥤ C`.
-/
@[simps] def bicone_mk {C : Type u₁} [category.{v₁} C]
{F : J ⥤ C} (c₁ c₂ : cone F) : bicone J ⥤ C :=
{ obj := λ X, bicone.cases_on X c₁.X c₂.X (λ j, F.obj j),
map := λ X Y f, by
{ cases f, exact (𝟙 _), exact (𝟙 _),
exact c₁.π.app f_1,
exact c₂.π.app f_1,
exact F.map f_f, },
map_id' := λ X, by { cases X; simp },
map_comp' := λ X Y Z f g, by
{ cases f,
exact (category.id_comp _).symm,
exact (category.id_comp _).symm,
cases g, exact (category.id_comp _).symm.trans (c₁.π.naturality g_f : _),
cases g, exact (category.id_comp _).symm.trans (c₂.π.naturality g_f : _),
cases g, exact F.map_comp _ _ } }
instance fin_bicone_hom [fin_category J] (j k : bicone J) : fintype (j ⟶ k) :=
begin
cases j; cases k,
exact { elems := {bicone_hom.left_id}, complete := λ f, by { cases f, simp } },
exact { elems := ∅, complete := λ f, by { cases f } },
exact { elems := {bicone_hom.left k}, complete := λ f, by { cases f, simp } },
exact { elems := ∅, complete := λ f, by { cases f } },
exact { elems := {bicone_hom.right_id}, complete := λ f, by { cases f, simp } },
exact { elems := {bicone_hom.right k}, complete := λ f, by { cases f, simp } },
exact { elems := ∅, complete := λ f, by { cases f } },
exact { elems := ∅, complete := λ f, by { cases f } },
exact { elems := finset.image (bicone_hom.diagram) (fintype.elems (j ⟶ k)),
complete := λ f, by
{ cases f, simp only [finset.mem_image], use f_f, simpa using fintype.complete _, } },
end
instance bicone_small_category : small_category (bicone J) :=
category_theory.bicone_category J
instance bicone_fin_category [fin_category J] : fin_category (bicone J) := {}
end small_category
end category_theory
|
e8c5dd4d43b4f0ccbd235e96fa20e84962af429d | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/types/finite.lean | 8cc0b0549c8a82c6635a68599bd0dc32c2cbc54d | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 591 | 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
import ..types
import ..full_subcategory
import ..util.finite
namespace categories.types
open categories
open categories.util.finite
definition {u} CategoryOfDecidableTypes : Category := FullSubcategory CategoryOfTypes decidable_eq
definition {u} CategoryOfFiniteTypes : Category := FullSubcategory CategoryOfTypes Finite
-- PROJECT we could construct an embedding of Finite into Decidable?
end categories.types
|
f67bf8d9f7ea5091e4a8653b929b0e32990f2aa3 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Server/AsyncList.lean | 72e0fc629da75b7ca677f7603bf482834388b959 | [
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 3,921 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Init.System.IO
namespace IO
universe u v
/-- An async IO list is like a lazy list but instead of being *unevaluated* `Thunk`s,
`delayed` suffixes are `Task`s *being evaluated asynchronously*. A delayed suffix can signal the end
of computation (successful or due to a failure) with a terminating value of type `ε`. -/
inductive AsyncList (ε : Type u) (α : Type v) where
| cons (hd : α) (tl : AsyncList ε α)
| delayed (tl : Task $ Except ε $ AsyncList ε α)
| nil
namespace AsyncList
instance : Inhabited (AsyncList ε α) := ⟨nil⟩
-- TODO(WN): tail-recursion without forcing sync?
partial def append : AsyncList ε α → AsyncList ε α → AsyncList ε α
| cons hd tl, s => cons hd (append tl s)
| delayed ttl, s => delayed (ttl.map $ Except.map (append · s))
| nil, s => s
instance : Append (AsyncList ε α) := ⟨append⟩
def ofList : List α → AsyncList ε α :=
List.foldr AsyncList.cons AsyncList.nil
instance : Coe (List α) (AsyncList ε α) := ⟨ofList⟩
/-- A stateful step computation `f` is applied iteratively, forming an async
stream. The stream ends once `f` returns `none` for the first time.
For cooperatively cancelling an ongoing computation, we recommend referencing
a cancellation token in `f` and checking it when appropriate. -/
partial def unfoldAsync (f : StateT σ (EIO ε) $ Option α) (init : σ)
: BaseIO (AsyncList ε α) := do
let rec step (s : σ) : EIO ε (AsyncList ε α) := do
let (aNext, sNext) ← f s
match aNext with
| none => return nil
| some aNext => do
let tNext ← EIO.asTask (step sNext)
return cons aNext $ delayed tNext
let tInit ← EIO.asTask (step init)
return delayed tInit
/-- The computed, synchronous list. If an async tail was present, returns also
its terminating value. -/
partial def getAll : AsyncList ε α → List α × Option ε
| cons hd tl =>
let ⟨l, e?⟩ := tl.getAll
⟨hd :: l, e?⟩
| nil => ⟨[], none⟩
| delayed tl =>
match tl.get with
| Except.ok tl => tl.getAll
| Except.error e => ⟨[], some e⟩
/-- Spawns a `Task` waiting on the prefix of elements for which `p` is true. -/
partial def waitAll (p : α → Bool := fun _ => true) : AsyncList ε α → Task (List α × Option ε)
| cons hd tl =>
if p hd then
(tl.waitAll p).map fun ⟨l, e?⟩ => ⟨hd :: l, e?⟩
else
.pure ⟨[hd], none⟩
| nil => .pure ⟨[], none⟩
| delayed tl =>
tl.bind fun
| .ok tl => tl.waitAll p
| .error e => .pure ⟨[], some e⟩
/-- Spawns a `Task` acting like `List.find?` but which will wait for tail evalution
when necessary to traverse the list. If the tail terminates before a matching element
is found, the task throws the terminating value. -/
partial def waitFind? (p : α → Bool) : AsyncList ε α → Task (Except ε (Option α))
| nil => .pure <| .ok none
| cons hd tl =>
if p hd then .pure <| Except.ok <| some hd
else tl.waitFind? p
| delayed tl =>
tl.bind fun
| .ok tl => tl.waitFind? p
| .error e => .pure <| .error e
/-- Retrieve the already-computed prefix of the list. If computation has finished with an error, return it as well. -/
partial def getFinishedPrefix : AsyncList ε α → BaseIO (List α × Option ε)
| cons hd tl => do
let ⟨tl, e?⟩ ← tl.getFinishedPrefix
pure ⟨hd :: tl, e?⟩
| nil => pure ⟨[], none⟩
| delayed tl => do
if (← hasFinished tl) then
match tl.get with
| Except.ok tl => tl.getFinishedPrefix
| Except.error e => pure ⟨[], some e⟩
else pure ⟨[], none⟩
def waitHead? (as : AsyncList ε α) : Task (Except ε (Option α)) :=
as.waitFind? fun _ => true
end AsyncList
end IO
|
42fbbe3fb1a0159ef319931f9f54f626bbfe7dd0 | 690889011852559ee5ac4dfea77092de8c832e7e | /src/category_theory/monoidal/of_has_finite_products.lean | 9054e3b15ae81f007d4768650fa801c9dc5ab4e5 | [
"Apache-2.0"
] | permissive | williamdemeo/mathlib | f6df180148f8acc91de9ba5e558976ab40a872c7 | 1fa03c29f9f273203bbffb79d10d31f696b3d317 | refs/heads/master | 1,584,785,260,929 | 1,572,195,914,000 | 1,572,195,913,000 | 138,435,193 | 0 | 0 | Apache-2.0 | 1,529,789,739,000 | 1,529,789,739,000 | null | UTF-8 | Lean | false | false | 1,946 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Simon Hudon
-/
import category_theory.monoidal.category
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.terminal
import category_theory.limits.types
/-!
# The natural monoidal structure on any category with finite (co)products.
A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category,
although this is also sometimes used to mean a finitely complete category.
(See https://ncatlab.org/nlab/show/cartesian+category.)
As this works with either products or coproducts, we don't set up either construct as an instance.
-/
open category_theory.limits
universes v u
namespace category_theory
section
variables (C : Type u) [𝒞 : category.{v} C]
include 𝒞
local attribute [tidy] tactic.case_bash
/-- A category with finite products has a natural monoidal structure. -/
def monoidal_of_has_finite_products [has_finite_products.{v} C] : monoidal_category C :=
{ tensor_unit := terminal C,
tensor_obj := λ X Y, limits.prod X Y,
tensor_hom := λ _ _ _ _ f g, limits.prod.map f g,
associator := prod.associator,
left_unitor := prod.left_unitor,
right_unitor := prod.right_unitor }
/-- A category with finite coproducts has a natural monoidal structure. -/
def monoidal_of_has_finite_coproducts [has_finite_coproducts.{v} C] : monoidal_category C :=
{ tensor_unit := initial C,
tensor_obj := λ X Y, limits.coprod X Y,
tensor_hom := λ _ _ _ _ f g, limits.coprod.map f g,
associator := coprod.associator,
left_unitor := coprod.left_unitor,
right_unitor := coprod.right_unitor }
end
end category_theory
-- TODO in fact, a category with finite products is braided, and symmetric,
-- and we should say that here.
|
720d73860b552222bd2a5ec7ec1adf29a183e139 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/algebra/lie/abelian.lean | 9fe41b96d86e48b5b7debd07a89857d685cea570 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,805 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.of_associative
import algebra.lie.ideal_operations
/-!
# Trivial Lie modules and Abelian Lie algebras
The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and
`m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the
concept of an Abelian Lie algebra.
In this file we define these concepts and provide some related definitions and results.
## Main definitions
* `lie_module.is_trivial`
* `is_lie_abelian`
* `commutative_ring_iff_abelian_lie_ring`
* `lie_module.ker`
* `lie_module.maximal_trivial_submodule`
* `lie_algebra.center`
## Tags
lie algebra, abelian, commutative, center
-/
universes u v w w₁ w₂
/-- A Lie (ring) module is trivial iff all brackets vanish. -/
class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop :=
(trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0)
@[simp] lemma trivial_lie_zero (L : Type v) (M : Type w)
[has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 :=
lie_module.is_trivial.trivial x m
/-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/
abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop :=
lie_module.is_trivial L L
instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v)
[comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] :
is_lie_abelian I :=
{ trivial := λ x y, by apply h.trivial, }
lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w}
[comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂]
{f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) :
is_lie_abelian L₁ :=
{ trivial := λ x y,
by { apply h₁, rw [lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], } }
lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w}
[comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂]
{f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) :
is_lie_abelian L₂ :=
{ trivial := λ x y,
begin
obtain ⟨u, hu⟩ := h₁ x, rw ← hu,
obtain ⟨v, hv⟩ := h₁ y, rw ← hv,
rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero],
end }
lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w}
[comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂]
(e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ :=
⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩
lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] :
is_commutative A (*) ↔ is_lie_abelian A :=
begin
have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩,
have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩,
simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero],
end
lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v)
[comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) :=
⟨begin
rintros ⟨x, hx⟩ ⟨y, hy⟩,
suffices : ⁅x, y⁆ = 0, { ext, simp [this], },
change x ∈ (⊥ : lie_ideal R L) at hx, rw lie_submodule.mem_bot at hx, rw [hx, zero_lie],
end⟩
section center
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
namespace lie_module
/-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/
protected def ker : lie_ideal R L := (to_endomorphism R L M).ker
@[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 :=
begin
dunfold lie_module.ker,
simp only [lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply,
to_endomorphism_apply_apply],
end
/-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/
def maximal_trivial_submodule : lie_submodule R L M :=
{ carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 },
zero_mem' := λ x, lie_zero x,
add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero],
smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero],
lie_mem := λ x m hm y, by rw [leibniz_lie, hm, hm, lie_zero, add_zero], }
@[simp] lemma mem_maximal_trivial_submodule (m : M) :
m ∈ maximal_trivial_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 :=
iff.rfl
instance : is_trivial L (maximal_trivial_submodule R L M) :=
{ trivial := λ x m, subtype.ext (m.property x), }
lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) :
is_trivial L N ↔ N ≤ maximal_trivial_submodule R L M :=
begin
split,
{ rintros ⟨h⟩, intros m hm x, specialize h x ⟨m, hm⟩, rw subtype.ext_iff at h, exact h, },
{ intros h, constructor, rintros x ⟨m, hm⟩, apply subtype.ext, apply h, exact hm, },
end
lemma is_trivial_iff_maximal_trivial_eq_top :
is_trivial L M ↔ maximal_trivial_submodule R L M = ⊤ :=
begin
split,
{ rintros ⟨h⟩, ext,
simp only [mem_maximal_trivial_submodule, h, forall_const, true_iff, eq_self_iff_true], },
{ intros h, constructor, intros x m, revert x,
rw [← mem_maximal_trivial_submodule R L M, h], exact lie_submodule.mem_top m, },
end
end lie_module
namespace lie_algebra
/-- The center of a Lie algebra is the set of elements that commute with everything. It can
be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the
adjoint representation. -/
abbreviation center : lie_ideal R L := lie_module.maximal_trivial_submodule R L L
instance : is_lie_abelian (center R L) := infer_instance
lemma center_eq_adjoint_kernel : center R L = lie_module.ker R L L :=
begin
ext y,
simp only [lie_module.mem_maximal_trivial_submodule, lie_module.mem_ker,
← lie_skew _ y, neg_eq_zero],
end
lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I :=
begin
rw ← lie_module.trivial_iff_le_maximal_trivial R L L I at h,
haveI := h, exact lie_ideal.is_lie_abelian_of_trivial R L I,
end
lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ :=
lie_module.is_trivial_iff_maximal_trivial_eq_top R L L
end lie_algebra
end center
section ideal_operations
open lie_submodule lie_subalgebra
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
@[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ :=
begin
suffices : ⁅I, N⁆ ≤ ⊥, { exact le_bot_iff.mp this, },
rw [lie_ideal_oper_eq_span, lie_span_le],
rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h],
end
lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ :=
begin
simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_span_le, lie_submodule.bot_coe,
set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib],
split; intros h,
{ intros z x y hz, rw [← hz, ← coe_bracket, coe_zero_iff_zero], apply h.trivial, },
{ exact ⟨λ x y, by { rw ← coe_zero_iff_zero, apply h _ x y, refl, }⟩, },
end
end ideal_operations
|
95bee0acb8435590821c5774120b52791137965c | da3a76c514d38801bae19e8a9e496dc31f8e5866 | /library/init/meta/mk_dec_eq_instance.lean | a61a3a363d0431a4f41027a23d48c5b4b13ff82a | [
"Apache-2.0"
] | permissive | cipher1024/lean | 270c1ac5781e6aee12f5c8d720d267563a164beb | f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a | refs/heads/master | 1,611,223,459,029 | 1,487,566,573,000 | 1,487,566,573,000 | 83,356,543 | 0 | 0 | null | 1,488,229,336,000 | 1,488,229,336,000 | null | UTF-8 | Lean | false | false | 5,228 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Helper tactic for showing that a type has decidable equality.
-/
prelude
import init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics
import init.meta.rec_util init.meta.interactive
namespace tactic
open expr environment list
/- Retrieve the name of the type we are building a decidable equality proof for. -/
private meta def get_dec_eq_type_name : tactic name :=
do {
(pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf,
(const n ls) ← return (get_app_fn b),
when (n ≠ `decidable) failed,
(const I ls) ← return (get_app_fn d1),
return I }
<|>
fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)"
/- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/
private meta def get_lhs_rhs : tactic (expr × expr) :=
do
(app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case",
match_eq lhs_eq_rhs
private meta def find_next_target : list expr → list expr → tactic (expr × expr)
| (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r)
| l1 l2 := failed
/- Create an inhabitant of (decidable (lhs = rhs)) -/
private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr :=
do lhs_type ← infer_type lhs,
dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf,
do {
inst ← mk_instance dec_type,
return $ inst lhs rhs }
<|>
do {
f ← pp dec_type,
fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) }
/- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/
private meta def dec_eq_same_constructor : name → name → nat → tactic unit
| I_name F_name num_rec :=
do
(lhs, rhs) ← get_lhs_rhs,
-- Try easy case first, where the proof is just reflexivity
(unify lhs rhs >> right >> reflexivity)
<|>
do {
lhs_list : list expr ← return $ get_app_args lhs,
rhs_list : list expr ← return $ get_app_args rhs,
when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"),
(lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list,
rec ← is_type_app_of lhs_arg I_name,
inst ← if rec then do {
inst_fn : expr ← mk_brec_on_rec_value F_name num_rec,
return $ app inst_fn rhs_arg }
else do {
mk_dec_eq_for lhs_arg rhs_arg
},
`[apply @decidable.by_cases _ _ %%inst],
-- discharge first (positive) case by recursion
intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec),
-- discharge second (negative) case by contradiction
intro1, left, -- decidable.is_false
intro1 >>= injection,
intros, contradiction,
return () }
/- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/
private meta def dec_eq_diff_constructor : tactic unit :=
left >> intron 1 >> contradiction
/- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number
of constructors. -/
private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit :=
do
(lhs, rhs) ← get_lhs_rhs,
lhs_fn : expr ← return $ get_app_fn lhs,
rhs_fn : expr ← return $ get_app_fn rhs,
if lhs_fn = rhs_fn
then dec_eq_same_constructor I_name F_name 0
else dec_eq_diff_constructor
private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit :=
intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name)
meta def mk_dec_eq_instance_core : tactic unit :=
do I_name ← get_dec_eq_type_name,
env ← get_env,
v_name ← return `_v,
F_name ← return `_F,
num_indices ← return $ inductive_num_indices env I_name,
idx_names ← return $ list.map (λ (p : name × nat), mk_num_name p~>fst p~>snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)),
-- Use brec_on if type is recursive.
-- We store the functional in the variable F.
if is_recursive env I_name
then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ())
else intro v_name >> return (),
-- Apply cases to first element of type (I ...)
get_local v_name >>= cases,
all_goals (dec_eq_case_1 I_name F_name)
meta def mk_dec_eq_instance : tactic unit :=
do env ← get_env,
(pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf,
(const I_name ls) ← return (get_app_fn d1),
when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $
do { d1' ← whnf d1,
(app I_basic_const I_idx) ← return d1',
I_idx_type ← infer_type I_idx,
new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)),
assert `_basic_dec_eq new_goal,
swap,
to_expr `(_basic_dec_eq %%I_idx) >>= exact,
intro1,
return () },
mk_dec_eq_instance_core
end tactic
|
c40f241fd5e2f3f7f542dd73cf5e600ebe3b7bf7 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/witt_vector/witt_polynomial.lean | c7fac8cfdf5a6a50645bb5f3e31ad389d61e9e2b | [
"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 | 10,804 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import algebra.char_p.invertible
import data.fintype.card
import data.mv_polynomial.variables
import data.mv_polynomial.comm_ring
import data.mv_polynomial.expand
import data.zmod.basic
/-!
# Witt polynomials
To endow `witt_vector p R` with a ring structure,
we need to study the so-called Witt polynomials.
Fix a base value `p : ℕ`.
The `p`-adic Witt polynomials are an infinite family of polynomials
indexed by a natural number `n`, taking values in an arbitrary ring `R`.
The variables of these polynomials are represented by natural numbers.
The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`,
with exactly these variables when `R` has characteristic `0`.
These polynomials are used to define the addition and multiplication operators
on the type of Witt vectors. (While this type itself is not complicated,
the ring operations are what make it interesting.)
When the base `p` is invertible in `R`, the `p`-adic Witt polynomials
form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis.
## Main declarations
* `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R`
* `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra
generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial,
which upon being bound to the Witt polynomials yields `X n`.
* `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that
`bind₁ (X_in_terms_of_W p R) (W_ R n) = X n`
* `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement
## Notation
In this file we use the following notation
* `p` is a natural number, typically assumed to be prime.
* `R` and `S` are commutative rings
* `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
open mv_polynomial
open finset (hiding map)
open finsupp (single)
open_locale big_operators
local attribute [-simp] coe_eval₂_hom
variables (p : ℕ)
variables (R : Type*) [comm_ring R]
/-- `witt_polynomial p R n` is the `n`-th Witt polynomial
with respect to a prime `p` with coefficients in a commutative ring `R`.
It is defined as:
`∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/
noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R :=
∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i : R)
lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) :
witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) :=
begin
apply sum_congr rfl,
rintro i -,
rw [monomial_eq, finsupp.prod_single_index],
rw pow_zero,
end
/-! We set up notation locally to this file, to keep statements short and comprehensible.
This allows us to simply write `W n` or `W_ ℤ n`. -/
-- Notation with ring of coefficients explicit
localized "notation `W_` := witt_polynomial p" in witt
-- Notation with ring of coefficients implicit
localized "notation `W` := witt_polynomial p _" in witt
open_locale witt
open mv_polynomial
/- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring.
If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial
over the target ring. -/
section
variables {R} {S : Type*} [comm_ring S]
@[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) :
map f (W n) = W n :=
begin
rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl],
intros i hi,
rw [map_monomial, ring_hom.map_pow, map_nat_cast],
end
variables (R)
@[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) :
constant_coeff (witt_polynomial p R n) = 0 :=
begin
simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial],
rw [sum_eq_zero],
rintro i hi,
rw [if_neg],
rw [finsupp.single_eq_zero],
exact ne_of_gt (pow_pos hp.1.pos _)
end
@[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 :=
by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero]
@[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p :=
by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ_comm, range_one,
sum_singleton, one_mul, pow_one, C_1, pow_zero]
lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) :
aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) :=
by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index]
/--
Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial
by expanding the `n`th Witt polynomial by `p`.
-/
@[simp] lemma witt_polynomial_zmod_self (n : ℕ) :
W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) :=
begin
simp only [witt_polynomial_eq_sum_C_mul_X_pow],
rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul,
add_zero, alg_hom.map_sum, sum_congr rfl],
intros k hk,
rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ],
congr,
rw mem_range at hk,
rw [add_comm, add_tsub_assoc_of_le (nat.lt_succ_iff.mp hk), ← add_comm],
end
section p_prime
-- in fact, `0 < p` would be sufficient
variables [hp : fact p.prime]
include hp
lemma witt_polynomial_vars [char_zero R] (n : ℕ) :
(witt_polynomial p R n).vars = range (n + 1) :=
begin
have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i},
{ intro i,
refine vars_monomial_single i (pow_ne_zero _ hp.1.ne_zero) _,
rw [← nat.cast_pow, nat.cast_ne_zero],
exact pow_ne_zero i hp.1.ne_zero },
rw [witt_polynomial, vars_sum_of_disjoint],
{ simp only [this, int.nat_cast_eq_coe_nat, bUnion_singleton_eq_self], },
{ simp only [this, int.nat_cast_eq_coe_nat],
intros a b h,
apply disjoint_singleton_left.mpr,
rwa mem_singleton, },
end
lemma witt_polynomial_vars_subset (n : ℕ) :
(witt_polynomial p R n).vars ⊆ range (n + 1) :=
begin
rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ],
apply vars_map,
end
end p_prime
end
/-!
## Witt polynomials as a basis of the polynomial algebra
If `p` is invertible in `R`, then the Witt polynomials form a basis
of the polynomial algebra `mv_polynomial ℕ R`.
The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction.
-/
/-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials
that corresponds to the ordinary `X n`. -/
noncomputable def X_in_terms_of_W [invertible (p : R)] :
ℕ → mv_polynomial ℕ R
| n := (X n - (∑ i : fin n,
have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R)
lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} :
X_in_terms_of_W p R n =
(X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) :=
by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] }
@[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) :
constant_coeff (X_in_terms_of_W p R n) = 0 :=
begin
apply nat.strong_induction_on n; clear n,
intros n IH,
rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum,
constant_coeff_C, sum_eq_zero],
{ simp only [constant_coeff_X, sub_zero, mul_zero] },
{ intros m H,
rw mem_range at H,
simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H],
rw [zero_pow, mul_zero],
apply pow_pos hp.1.pos, }
end
@[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] :
X_in_terms_of_W p R 0 = X 0 :=
by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero]
section p_prime
variables [hp : fact p.prime]
include hp
lemma X_in_terms_of_W_vars_aux (n : ℕ) :
n ∈ (X_in_terms_of_W p ℚ n).vars ∧
(X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) :=
begin
apply nat.strong_induction_on n, clear n,
intros n ih,
rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ,
insert_eq],
swap 3, { apply nonzero_of_invertible },
work_on_goal 0
{ simp only [true_and, true_or, eq_self_iff_true,
mem_union, mem_singleton],
intro i,
rw [mem_union, mem_union],
apply or.imp id },
work_on_goal 1 { rw [vars_X, disjoint_singleton_left] },
all_goals
{ intro H,
replace H := vars_sum_subset _ _ H,
rw mem_bUnion at H,
rcases H with ⟨j, hj, H⟩,
rw vars_C_mul at H,
swap,
{ apply pow_ne_zero, exact_mod_cast hp.1.ne_zero },
rw mem_range at hj,
replace H := (ih j hj).2 (vars_pow _ _ H),
rw mem_range at H },
{ rw mem_range,
exact lt_of_lt_of_le H hj },
{ exact lt_irrefl n (lt_of_lt_of_le H hj) },
end
lemma X_in_terms_of_W_vars_subset (n : ℕ) :
(X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) :=
(X_in_terms_of_W_vars_aux p n).2
end p_prime
lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) :
X_in_terms_of_W p R n * C (p^n : R) =
X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) :=
by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one]
@[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) :
bind₁ (X_in_terms_of_W p R) (W_ R k) = X k :=
begin
rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum],
simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C],
rw [sum_range_succ_comm, tsub_self, pow_zero, pow_one, bind₁_X_right,
mul_comm, ← C_pow, X_in_terms_of_W_aux],
simp only [C_pow, bind₁_X_right, sub_add_cancel],
end
@[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) :
bind₁ (W_ R) (X_in_terms_of_W p R n) = X n :=
begin
apply nat.strong_induction_on n,
clear n, intros n H,
rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C,
alg_hom.map_sum],
have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n,
by simp only [witt_polynomial_eq_sum_C_mul_X_pow, tsub_self, sum_range_succ_comm,
pow_one, add_sub_cancel, pow_zero],
rw [sum_congr rfl, this],
{ -- this is really slow for some reason
rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] },
{ intros i h,
rw mem_range at h,
simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] },
end
|
8960c61a253e2339bf9860e5457765bee2799700 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/metric_space/hausdorff_dimension.lean | ba277a6b4c64bd4d10d5460f6aaf6f8bf714adab | [
"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 | 22,787 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import measure_theory.measure.hausdorff
/-!
# Hausdorff dimension
The Hausdorff dimension of a set `X` in an (extended) metric space is the unique number
`dimH s : ℝ≥0∞` such that for any `d : ℝ≥0` we have
- `μH[d] s = 0` if `dimH s < d`, and
- `μH[d] s = ∞` if `d < dimH s`.
In this file we define `dimH s` to be the Hausdorff dimension of `s`, then prove some basic
properties of Hausdorff dimension.
## Main definitions
* `measure_theory.dimH`: the Hausdorff dimension of a set. For the Hausdorff dimension of the whole
space we use `measure_theory.dimH (set.univ : set X)`.
## Main results
### Basic properties of Hausdorff dimension
* `hausdorff_measure_of_lt_dimH`, `dimH_le_of_hausdorff_measure_ne_top`,
`le_dimH_of_hausdorff_measure_eq_top`, `hausdorff_measure_of_dimH_lt`, `measure_zero_of_dimH_lt`,
`le_dimH_of_hausdorff_measure_ne_zero`, `dimH_of_hausdorff_measure_ne_zero_ne_top`: various forms
of the characteristic property of the Hausdorff dimension;
* `dimH_union`: the Hausdorff dimension of the union of two sets is the maximum of their Hausdorff
dimensions.
* `dimH_Union`, `dimH_bUnion`, `dimH_sUnion`: the Hausdorff dimension of a countable union of sets
is the supremum of their Hausdorff dimensions;
* `dimH_empty`, `dimH_singleton`, `set.subsingleton.dimH_zero`, `set.countable.dimH_zero` : `dimH s
= 0` whenever `s` is countable;
### (Pre)images under (anti)lipschitz and Hölder continuous maps
* `holder_with.dimH_image_le` etc: if `f : X → Y` is Hölder continuous with exponent `r > 0`, then
for any `s`, `dimH (f '' s) ≤ dimH s / r`. We prove versions of this statement for `holder_with`,
`holder_on_with`, and locally Hölder maps, as well as for `set.image` and `set.range`.
* `lipschitz_with.dimH_image_le` etc: Lipschitz continuous maps do not increase the Hausdorff
dimension of sets.
* for a map that is known to be both Lipschitz and antilipschitz (e.g., for an `isometry` or
a `continuous_linear_equiv`) we also prove `dimH (f '' s) = dimH s`.
### Hausdorff measure in `ℝⁿ`
* `real.dimH_of_nonempty_interior`: if `s` is a set in a finite dimensional real vector space `E`
with nonempty interior, then the Hausdorff dimension of `s` is equal to the dimension of `E`.
* `dense_compl_of_dimH_lt_finrank`: if `s` is a set in a finite dimensional real vector space `E`
with Hausdorff dimension strictly less than the dimension of `E`, the `s` has a dense complement.
* `cont_diff.dense_compl_range_of_finrank_lt_finrank`: the complement to the range of a `C¹`
smooth map is dense provided that the dimension of the domain is strictly less than the dimension
of the codomain.
## Notations
We use the following notation localized in `measure_theory`. It is defined in
`measure_theory.measure.hausdorff`.
- `μH[d]` : `measure_theory.measure.hausdorff_measure d`
## Implementation notes
* The definition of `dimH` explicitly uses `borel X` as a measurable space structure. This way we
can formulate lemmas about Hausdorff dimension without assuming that the environment has a
`[measurable_space X]` instance that is equal but possibly not defeq to `borel X`.
Lemma `dimH_def` unfolds this definition using whatever `[measurable_space X]` instance we have in
the environment (as long as it is equal to `borel X`).
* The definition `dimH` is irreducible; use API lemmas or `dimH_def` instead.
## Tags
Hausdorff measure, Hausdorff dimension, dimension
-/
open_locale measure_theory ennreal nnreal topological_space
open measure_theory measure_theory.measure set topological_space finite_dimensional filter
variables {ι X Y : Type*} [emetric_space X] [emetric_space Y]
/-- Hausdorff dimension of a set in an (e)metric space. -/
@[irreducible] noncomputable def dimH (s : set X) : ℝ≥0∞ :=
by { borelize X, exact ⨆ (d : ℝ≥0) (hd : @hausdorff_measure X _ _ ⟨rfl⟩ d s = ∞), d }
/-!
### Basic properties
-/
section measurable
variables [measurable_space X] [borel_space X]
/-- Unfold the definition of `dimH` using `[measurable_space X] [borel_space X]` from the
environment. -/
lemma dimH_def (s : set X) : dimH s = ⨆ (d : ℝ≥0) (hd : μH[d] s = ∞), d :=
by { borelize X, rw dimH }
lemma hausdorff_measure_of_lt_dimH {s : set X} {d : ℝ≥0} (h : ↑d < dimH s) : μH[d] s = ∞ :=
begin
simp only [dimH_def, lt_supr_iff] at h,
rcases h with ⟨d', hsd', hdd'⟩,
rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hdd',
exact top_unique (hsd' ▸ hausdorff_measure_mono hdd'.le _)
end
lemma dimH_le {s : set X} {d : ℝ≥0∞} (H : ∀ d' : ℝ≥0, μH[d'] s = ∞ → ↑d' ≤ d) : dimH s ≤ d :=
(dimH_def s).trans_le $ supr₂_le H
lemma dimH_le_of_hausdorff_measure_ne_top {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ ∞) :
dimH s ≤ d :=
le_of_not_lt $ mt hausdorff_measure_of_lt_dimH h
lemma le_dimH_of_hausdorff_measure_eq_top {s : set X} {d : ℝ≥0} (h : μH[d] s = ∞) :
↑d ≤ dimH s :=
by { rw dimH_def, exact le_supr₂ d h }
lemma hausdorff_measure_of_dimH_lt {s : set X} {d : ℝ≥0}
(h : dimH s < d) : μH[d] s = 0 :=
begin
rw dimH_def at h,
rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨d', hsd', hd'd⟩,
rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hd'd,
exact (hausdorff_measure_zero_or_top hd'd s).resolve_right (λ h, hsd'.not_le $ le_supr₂ d' h)
end
lemma measure_zero_of_dimH_lt {μ : measure X} {d : ℝ≥0}
(h : μ ≪ μH[d]) {s : set X} (hd : dimH s < d) :
μ s = 0 :=
h $ hausdorff_measure_of_dimH_lt hd
lemma le_dimH_of_hausdorff_measure_ne_zero {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ 0) :
↑d ≤ dimH s :=
le_of_not_lt $ mt hausdorff_measure_of_dimH_lt h
lemma dimH_of_hausdorff_measure_ne_zero_ne_top {d : ℝ≥0} {s : set X} (h : μH[d] s ≠ 0)
(h' : μH[d] s ≠ ∞) : dimH s = d :=
le_antisymm (dimH_le_of_hausdorff_measure_ne_top h') (le_dimH_of_hausdorff_measure_ne_zero h)
end measurable
@[mono] lemma dimH_mono {s t : set X} (h : s ⊆ t) : dimH s ≤ dimH t :=
begin
borelize X,
exact dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top $
top_unique $ hd ▸ measure_mono h)
end
lemma dimH_subsingleton {s : set X} (h : s.subsingleton) : dimH s = 0 :=
begin
borelize X,
apply le_antisymm _ (zero_le _),
refine dimH_le_of_hausdorff_measure_ne_top _,
exact ((hausdorff_measure_le_one_of_subsingleton h le_rfl).trans_lt ennreal.one_lt_top).ne,
end
alias dimH_subsingleton ← set.subsingleton.dimH_zero
@[simp] lemma dimH_empty : dimH (∅ : set X) = 0 := subsingleton_empty.dimH_zero
@[simp] lemma dimH_singleton (x : X) : dimH ({x} : set X) = 0 := subsingleton_singleton.dimH_zero
@[simp] lemma dimH_Union [encodable ι] (s : ι → set X) :
dimH (⋃ i, s i) = ⨆ i, dimH (s i) :=
begin
borelize X,
refine le_antisymm (dimH_le $ λ d hd, _) (supr_le $ λ i, dimH_mono $ subset_Union _ _),
contrapose! hd,
have : ∀ i, μH[d] (s i) = 0,
from λ i, hausdorff_measure_of_dimH_lt ((le_supr (λ i, dimH (s i)) i).trans_lt hd),
rw measure_Union_null this,
exact ennreal.zero_ne_top
end
@[simp] lemma dimH_bUnion {s : set ι} (hs : s.countable) (t : ι → set X) :
dimH (⋃ i ∈ s, t i) = ⨆ i ∈ s, dimH (t i) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union, dimH_Union, ← supr_subtype'']
end
@[simp] lemma dimH_sUnion {S : set (set X)} (hS : S.countable) : dimH (⋃₀ S) = ⨆ s ∈ S, dimH s :=
by rw [sUnion_eq_bUnion, dimH_bUnion hS]
@[simp] lemma dimH_union (s t : set X) : dimH (s ∪ t) = max (dimH s) (dimH t) :=
by rw [union_eq_Union, dimH_Union, supr_bool_eq, cond, cond, ennreal.sup_eq_max]
lemma dimH_countable {s : set X} (hs : s.countable) : dimH s = 0 :=
bUnion_of_singleton s ▸ by simp only [dimH_bUnion hs, dimH_singleton, ennreal.supr_zero_eq_zero]
alias dimH_countable ← set.countable.dimH_zero
lemma dimH_finite {s : set X} (hs : s.finite) : dimH s = 0 := hs.countable.dimH_zero
alias dimH_finite ← set.finite.dimH_zero
@[simp] lemma dimH_coe_finset (s : finset X) : dimH (s : set X) = 0 := s.finite_to_set.dimH_zero
alias dimH_coe_finset ← finset.dimH_zero
/-!
### Hausdorff dimension as the supremum of local Hausdorff dimensions
-/
section
variables [second_countable_topology X]
/-- If `r` is less than the Hausdorff dimension of a set `s` in an (extended) metric space with
second countable topology, then there exists a point `x ∈ s` such that every neighborhood
`t` of `x` within `s` has Hausdorff dimension greater than `r`. -/
lemma exists_mem_nhds_within_lt_dimH_of_lt_dimH {s : set X} {r : ℝ≥0∞} (h : r < dimH s) :
∃ x ∈ s, ∀ t ∈ 𝓝[s] x, r < dimH t :=
begin
contrapose! h, choose! t htx htr using h,
rcases countable_cover_nhds_within htx with ⟨S, hSs, hSc, hSU⟩,
calc dimH s ≤ dimH (⋃ x ∈ S, t x) : dimH_mono hSU
... = ⨆ x ∈ S, dimH (t x) : dimH_bUnion hSc _
... ≤ r : supr₂_le (λ x hx, htr x $ hSs hx)
end
/-- In an (extended) metric space with second countable topology, the Hausdorff dimension
of a set `s` is the supremum over `x ∈ s` of the limit superiors of `dimH t` along
`(𝓝[s] x).small_sets`. -/
lemma bsupr_limsup_dimH (s : set X) : (⨆ x ∈ s, limsup (𝓝[s] x).small_sets dimH) = dimH s :=
begin
refine le_antisymm (supr₂_le $ λ x hx, _) _,
{ refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _),
exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ },
{ refine le_of_forall_ge_of_dense (λ r hr, _),
rcases exists_mem_nhds_within_lt_dimH_of_lt_dimH hr with ⟨x, hxs, hxr⟩,
refine le_supr₂_of_le x hxs _, rw limsup_eq, refine le_Inf (λ b hb, _),
rcases eventually_small_sets.1 hb with ⟨t, htx, ht⟩,
exact (hxr t htx).le.trans (ht t subset.rfl) }
end
/-- In an (extended) metric space with second countable topology, the Hausdorff dimension
of a set `s` is the supremum over all `x` of the limit superiors of `dimH t` along
`(𝓝[s] x).small_sets`. -/
lemma supr_limsup_dimH (s : set X) : (⨆ x, limsup (𝓝[s] x).small_sets dimH) = dimH s :=
begin
refine le_antisymm (supr_le $ λ x, _) _,
{ refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _),
exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ },
{ rw ← bsupr_limsup_dimH, exact supr₂_le_supr _ _ }
end
end
/-!
### Hausdorff dimension and Hölder continuity
-/
variables {C K r : ℝ≥0} {f : X → Y} {s t : set X}
/-- If `f` is a Hölder continuous map with exponent `r > 0`, then `dimH (f '' s) ≤ dimH s / r`. -/
lemma holder_on_with.dimH_image_le (h : holder_on_with C r f s) (hr : 0 < r) :
dimH (f '' s) ≤ dimH s / r :=
begin
borelize [X, Y],
refine dimH_le (λ d hd, _),
have := h.hausdorff_measure_image_le hr d.coe_nonneg,
rw [hd, ennreal.coe_rpow_of_nonneg _ d.coe_nonneg, top_le_iff] at this,
have Hrd : μH[(r * d : ℝ≥0)] s = ⊤,
{ contrapose this, exact ennreal.mul_ne_top ennreal.coe_ne_top this },
rw [ennreal.le_div_iff_mul_le, mul_comm, ← ennreal.coe_mul],
exacts [le_dimH_of_hausdorff_measure_eq_top Hrd, or.inl (mt ennreal.coe_eq_zero.1 hr.ne'),
or.inl ennreal.coe_ne_top]
end
namespace holder_with
/-- If `f : X → Y` is Hölder continuous with a positive exponent `r`, then the Hausdorff dimension
of the image of a set `s` is at most `dimH s / r`. -/
lemma dimH_image_le (h : holder_with C r f) (hr : 0 < r) (s : set X) :
dimH (f '' s) ≤ dimH s / r :=
(h.holder_on_with s).dimH_image_le hr
/-- If `f` is a Hölder continuous map with exponent `r > 0`, then the Hausdorff dimension of its
range is at most the Hausdorff dimension of its domain divided by `r`. -/
lemma dimH_range_le (h : holder_with C r f) (hr : 0 < r) :
dimH (range f) ≤ dimH (univ : set X) / r :=
@image_univ _ _ f ▸ h.dimH_image_le hr univ
end holder_with
/-- If `s` is a set in a space `X` with second countable topology and `f : X → Y` is Hölder
continuous in a neighborhood within `s` of every point `x ∈ s` with the same positive exponent `r`
but possibly different coefficients, then the Hausdorff dimension of the image `f '' s` is at most
the Hausdorff dimension of `s` divided by `r`. -/
lemma dimH_image_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y}
(hr : 0 < r) {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C r f t) :
dimH (f '' s) ≤ dimH s / r :=
begin
choose! C t htn hC using hf,
rcases countable_cover_nhds_within htn with ⟨u, hus, huc, huU⟩,
replace huU := inter_eq_self_of_subset_left huU, rw inter_Union₂ at huU,
rw [← huU, image_Union₂, dimH_bUnion huc, dimH_bUnion huc], simp only [ennreal.supr_div],
exact supr₂_mono (λ x hx, ((hC x (hus hx)).mono (inter_subset_right _ _)).dimH_image_le hr)
end
/-- If `f : X → Y` is Hölder continuous in a neighborhood of every point `x : X` with the same
positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the range
of `f` is at most the Hausdorff dimension of `X` divided by `r`. -/
lemma dimH_range_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y}
(hr : 0 < r) (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), holder_on_with C r f s) :
dimH (range f) ≤ dimH (univ : set X) / r :=
begin
rw ← image_univ,
refine dimH_image_le_of_locally_holder_on hr (λ x _, _),
simpa only [exists_prop, nhds_within_univ] using hf x
end
/-!
### Hausdorff dimension and Lipschitz continuity
-/
/-- If `f : X → Y` is Lipschitz continuous on `s`, then `dimH (f '' s) ≤ dimH s`. -/
lemma lipschitz_on_with.dimH_image_le (h : lipschitz_on_with K f s) : dimH (f '' s) ≤ dimH s :=
by simpa using h.holder_on_with.dimH_image_le zero_lt_one
namespace lipschitz_with
/-- If `f` is a Lipschitz continuous map, then `dimH (f '' s) ≤ dimH s`. -/
lemma dimH_image_le (h : lipschitz_with K f) (s : set X) : dimH (f '' s) ≤ dimH s :=
(h.lipschitz_on_with s).dimH_image_le
/-- If `f` is a Lipschitz continuous map, then the Hausdorff dimension of its range is at most the
Hausdorff dimension of its domain. -/
lemma dimH_range_le (h : lipschitz_with K f) : dimH (range f) ≤ dimH (univ : set X) :=
@image_univ _ _ f ▸ h.dimH_image_le univ
end lipschitz_with
/-- If `s` is a set in an extended metric space `X` with second countable topology and `f : X → Y`
is Lipschitz in a neighborhood within `s` of every point `x ∈ s`, then the Hausdorff dimension of
the image `f '' s` is at most the Hausdorff dimension of `s`. -/
lemma dimH_image_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y}
{s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with C f t) :
dimH (f '' s) ≤ dimH s :=
begin
have : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C 1 f t,
by simpa only [holder_on_with_one] using hf,
simpa only [ennreal.coe_one, ennreal.div_one]
using dimH_image_le_of_locally_holder_on zero_lt_one this
end
/-- If `f : X → Y` is Lipschitz in a neighborhood of each point `x : X`, then the Hausdorff
dimension of `range f` is at most the Hausdorff dimension of `X`. -/
lemma dimH_range_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y}
(hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), lipschitz_on_with C f s) :
dimH (range f) ≤ dimH (univ : set X) :=
begin
rw ← image_univ,
refine dimH_image_le_of_locally_lipschitz_on (λ x _, _),
simpa only [exists_prop, nhds_within_univ] using hf x
end
namespace antilipschitz_with
lemma dimH_preimage_le (hf : antilipschitz_with K f) (s : set Y) :
dimH (f ⁻¹' s) ≤ dimH s :=
begin
borelize [X, Y],
refine dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top _),
have := hf.hausdorff_measure_preimage_le d.coe_nonneg s,
rw [hd, top_le_iff] at this,
contrapose! this,
exact ennreal.mul_ne_top (by simp) this
end
lemma le_dimH_image (hf : antilipschitz_with K f) (s : set X) :
dimH s ≤ dimH (f '' s) :=
calc dimH s ≤ dimH (f ⁻¹' (f '' s)) : dimH_mono (subset_preimage_image _ _)
... ≤ dimH (f '' s) : hf.dimH_preimage_le _
end antilipschitz_with
/-!
### Isometries preserve Hausdorff dimension
-/
lemma isometry.dimH_image (hf : isometry f) (s : set X) : dimH (f '' s) = dimH s :=
le_antisymm (hf.lipschitz.dimH_image_le _) (hf.antilipschitz.le_dimH_image _)
namespace isometric
@[simp] lemma dimH_image (e : X ≃ᵢ Y) (s : set X) : dimH (e '' s) = dimH s :=
e.isometry.dimH_image s
@[simp] lemma dimH_preimage (e : X ≃ᵢ Y) (s : set Y) : dimH (e ⁻¹' s) = dimH s :=
by rw [← e.image_symm, e.symm.dimH_image]
lemma dimH_univ (e : X ≃ᵢ Y) : dimH (univ : set X) = dimH (univ : set Y) :=
by rw [← e.dimH_preimage univ, preimage_univ]
end isometric
namespace continuous_linear_equiv
variables {𝕜 E F : Type*} [nondiscrete_normed_field 𝕜]
[normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F]
@[simp] lemma dimH_image (e : E ≃L[𝕜] F) (s : set E) : dimH (e '' s) = dimH s :=
le_antisymm (e.lipschitz.dimH_image_le s) $
by simpa only [e.symm_image_image] using e.symm.lipschitz.dimH_image_le (e '' s)
@[simp] lemma dimH_preimage (e : E ≃L[𝕜] F) (s : set F) : dimH (e ⁻¹' s) = dimH s :=
by rw [← e.image_symm_eq_preimage, e.symm.dimH_image]
lemma dimH_univ (e : E ≃L[𝕜] F) : dimH (univ : set E) = dimH (univ : set F) :=
by rw [← e.dimH_preimage, preimage_univ]
end continuous_linear_equiv
/-!
### Hausdorff dimension in a real vector space
-/
namespace real
variables {E : Type*} [fintype ι] [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
theorem dimH_ball_pi (x : ι → ℝ) {r : ℝ} (hr : 0 < r) :
dimH (metric.ball x r) = fintype.card ι :=
begin
casesI is_empty_or_nonempty ι,
{ rwa [dimH_subsingleton, eq_comm, nat.cast_eq_zero, fintype.card_eq_zero_iff],
exact λ x _ y _, subsingleton.elim x y },
{ rw ← ennreal.coe_nat,
have : μH[fintype.card ι] (metric.ball x r) = ennreal.of_real ((2 * r) ^ fintype.card ι),
by rw [hausdorff_measure_pi_real, real.volume_pi_ball _ hr],
refine dimH_of_hausdorff_measure_ne_zero_ne_top _ _; rw [nnreal.coe_nat_cast, this],
{ simp [pow_pos (mul_pos zero_lt_two hr)] },
{ exact ennreal.of_real_ne_top } }
end
theorem dimH_ball_pi_fin {n : ℕ} (x : fin n → ℝ) {r : ℝ} (hr : 0 < r) :
dimH (metric.ball x r) = n :=
by rw [dimH_ball_pi x hr, fintype.card_fin]
theorem dimH_univ_pi (ι : Type*) [fintype ι] : dimH (univ : set (ι → ℝ)) = fintype.card ι :=
by simp only [← metric.Union_ball_nat_succ (0 : ι → ℝ), dimH_Union,
dimH_ball_pi _ (nat.cast_add_one_pos _), supr_const]
theorem dimH_univ_pi_fin (n : ℕ) : dimH (univ : set (fin n → ℝ)) = n :=
by rw [dimH_univ_pi, fintype.card_fin]
theorem dimH_of_mem_nhds {x : E} {s : set E} (h : s ∈ 𝓝 x) :
dimH s = finrank ℝ E :=
begin
have e : E ≃L[ℝ] (fin (finrank ℝ E) → ℝ),
from continuous_linear_equiv.of_finrank_eq (finite_dimensional.finrank_fin_fun ℝ).symm,
rw ← e.dimH_image,
refine le_antisymm _ _,
{ exact (dimH_mono (subset_univ _)).trans_eq (dimH_univ_pi_fin _) },
{ have : e '' s ∈ 𝓝 (e x), by { rw ← e.map_nhds_eq, exact image_mem_map h },
rcases metric.nhds_basis_ball.mem_iff.1 this with ⟨r, hr0, hr⟩,
simpa only [dimH_ball_pi_fin (e x) hr0] using dimH_mono hr }
end
theorem dimH_of_nonempty_interior {s : set E} (h : (interior s).nonempty) :
dimH s = finrank ℝ E :=
let ⟨x, hx⟩ := h in dimH_of_mem_nhds (mem_interior_iff_mem_nhds.1 hx)
variable (E)
theorem dimH_univ_eq_finrank : dimH (univ : set E) = finrank ℝ E :=
dimH_of_mem_nhds (@univ_mem _ (𝓝 0))
theorem dimH_univ : dimH (univ : set ℝ) = 1 :=
by rw [dimH_univ_eq_finrank ℝ, finite_dimensional.finrank_self, nat.cast_one]
end real
variables {E F : Type*}
[normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
[normed_group F] [normed_space ℝ F]
theorem dense_compl_of_dimH_lt_finrank {s : set E} (hs : dimH s < finrank ℝ E) : dense sᶜ :=
begin
refine λ x, mem_closure_iff_nhds.2 (λ t ht, ne_empty_iff_nonempty.1 $ λ he, hs.not_le _),
rw [← diff_eq, diff_eq_empty] at he,
rw [← real.dimH_of_mem_nhds ht],
exact dimH_mono he
end
/-!
### Hausdorff dimension and `C¹`-smooth maps
`C¹`-smooth maps are locally Lipschitz continuous, hence they do not increase the Hausdorff
dimension of sets.
-/
/-- Let `f` be a function defined on a finite dimensional real normed space. If `f` is `C¹`-smooth
on a convex set `s`, then the Hausdorff dimension of `f '' s` is less than or equal to the Hausdorff
dimension of `s`.
TODO: do we actually need `convex ℝ s`? -/
lemma cont_diff_on.dimH_image_le {f : E → F} {s t : set E} (hf : cont_diff_on ℝ 1 f s)
(hc : convex ℝ s) (ht : t ⊆ s) :
dimH (f '' t) ≤ dimH t :=
dimH_image_le_of_locally_lipschitz_on $ λ x hx,
let ⟨C, u, hu, hf⟩ := (hf x (ht hx)).exists_lipschitz_on_with hc
in ⟨C, u, nhds_within_mono _ ht hu, hf⟩
/-- The Hausdorff dimension of the range of a `C¹`-smooth function defined on a finite dimensional
real normed space is at most the dimension of its domain as a vector space over `ℝ`. -/
lemma cont_diff.dimH_range_le {f : E → F} (h : cont_diff ℝ 1 f) :
dimH (range f) ≤ finrank ℝ E :=
calc dimH (range f) = dimH (f '' univ) : by rw image_univ
... ≤ dimH (univ : set E) : h.cont_diff_on.dimH_image_le convex_univ subset.rfl
... = finrank ℝ E : real.dimH_univ_eq_finrank E
/-- A particular case of Sard's Theorem. Let `f : E → F` be a map between finite dimensional real
vector spaces. Suppose that `f` is `C¹` smooth on a convex set `s` of Hausdorff dimension strictly
less than the dimension of `F`. Then the complement of the image `f '' s` is dense in `F`. -/
lemma cont_diff_on.dense_compl_image_of_dimH_lt_finrank [finite_dimensional ℝ F] {f : E → F}
{s t : set E} (h : cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s)
(htF : dimH t < finrank ℝ F) :
dense (f '' t)ᶜ :=
dense_compl_of_dimH_lt_finrank $ (h.dimH_image_le hc ht).trans_lt htF
/-- A particular case of Sard's Theorem. If `f` is a `C¹` smooth map from a real vector space to a
real vector space `F` of strictly larger dimension, then the complement of the range of `f` is dense
in `F`. -/
lemma cont_diff.dense_compl_range_of_finrank_lt_finrank [finite_dimensional ℝ F] {f : E → F}
(h : cont_diff ℝ 1 f) (hEF : finrank ℝ E < finrank ℝ F) :
dense (range f)ᶜ :=
dense_compl_of_dimH_lt_finrank $ h.dimH_range_le.trans_lt $ ennreal.coe_nat_lt_coe_nat.2 hEF
|
26119b0e10dc64810a5fb7d4b29adfcc225efd2b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/witt_vector/truncated_auto.lean | 08abb692eed2c3d593af865417499ebae366663e | [] | 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 | 16,512 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.witt_vector.init_tail
import Mathlib.tactic.equiv_rw
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Truncated Witt vectors
The ring of truncated Witt vectors (of length `n`) is a quotient of the ring of Witt vectors.
It retains the first `n` coefficients of each Witt vector.
In this file, we set up the basic quotient API for this ring.
The ring of Witt vectors is the projective limit of all the rings of truncated Witt vectors.
## Main declarations
- `truncated_witt_vector`: the underlying type of the ring of truncated Witt vectors
- `truncated_witt_vector.comm_ring`: the ring structure on truncated Witt vectors
- `witt_vector.truncate`: the quotient homomorphism that truncates a Witt vector,
to obtain a truncated Witt vector
- `truncated_witt_vector.truncate`: the homomorphism that truncates
a truncated Witt vector of length `n` to one of length `m` (for some `m ≤ n`)
- `witt_vector.lift`: the unique ring homomorphism into the ring of Witt vectors
that is compatible with a family of ring homomorphisms to the truncated Witt vectors:
this realizes the ring of Witt vectors as projective limit of the rings of truncated Witt vectors
-/
/--
A truncated Witt vector over `R` is a vector of elements of `R`,
i.e., the first `n` coefficients of a Witt vector.
We will define operations on this type that are compatible with the (untruncated) Witt
vector operations.
`truncated_witt_vector p n R` takes a parameter `p : ℕ` that is not used in the definition.
In practice, this number `p` is assumed to be a prime number,
and under this assumption we construct a ring structure on `truncated_witt_vector p n R`.
(`truncated_witt_vector p₁ n R` and `truncated_witt_vector p₂ n R` are definitionally
equal as types but will have different ring operations.)
-/
def truncated_witt_vector (p : ℕ) (n : ℕ) (R : Type u_1) := fin n → R
protected instance truncated_witt_vector.inhabited (p : ℕ) (n : ℕ) (R : Type u_1) [Inhabited R] :
Inhabited (truncated_witt_vector p n R) :=
{ default := fun (_x : fin n) => Inhabited.default }
namespace truncated_witt_vector
/-- Create a `truncated_witt_vector` from a vector `x`. -/
def mk (p : ℕ) {n : ℕ} {R : Type u_1} (x : fin n → R) : truncated_witt_vector p n R := x
/-- `x.coeff i` is the `i`th entry of `x`. -/
def coeff {p : ℕ} {n : ℕ} {R : Type u_1} (i : fin n) (x : truncated_witt_vector p n R) : R := x i
theorem ext {p : ℕ} {n : ℕ} {R : Type u_1} {x : truncated_witt_vector p n R}
{y : truncated_witt_vector p n R} (h : ∀ (i : fin n), coeff i x = coeff i y) : x = y :=
funext h
theorem ext_iff {p : ℕ} {n : ℕ} {R : Type u_1} {x : truncated_witt_vector p n R}
{y : truncated_witt_vector p n R} : x = y ↔ ∀ (i : fin n), coeff i x = coeff i y :=
{ mp :=
fun (h : x = y) (i : fin n) =>
eq.mpr (id (Eq._oldrec (Eq.refl (coeff i x = coeff i y)) h)) (Eq.refl (coeff i y)),
mpr := ext }
@[simp] theorem coeff_mk {p : ℕ} {n : ℕ} {R : Type u_1} (x : fin n → R) (i : fin n) :
coeff i (mk p x) = x i :=
rfl
@[simp] theorem mk_coeff {p : ℕ} {n : ℕ} {R : Type u_1} (x : truncated_witt_vector p n R) :
(mk p fun (i : fin n) => coeff i x) = x :=
sorry
/--
We can turn a truncated Witt vector `x` into a Witt vector
by setting all coefficients after `x` to be 0.
-/
def out {p : ℕ} {n : ℕ} {R : Type u_1} [comm_ring R] (x : truncated_witt_vector p n R) :
witt_vector p R :=
witt_vector.mk p
fun (i : ℕ) =>
dite (i < n) (fun (h : i < n) => coeff { val := i, property := h } x) fun (h : ¬i < n) => 0
@[simp] theorem coeff_out {p : ℕ} {n : ℕ} {R : Type u_1} [comm_ring R]
(x : truncated_witt_vector p n R) (i : fin n) : witt_vector.coeff (out x) ↑i = coeff i x :=
sorry
theorem out_injective {p : ℕ} {n : ℕ} {R : Type u_1} [comm_ring R] : function.injective out := sorry
end truncated_witt_vector
namespace witt_vector
/-- `truncate_fun n x` uses the first `n` entries of `x` to construct a `truncated_witt_vector`,
which has the same base `p` as `x`.
This function is bundled into a ring homomorphism in `witt_vector.truncate` -/
def truncate_fun {p : ℕ} (n : ℕ) {R : Type u_1} (x : witt_vector p R) :
truncated_witt_vector p n R :=
truncated_witt_vector.mk p fun (i : fin n) => coeff x ↑i
@[simp] theorem coeff_truncate_fun {p : ℕ} {n : ℕ} {R : Type u_1} (x : witt_vector p R)
(i : fin n) : truncated_witt_vector.coeff i (truncate_fun n x) = coeff x ↑i :=
sorry
@[simp] theorem out_truncate_fun {p : ℕ} {n : ℕ} {R : Type u_1} [comm_ring R]
(x : witt_vector p R) : truncated_witt_vector.out (truncate_fun n x) = init n x :=
sorry
end witt_vector
namespace truncated_witt_vector
@[simp] theorem truncate_fun_out {p : ℕ} {n : ℕ} {R : Type u_1} [comm_ring R]
(x : truncated_witt_vector p n R) : witt_vector.truncate_fun n (out x) = x :=
sorry
protected instance has_zero (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
HasZero (truncated_witt_vector p n R) :=
{ zero := witt_vector.truncate_fun n 0 }
protected instance has_one (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
HasOne (truncated_witt_vector p n R) :=
{ one := witt_vector.truncate_fun n 1 }
protected instance has_add (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
Add (truncated_witt_vector p n R) :=
{ add := fun (x y : truncated_witt_vector p n R) => witt_vector.truncate_fun n (out x + out y) }
protected instance has_mul (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
Mul (truncated_witt_vector p n R) :=
{ mul := fun (x y : truncated_witt_vector p n R) => witt_vector.truncate_fun n (out x * out y) }
protected instance has_neg (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
Neg (truncated_witt_vector p n R) :=
{ neg := fun (x : truncated_witt_vector p n R) => witt_vector.truncate_fun n (-out x) }
@[simp] theorem coeff_zero (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R]
(i : fin n) : coeff i 0 = 0 :=
id
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coeff i (witt_vector.truncate_fun n 0) = 0))
(witt_vector.coeff_truncate_fun 0 i)))
(eq.mpr
(id (Eq._oldrec (Eq.refl (witt_vector.coeff 0 ↑i = 0)) (witt_vector.zero_coeff p R ↑i)))
(Eq.refl 0)))
end truncated_witt_vector
/-- A macro tactic used to prove that `truncate_fun` respects ring operations. -/
namespace witt_vector
theorem truncate_fun_surjective (p : ℕ) (n : ℕ) (R : Type u_1) [comm_ring R] :
function.surjective (truncate_fun n) :=
fun (x : truncated_witt_vector p n R) =>
Exists.intro (truncated_witt_vector.out x) (truncated_witt_vector.truncate_fun_out x)
@[simp] theorem truncate_fun_zero (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1)
[comm_ring R] : truncate_fun n 0 = 0 :=
rfl
@[simp] theorem truncate_fun_one (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1)
[comm_ring R] : truncate_fun n 1 = 1 :=
rfl
@[simp] theorem truncate_fun_add {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1}
[comm_ring R] (x : witt_vector p R) (y : witt_vector p R) :
truncate_fun n (x + y) = truncate_fun n x + truncate_fun n y :=
sorry
@[simp] theorem truncate_fun_mul {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1}
[comm_ring R] (x : witt_vector p R) (y : witt_vector p R) :
truncate_fun n (x * y) = truncate_fun n x * truncate_fun n y :=
sorry
theorem truncate_fun_neg {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1} [comm_ring R]
(x : witt_vector p R) : truncate_fun n (-x) = -truncate_fun n x :=
sorry
end witt_vector
namespace truncated_witt_vector
protected instance comm_ring (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1)
[comm_ring R] : comm_ring (truncated_witt_vector p n R) :=
function.surjective.comm_ring (witt_vector.truncate_fun n)
(witt_vector.truncate_fun_surjective p n R) (witt_vector.truncate_fun_zero p n R)
(witt_vector.truncate_fun_one p n R) (witt_vector.truncate_fun_add n)
(witt_vector.truncate_fun_mul n) (witt_vector.truncate_fun_neg n)
end truncated_witt_vector
namespace witt_vector
/-- `truncate n` is a ring homomorphism that truncates `x` to its first `n` entries
to obtain a `truncated_witt_vector`, which has the same base `p` as `x`. -/
def truncate {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1} [comm_ring R] :
witt_vector p R →+* truncated_witt_vector p n R :=
ring_hom.mk (truncate_fun n) (truncate_fun_one p n R) (truncate_fun_mul n)
(truncate_fun_zero p n R) (truncate_fun_add n)
theorem truncate_surjective (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (R : Type u_1) [comm_ring R] :
function.surjective ⇑(truncate n) :=
truncate_fun_surjective p n R
@[simp] theorem coeff_truncate {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} {R : Type u_1}
[comm_ring R] (x : witt_vector p R) (i : fin n) :
truncated_witt_vector.coeff i (coe_fn (truncate n) x) = coeff x ↑i :=
coeff_truncate_fun x i
theorem mem_ker_truncate {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1} [comm_ring R]
(x : witt_vector p R) : x ∈ ring_hom.ker (truncate n) ↔ ∀ (i : ℕ), i < n → coeff x i = 0 :=
sorry
@[simp] theorem truncate_mk (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1} [comm_ring R]
(f : ℕ → R) :
coe_fn (truncate n) (mk p f) = truncated_witt_vector.mk p fun (k : fin n) => f ↑k :=
sorry
end witt_vector
namespace truncated_witt_vector
/--
A ring homomorphism that truncates a truncated Witt vector of length `m` to
a truncated Witt vector of length `n`, for `n ≤ m`.
-/
def truncate {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} {R : Type u_1} [comm_ring R] {m : ℕ}
(hm : n ≤ m) : truncated_witt_vector p m R →+* truncated_witt_vector p n R :=
ring_hom.lift_of_surjective (witt_vector.truncate m) (witt_vector.truncate_surjective p m R)
(witt_vector.truncate n) sorry
@[simp] theorem truncate_comp_witt_vector_truncate {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ}
{R : Type u_1} [comm_ring R] {m : ℕ} (hm : n ≤ m) :
ring_hom.comp (truncate hm) (witt_vector.truncate m) = witt_vector.truncate n :=
ring_hom.lift_of_surjective_comp (witt_vector.truncate m) (witt_vector.truncate_surjective p m R)
(witt_vector.truncate n) (truncate._proof_1 hm)
@[simp] theorem truncate_witt_vector_truncate {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ}
{R : Type u_1} [comm_ring R] {m : ℕ} (hm : n ≤ m) (x : witt_vector p R) :
coe_fn (truncate hm) (coe_fn (witt_vector.truncate m) x) = coe_fn (witt_vector.truncate n) x :=
ring_hom.lift_of_surjective_comp_apply (witt_vector.truncate m)
(witt_vector.truncate_surjective p m R) (witt_vector.truncate n) (truncate._proof_1 hm) x
@[simp] theorem truncate_truncate {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{n₁ : ℕ} {n₂ : ℕ} {n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) (x : truncated_witt_vector p n₃ R) :
coe_fn (truncate h1) (coe_fn (truncate h2) x) = coe_fn (truncate (has_le.le.trans h1 h2)) x :=
sorry
@[simp] theorem truncate_comp {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{n₁ : ℕ} {n₂ : ℕ} {n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) :
ring_hom.comp (truncate h1) (truncate h2) = truncate (has_le.le.trans h1 h2) :=
sorry
theorem truncate_surjective {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} {R : Type u_1} [comm_ring R]
{m : ℕ} (hm : n ≤ m) : function.surjective ⇑(truncate hm) :=
sorry
@[simp] theorem coeff_truncate {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} {R : Type u_1}
[comm_ring R] {m : ℕ} (hm : n ≤ m) (i : fin n) (x : truncated_witt_vector p m R) :
coeff i (coe_fn (truncate hm) x) = coeff (coe_fn (fin.cast_le hm) i) x :=
sorry
protected instance fintype {p : ℕ} {n : ℕ} {R : Type u_1} [fintype R] :
fintype (truncated_witt_vector p n R) :=
pi.fintype
theorem card (p : ℕ) (n : ℕ) {R : Type u_1} [fintype R] :
fintype.card (truncated_witt_vector p n R) = fintype.card R ^ n :=
sorry
theorem infi_ker_truncate {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R] :
(infi fun (i : ℕ) => ring_hom.ker (witt_vector.truncate i)) = ⊥ :=
sorry
end truncated_witt_vector
namespace witt_vector
/--
Given a family `fₖ : S → truncated_witt_vector p k R` and `s : S`, we produce a Witt vector by
defining the `k`th entry to be the final entry of `fₖ s`.
-/
def lift_fun {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R] {S : Type u_2}
[semiring S] (f : (k : ℕ) → S →+* truncated_witt_vector p k R) (s : S) : witt_vector p R :=
mk p fun (k : ℕ) => truncated_witt_vector.coeff (fin.last k) (coe_fn (f (k + 1)) s)
@[simp] theorem truncate_lift_fun {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1}
[comm_ring R] {S : Type u_2} [semiring S] {f : (k : ℕ) → S →+* truncated_witt_vector p k R}
(f_compat :
∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂), ring_hom.comp (truncated_witt_vector.truncate hk) (f k₂) = f k₁)
(s : S) : coe_fn (truncate n) (lift_fun f s) = coe_fn (f n) s :=
sorry
/--
Given compatible ring homs from `S` into `truncated_witt_vector n` for each `n`, we can lift these
to a ring hom `S → 𝕎 R`.
`lift` defines the universal property of `𝕎 R` as the inverse limit of `truncated_witt_vector n`.
-/
def lift {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R] {S : Type u_2} [semiring S]
(f : (k : ℕ) → S →+* truncated_witt_vector p k R)
(f_compat :
∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂),
ring_hom.comp (truncated_witt_vector.truncate hk) (f k₂) = f k₁) :
S →+* witt_vector p R :=
ring_hom.mk (lift_fun f) sorry sorry sorry sorry
@[simp] theorem truncate_lift {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1} [comm_ring R]
{S : Type u_2} [semiring S] {f : (k : ℕ) → S →+* truncated_witt_vector p k R}
(f_compat :
∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂), ring_hom.comp (truncated_witt_vector.truncate hk) (f k₂) = f k₁)
(s : S) :
coe_fn (truncate n) (coe_fn (lift (fun (k₂ : ℕ) => f k₂) f_compat) s) = coe_fn (f n) s :=
truncate_lift_fun n f_compat s
@[simp] theorem truncate_comp_lift {p : ℕ} [hp : fact (nat.prime p)] (n : ℕ) {R : Type u_1}
[comm_ring R] {S : Type u_2} [semiring S] {f : (k : ℕ) → S →+* truncated_witt_vector p k R}
(f_compat :
∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂),
ring_hom.comp (truncated_witt_vector.truncate hk) (f k₂) = f k₁) :
ring_hom.comp (truncate n) (lift (fun (k₂ : ℕ) => f k₂) f_compat) = f n :=
sorry
/-- The uniqueness part of the universal property of `𝕎 R`. -/
theorem lift_unique {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R] {S : Type u_2}
[semiring S] {f : (k : ℕ) → S →+* truncated_witt_vector p k R}
(f_compat :
∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂), ring_hom.comp (truncated_witt_vector.truncate hk) (f k₂) = f k₁)
(g : S →+* witt_vector p R) (g_compat : ∀ (k : ℕ), ring_hom.comp (truncate k) g = f k) :
lift (fun (k₂ : ℕ) => f k₂) f_compat = g :=
sorry
/-- The universal property of `𝕎 R` as projective limit of truncated Witt vector rings. -/
@[simp] theorem lift_equiv_symm_apply_coe {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1}
[comm_ring R] {S : Type u_2} [semiring S] (g : S →+* witt_vector p R) (k : ℕ) :
coe (coe_fn (equiv.symm lift_equiv) g) k = ring_hom.comp (truncate k) g :=
Eq.refl (coe (coe_fn (equiv.symm lift_equiv) g) k)
theorem hom_ext {p : ℕ} [hp : fact (nat.prime p)] {R : Type u_1} [comm_ring R] {S : Type u_2}
[semiring S] (g₁ : S →+* witt_vector p R) (g₂ : S →+* witt_vector p R)
(h : ∀ (k : ℕ), ring_hom.comp (truncate k) g₁ = ring_hom.comp (truncate k) g₂) : g₁ = g₂ :=
equiv.injective (equiv.symm lift_equiv) (subtype.ext (funext h))
end Mathlib |
7690d71a993dc83aaafd8e48cb33139b826505ec | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1258.lean | add8dceff455c20c9df962bd78f4989093a880eb | [
"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 | 188 | lean | constant P : list ℕ → list ℕ → Prop
lemma foo (xs : list ℕ) : Π (ns : list ℕ), P xs ns
| [] := sorry
| (n::ns) := begin clear foo, cases xs, exact sorry, exact sorry end
|
1359fe5b5cc21e641b97c4f4dcdf9f1c79fb1962 | 076f5040b63237c6dd928c6401329ed5adcb0e44 | /instructor-notes/2019.10.03.review.lean | eb5f66fb04c877b4607011342de67c19687df98e | [] | 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 | 4,168 | lean |
namespace review
/-
The identity function for any type:
a *polymorphic* identity function.
Key points: type parameters (i.e.,
polymorphism); type inference; and
implicit type arguments.
-/
def id (α : Type) (a : α) : α := a
/-
Examples of its use. Note how we
have to specific type argument
values explicitly--bool string,
nat--even though they clearly can
be inferred from the value of the
second argument.
-/
#eval id bool tt
#eval id string "I love polym!"
#eval id nat 4
#check id
/-
We can ask Lean to infer the value
of the first, type, parameter and to
make it implicit, so that we don't
have to provide it explicitly when
we use the id' function. Here we also
use a "by cases" rather than C-style
presentation of this function.
-/
def id' {α : Type} : α → α
| a := a
/-
Sometimes we want to turn off implicit
inference of arguments. We do that by
prefixing an expression that uses implicit
arguments with @.
-/
#check (@id' nat)
#eval @id' bool tt
/-
Examples with implicit type arguments.
-/
#eval id' "I love polym!"
#eval id' 4
#check id'
/-
Boxed again: A NON-polymorphic version
of a "boxed value" data type -- this one
is dedicated to "boxing up" nat values.
-/
inductive boxed_nat : Type
| box_nat : ℕ → boxed_nat
inductive boxed_nat' : Type
| box_nat (n : ℕ) : boxed_nat'
open boxed_nat
def unbox_nat : boxed_nat → ℕ
| (box_nat v) := v
#eval unbox_nat (box_nat 4)
/-
Here's a corresponding polymorphic
version, in which we've *abstracted*
from nat to "any type" as indicated
by the type argument, α.
-/
inductive boxed (α : Type) : Type
| box : α → boxed
-- Another way to write the same
-- "box" constructor, in more of
-- a C style.
inductive boxed' (α : Type) : Type
| box (n : α) : boxed'
open boxed
-- A polymorphic unbox function taking
-- its type argument implicitly.
def unbox {α : Type} : boxed α → α
| (box v) := v
#eval unbox (box 4)
#eval unbox (box tt)
#eval unbox (box "I love this stuff!")
/-
A polymorphic "product type", prod. A product
type is a type whose values are ordered pairs.
Here the types of the first and second elements
of such a pair are given by the values of two
type arguments, α and β respectively. The pair
constructor takes a value of type α and one of
type β and yeilds the term (pair a b), whic we
will interpret as representing the ordered pair,
(a, b), a concept that should be familiar from
basic high school algebra.
-/
inductive prod (α β : Type) : Type
| pair (a : α) (b : β) : prod
/-
Functions that take a pair (or a longer
"tuple") and that return one of its
component values is called a projection
function. Here we define two polymorphic
projection functions for ordered pairs:
fst returns the first element of a given
pair, and snd returns the second one.
-/
def fst {α β : Type} : prod α β → α
| (prod.pair a b) := a
def snd {α β : Type} : prod α β → β
| (prod.pair a b) := b
/-
This function swaps the values in a pair.
Take note of the type of this polymorphic
function.
-/
def swap {α β : Type} : prod α β → prod β α
| (prod.pair a b) := prod.pair b a
/-
Examples.
-/
def p1 := prod.pair 3 tt
#eval fst p1
#eval snd p1
#reduce swap p1
def id' {α : Type} : α → α :=
λ (a : α), a
def id {α : Type} (a : α) : α := a
#eval id 3
#eval id tt
#eval id "I love type arguments!"
/-
Reviewing simple polymorphic types
-/
inductive boxed (α : Type) : Type
| box : α → boxed
open boxed
def unbox (α : Type) : boxed α → α
| (box a) := a
/-
A more interesting polymorphic type.
The type, prod, of ordered pairs.
-/
inductive prod (α β : Type) : Type
| pair (a : α) (b : β) : prod
def p1 : prod bool nat := prod.pair ff 3
def fst {α β : Type} : prod α β → α
| (prod.pair a b) := a
def snd {α β : Type} : prod α β → β
| (prod.pair a b) := b
def swap {α β : Type} : prod α β → prod β α
| (prod.pair a b) := prod.pair b a
#eval fst p1
#eval snd p1
#reduce swap p1
#check list
/-
A polymorphic list type!
-/
inductive mlist (α : Type) : Type
| nil : mlist
| cons (h : α) (t : mlist) : mlist
end review |
ed386d166429d936deaff54bf94a642c2c39edf6 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/inequality/14.lean | b869bc989bf83537a047465daf86b25d27b1cef4 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 169 | lean | theorem add_le_add_left (a b : mynat) (h : a ≤ b) (t : mynat) :
t + a ≤ t + b :=
begin
rw add_comm t a,
rw add_comm t b,
exact add_le_add_right a b h t,
end
|
56671e650876be4cbef479f60001e62abde17de7 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Init/Classical.lean | 480eb14d4c51e575faafe065252e0bc9ea5a9f8b | [
"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 | 5,574 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
import Init.NotationExtra
universe u v
/-! # Classical reasoning support -/
namespace Classical
noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : ∃ x, p x) : {x // p x} :=
choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩
noncomputable def choose {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α :=
(indefiniteDescription p h).val
theorem choose_spec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (choose h) :=
(indefiniteDescription p h).property
/-- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/
theorem em (p : Prop) : p ∨ ¬p :=
let U (x : Prop) : Prop := x = True ∨ p
let V (x : Prop) : Prop := x = False ∨ p
have exU : ∃ x, U x := ⟨True, Or.inl rfl⟩
have exV : ∃ x, V x := ⟨False, Or.inl rfl⟩
let u : Prop := choose exU
let v : Prop := choose exV
have u_def : U u := choose_spec exU
have v_def : V v := choose_spec exV
have not_uv_or_p : u ≠ v ∨ p :=
match u_def, v_def with
| Or.inr h, _ => Or.inr h
| _, Or.inr h => Or.inr h
| Or.inl hut, Or.inl hvf =>
have hne : u ≠ v := by simp [hvf, hut, true_ne_false]
Or.inl hne
have p_implies_uv : p → u = v :=
fun hp =>
have hpred : U = V :=
funext fun x =>
have hl : (x = True ∨ p) → (x = False ∨ p) :=
fun _ => Or.inr hp
have hr : (x = False ∨ p) → (x = True ∨ p) :=
fun _ => Or.inr hp
show (x = True ∨ p) = (x = False ∨ p) from
propext (Iff.intro hl hr)
have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV := by
rw [hpred]; intros; rfl
show u = v from h₀ _ _
match not_uv_or_p with
| Or.inl hne => Or.inr (mt p_implies_uv hne)
| Or.inr h => Or.inl h
theorem exists_true_of_nonempty {α : Sort u} : Nonempty α → ∃ _ : α, True
| ⟨x⟩ => ⟨x, trivial⟩
noncomputable def inhabited_of_nonempty {α : Sort u} (h : Nonempty α) : Inhabited α :=
⟨choice h⟩
noncomputable def inhabited_of_exists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Inhabited α :=
inhabited_of_nonempty (Exists.elim h (fun w _ => ⟨w⟩))
/-- All propositions are `Decidable`. -/
noncomputable scoped instance (priority := low) propDecidable (a : Prop) : Decidable a :=
choice <| match em a with
| Or.inl h => ⟨isTrue h⟩
| Or.inr h => ⟨isFalse h⟩
noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) where
default := inferInstance
noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α :=
fun _ _ => inferInstance
noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) :=
match (propDecidable (Nonempty α)) with
| (isTrue hp) => PSum.inl (@default _ (inhabited_of_nonempty hp))
| (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn)
noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // (∃ y : α, p y) → p x} :=
@dite _ (∃ x : α, p x) (propDecidable _)
(fun (hp : ∃ x : α, p x) =>
show {x : α // (∃ y : α, p y) → p x} from
let xp := indefiniteDescription _ hp;
⟨xp.val, fun _ => xp.property⟩)
(fun hp => ⟨choice h, fun h => absurd h hp⟩)
/-- the Hilbert epsilon Function -/
noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α :=
(strongIndefiniteDescription p h).val
theorem epsilon_spec_aux {α : Sort u} (h : Nonempty α) (p : α → Prop) : (∃ y, p y) → p (@epsilon α h p) :=
(strongIndefiniteDescription p h).property
theorem epsilon_spec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) : p (@epsilon α (nonempty_of_exists hex) p) :=
epsilon_spec_aux (nonempty_of_exists hex) p hex
theorem epsilon_singleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x :=
@epsilon_spec α (fun y => y = x) ⟨x, rfl⟩
/-- the axiom of choice -/
theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, ∃ y, r x y) : ∃ (f : ∀ x, β x), ∀ x, r x (f x) :=
⟨_, fun x => choose_spec (h x)⟩
theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, ∃ y, p x y) ↔ ∃ (f : ∀ x, b x), ∀ x, p x (f x) :=
⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩
theorem propComplete (a : Prop) : a = True ∨ a = False :=
match em a with
| Or.inl ha => Or.inl (propext (Iff.intro (fun _ => ⟨⟩) (fun _ => ha)))
| Or.inr hn => Or.inr (propext (Iff.intro (fun h => hn h) (fun h => False.elim h)))
-- this supercedes byCases in Decidable
theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q :=
Decidable.byCases (dec := propDecidable _) hpq hnpq
-- this supercedes byContradiction in Decidable
theorem byContradiction {p : Prop} (h : ¬p → False) : p :=
Decidable.byContradiction (dec := propDecidable _) h
/--
`by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch.
-/
syntax "by_cases" (atomic(ident ":"))? term : tactic
macro_rules
| `(tactic| by_cases $h : $e) =>
`(tactic|
cases em $e with
| inl $h => _
| inr $h => _)
| `(tactic| by_cases $e) =>
`(tactic|
cases em $e with
| inl h => _
| inr h => _)
end Classical
|
238bf43b26dc8a541823009bfbef4c91d4c1a2ba | 3863d2564418bccb1859e057bf5a4ef240e75fd7 | /hott/types/fiber.hlean | 700602e7bc7e9015dcbe3eec2b3f281d6112fa8b | [
"Apache-2.0"
] | permissive | JacobGross/lean | 118bbb067ff4d4af48a266face2c7eb9868fa91c | eb26087df940c54337cb807b4bc6d345d1fc1085 | refs/heads/master | 1,582,735,011,532 | 1,462,557,826,000 | 1,462,557,826,000 | 46,451,196 | 0 | 0 | null | 1,462,557,826,000 | 1,447,885,161,000 | C++ | UTF-8 | Lean | false | false | 6,256 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about fibers
-/
import .sigma .eq .pi
open equiv sigma sigma.ops eq pi
structure fiber {A B : Type} (f : A → B) (b : B) :=
(point : A)
(point_eq : f point = b)
namespace fiber
variables {A B : Type} {f : A → B} {b : B}
protected definition sigma_char [constructor]
(f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) :=
begin
fapply equiv.MK,
{intro x, exact ⟨point x, point_eq x⟩},
{intro x, exact (fiber.mk x.1 x.2)},
{intro x, exact abstract begin cases x, apply idp end end},
{intro x, exact abstract begin cases x, apply idp end end},
end
definition fiber_eq_equiv (x y : fiber f b)
: (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) :=
begin
apply equiv.trans,
apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char,
apply equiv.trans,
apply sigma_eq_equiv,
apply sigma_equiv_sigma_right,
intro p,
apply pathover_eq_equiv_Fl,
end
definition fiber_eq {x y : fiber f b} (p : point x = point y)
(q : point_eq x = ap f p ⬝ point_eq y) : x = y :=
to_inv !fiber_eq_equiv ⟨p, q⟩
open is_trunc
definition fiber_pr1 (B : A → Type) (a : A) : fiber (pr1 : (Σa, B a) → A) a ≃ B a :=
calc
fiber pr1 a ≃ Σu, u.1 = a : fiber.sigma_char
... ≃ Σa' (b : B a'), a' = a : sigma_assoc_equiv
... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', !comm_equiv_nondep)
... ≃ Σu, B u.1 : sigma_assoc_equiv
... ≃ B a : !sigma_equiv_of_is_contr_left
definition sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A :=
calc
(Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, !fiber.sigma_char)
... ≃ Σa b, f a = b : sigma_comm_equiv
... ≃ A : sigma_equiv_of_is_contr_right
definition is_pointed_fiber [instance] [constructor] (f : A → B) (a : A)
: pointed (fiber f (f a)) :=
pointed.mk (fiber.mk a idp)
definition pointed_fiber [constructor] (f : A → B) (a : A) : Type* :=
pointed.Mk (fiber.mk a (idpath (f a)))
definition is_trunc_fun [reducible] (n : trunc_index) (f : A → B) :=
Π(b : B), is_trunc n (fiber f b)
definition is_contr_fun [reducible] (f : A → B) := is_trunc_fun -2 f
-- pre and post composition with equivalences
open function
protected definition equiv_postcompose [constructor] {B' : Type} (g : B → B') [H : is_equiv g]
: fiber (g ∘ f) (g b) ≃ fiber f b :=
calc
fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char
... ≃ Σa : A, f a = b : begin
apply sigma_equiv_sigma_right, intro a,
apply equiv.symm, apply eq_equiv_fn_eq
end
... ≃ fiber f b : fiber.sigma_char
protected definition equiv_precompose [constructor] {A' : Type} (g : A' → A) [H : is_equiv g]
: fiber (f ∘ g) b ≃ fiber f b :=
calc
fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char
... ≃ Σa : A, f a = b : begin
apply sigma_equiv_sigma (equiv.mk g H),
intro a', apply erfl
end
... ≃ fiber f b : fiber.sigma_char
end fiber
open unit is_trunc pointed
namespace fiber
definition fiber_star_equiv [constructor] (A : Type) : fiber (λx : A, star) star ≃ A :=
begin
fapply equiv.MK,
{ intro f, cases f with a H, exact a },
{ intro a, apply fiber.mk a, reflexivity },
{ intro a, reflexivity },
{ intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H,
rewrite [is_set.elim H (refl star)] }
end
definition fiber_const_equiv [constructor] (A : Type) (a₀ : A) (a : A)
: fiber (λz : unit, a₀) a ≃ a₀ = a :=
calc
fiber (λz : unit, a₀) a
≃ Σz : unit, a₀ = a : fiber.sigma_char
... ≃ a₀ = a : sigma_unit_left
-- the pointed fiber of a pointed map, which is the fiber over the basepoint
definition pfiber [constructor] {X Y : Type*} (f : X →* Y) : Type* :=
pointed.MK (fiber f pt) (fiber.mk pt !respect_pt)
definition ppoint [constructor] {X Y : Type*} (f : X →* Y) : pfiber f →* X :=
pmap.mk point idp
end fiber
open function is_equiv
namespace fiber
/- Theorem 4.7.6 -/
variables {A : Type} {P Q : A → Type}
variable (f : Πa, P a → Q a)
definition fiber_total_equiv [constructor] {a : A} (q : Q a)
: fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q :=
calc
fiber (total f) ⟨a , q⟩
≃ Σ(w : Σx, P x), ⟨w.1 , f w.1 w.2 ⟩ = ⟨a , q⟩
: fiber.sigma_char
... ≃ Σ(x : A), Σ(p : P x), ⟨x , f x p⟩ = ⟨a , q⟩
: sigma_assoc_equiv
... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q
:
begin
apply sigma_equiv_sigma_right, intro x,
apply sigma_equiv_sigma_right, intro p,
apply sigma_eq_equiv
end
... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q
:
begin
apply sigma_equiv_sigma_right, intro x,
apply sigma_comm_equiv
end
... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q
: sigma_assoc_equiv
... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q
: sigma_equiv_of_is_contr_left
... ≃ Σ(p : P a), f a p =[idpath a] q
: equiv_of_eq idp
... ≃ Σ(p : P a), f a p = q
:
begin
apply sigma_equiv_sigma_right, intro p,
apply pathover_idp
end
... ≃ fiber (f a) q
: fiber.sigma_char
end fiber
|
9b481d9d74dff51c0e89f7580636b20289ea69fa | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/analysis/calculus/inverse.lean | 9ba67554f06e4c92e391f547f25b671fdfe007ef | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 21,677 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov.
-/
import analysis.calculus.deriv
import topology.local_homeomorph
import topology.metric_space.contracting
/-!
# Inverse function theorem
In this file we prove the inverse function theorem. It says that if a map `f : E → F`
has an invertible strict derivative `f'` at `a`, then it is locally invertible,
and the inverse function has derivative `f' ⁻¹`.
We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f`
with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`.
The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems
about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`.
Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`,
and prove two versions of the inverse function theorem:
* `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the
strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the
strict sense;
* `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in
the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative
`f'.symm` at `f a` in the strict sense.
In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and
`f'⁻¹`. Some other versions of the theorem assuming that we already know the inverse function are
formulated in `fderiv.lean` and `deriv.lean`
## Notations
In the section about `approximates_linear_on` we introduce some `local notation` to make formulas
shorter:
* by `N` we denote `∥f'⁻¹∥`;
* by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that
`{x | f x = y}` is nonempty.
## Tags
derivative, strictly differentiable, inverse function
-/
open function set filter metric
open_locale topological_space classical nnreal
noncomputable theory
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space 𝕜 G]
variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G']
open asymptotics filter metric set
open continuous_linear_map (id)
/-!
### Non-linear maps approximating close to affine maps
In this section we study a map `f` such that `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` on an open set
`s`, where `f' : E ≃L[𝕜] F` is a continuous linear equivalence and `c < ∥f'⁻¹∥`. Maps of this type
behave like `f a + f' (x - a)` near each `a ∈ s`.
If `E` is a complete space, we prove that the image `f '' s` is open, and `f` is a homeomorphism
between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to
be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`.
Maps of this type naturally appear in the proof of the inverse function theorem (see next section),
and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function
exists.
We define this auxiliary notion to split the proof of the inverse function theorem into small
lemmas. This approach makes it possible
- to prove a lower estimate on the size of the domain of the inverse function;
- to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a
function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`.
-/
/-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`,
if `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` whenever `x, y ∈ s`.
This predicate is defined to facilitate the splitting of the inverse function theorem into small
lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined
on a specific set. -/
def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop :=
∀ (x ∈ s) (y ∈ s), ∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥
namespace approximates_linear_on
variables [cs : complete_space E] {f : E → F}
/-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily
invertible) continuous linear map. -/
section
variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0}
theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) :
approximates_linear_on f f' s c' :=
λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _)
theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) :
approximates_linear_on f f' s c :=
λ x hx y hy, hf x (hst hx) y (hst hy)
lemma lipschitz_sub (hf : approximates_linear_on f f' s c) :
lipschitz_with c (λ x : s, f x - f' x) :=
begin
refine lipschitz_with.of_dist_le_mul (λ x y, _),
rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm],
convert hf x x.2 y y.2 using 2,
rw [f'.map_sub], abel
end
protected lemma lipschitz (hf : approximates_linear_on f f' s c) :
lipschitz_with (nnnorm f' + c) (s.restrict f) :=
by simpa only [restrict_apply, add_sub_cancel'_right]
using (f'.lipschitz.restrict s).add hf.lipschitz_sub
protected lemma continuous (hf : approximates_linear_on f f' s c) :
continuous (s.restrict f) :=
hf.lipschitz.continuous
protected lemma continuous_on (hf : approximates_linear_on f f' s c) :
continuous_on f s :=
continuous_on_iff_continuous_restrict.2 hf.continuous
end
/-!
From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`.
We also assume that either `E = {0}`, or `c < ∥f'⁻¹∥⁻¹`. We use `N` as an abbreviation for `∥f'⁻¹∥`.
-/
variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0}
local notation `N` := nnnorm (f'.symm : F →L[𝕜] E)
protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) :=
begin
cases hc with hE hc,
{ haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩,
exact antilipschitz_with.of_subsingleton },
convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc,
simp [restrict]
end
protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
injective (s.restrict f) :=
(hf.antilipschitz hc).injective
protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
inj_on f s :=
inj_on_iff_injective.2 $ hf.injective hc
/-- A map approximating a linear equivalence on a set defines a local equivalence on this set.
Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below.
This is a first step towards the inverse function. -/
def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F :=
(hf.inj_on hc).to_local_equiv _ _
/-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/
lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) :
continuous_on (hf.to_local_equiv hc).symm (f '' s) :=
begin
apply continuous_on_iff_continuous_restrict.2,
refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous,
exact (λ x hx, (hf.to_local_equiv hc).map_target hx)
end
/-!
Now we prove that `f '' s` is an open set. This follows from the fact that the restriction of `f`
on `s` is an open map. More precisely, we show that the image of a closed ball $$\bar B(a, ε) ⊆ s$$
under `f` includes the closed ball $$\bar B\left(f(a), \frac{ε}{∥{f'}⁻¹∥⁻¹-c}\right)$$.
In order to do this, we introduce an auxiliary map $$g_y(x) = x + {f'}⁻¹ (y - f x)$$. Provided that
$$∥y - f a∥ ≤ \frac{ε}{∥{f'}⁻¹∥⁻¹-c}$$, we prove that $$g_y$$ contracts in $$\bar B(a, ε)$$ and `f`
sends the fixed point of $$g_y$$ to `y`.
-/
section
variables (f f')
/-- Iterations of this map converge to `f⁻¹ y`. The formula is very similar to the one
used in Newton's method, but we use the same `f'.symm` for all `y` instead of evaluating
the derivative at each point along the orbit. -/
def inverse_approx_map (y : F) (x : E) : E := x + f'.symm (y - f x)
end
section inverse_approx_map
variables (y : F) {x x' : E} {ε : ℝ}
local notation `g` := inverse_approx_map f f' y
lemma inverse_approx_map_sub (x x' : E) : g x - g x' = (x - x') - f'.symm (f x - f x') :=
by { simp only [inverse_approx_map, f'.symm.map_sub], abel }
lemma inverse_approx_map_dist_self (x : E) :
dist (g x) x = dist (f'.symm $ f x) (f'.symm y) :=
by simp only [inverse_approx_map, dist_eq_norm, f'.symm.map_sub, add_sub_cancel', norm_sub_rev]
lemma inverse_approx_map_dist_self_le (x : E) :
dist (g x) x ≤ N * dist (f x) y :=
by { rw inverse_approx_map_dist_self, exact f'.symm.lipschitz.dist_le_mul (f x) y }
lemma inverse_approx_map_fixed_iff {x : E} :
g x = x ↔ f x = y :=
by rw [← dist_eq_zero, inverse_approx_map_dist_self, dist_eq_zero, f'.symm.injective.eq_iff]
lemma inverse_approx_map_contracts_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
{x x'} (hx : x ∈ s) (hx' : x' ∈ s) :
dist (g x) (g x') ≤ N * c * dist x x' :=
begin
rw [dist_eq_norm, dist_eq_norm, inverse_approx_map_sub, norm_sub_rev],
suffices : ∥f'.symm (f x - f x' - f' (x - x'))∥ ≤ N * (c * ∥x - x'∥),
by simpa only [f'.symm.map_sub, f'.symm_apply_apply, mul_assoc] using this,
exact (f'.symm : F →L[𝕜] E).le_op_norm_of_le (hf x hx x' hx')
end
variable {y}
lemma inverse_approx_map_maps_to (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) {b : E} (hb : b ∈ s) (hε : closed_ball b ε ⊆ s)
(hy : y ∈ closed_ball (f b) ((N⁻¹ - c) * ε)) :
maps_to g (closed_ball b ε) (closed_ball b ε) :=
begin
cases hc with hE hc,
{ exactI λ x hx, subsingleton.elim x (g x) ▸ hx },
assume x hx,
simp only [mem_closed_ball] at hx hy ⊢,
rw [dist_comm] at hy,
calc dist (inverse_approx_map f f' y x) b ≤
dist (inverse_approx_map f f' y x) (inverse_approx_map f f' y b) +
dist (inverse_approx_map f f' y b) b : dist_triangle _ _ _
... ≤ N * c * dist x b + N * dist (f b) y :
add_le_add (hf.inverse_approx_map_contracts_on y (hε hx) hb)
(inverse_approx_map_dist_self_le _ _)
... ≤ N * c * ε + N * ((N⁻¹ - c) * ε) :
add_le_add (mul_le_mul_of_nonneg_left hx (mul_nonneg (nnreal.coe_nonneg _) c.coe_nonneg))
(mul_le_mul_of_nonneg_left hy (nnreal.coe_nonneg _))
... = N * (c + (N⁻¹ - c)) * ε : by simp only [mul_add, add_mul, mul_assoc]
... = ε : by { rw [add_sub_cancel'_right, mul_inv_cancel, one_mul],
exact ne_of_gt (inv_pos.1 $ lt_of_le_of_lt c.coe_nonneg hc) }
end
end inverse_approx_map
include cs
variable {ε : ℝ}
theorem surj_on_closed_ball (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) :
surj_on f (closed_ball b ε) (closed_ball (f b) ((N⁻¹ - c) * ε)) :=
begin
cases hc with hE hc,
{ resetI,
haveI hF : subsingleton F := f'.symm.to_linear_equiv.to_equiv.subsingleton,
intros y hy,
exact ⟨b, mem_closed_ball_self ε0, subsingleton.elim _ _⟩ },
intros y hy,
have : contracting_with (N * c) ((hf.inverse_approx_map_maps_to (or.inr hc)
(hε $ mem_closed_ball_self ε0) hε hy).restrict _ _ _),
{ split,
{ rwa [mul_comm, ← nnreal.lt_inv_iff_mul_lt],
exact ne_of_gt (inv_pos.1 $ lt_of_le_of_lt c.coe_nonneg hc) },
{ exact lipschitz_with.of_dist_le_mul (λ x x', hf.inverse_approx_map_contracts_on
y (hε x.mem) (hε x'.mem)) } },
refine ⟨this.efixed_point' _ _ _ b (mem_closed_ball_self ε0) (edist_lt_top _ _), _, _⟩,
{ exact is_closed_ball.is_complete },
{ apply contracting_with.efixed_point_mem' },
{ exact (inverse_approx_map_fixed_iff y).1 (this.efixed_point_is_fixed_pt' _ _ _ _) }
end
section
variables (f s)
/-- Given a function `f` that approximates a linear equivalence on an open set `s`,
returns a local homeomorph with `to_fun = f` and `source = s`. -/
def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F :=
{ to_local_equiv := hf.to_local_equiv hc,
open_source := hs,
open_target :=
begin
cases hc with hE hc,
{ resetI,
haveI hF : subsingleton F := f'.to_linear_equiv.to_equiv.symm.subsingleton,
apply is_open_discrete },
change is_open (f '' s),
simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢,
intros x hx,
rcases hs x hx with ⟨ε, ε0, hε⟩,
refine ⟨(N⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩,
exact (hf.surj_on_closed_ball (or.inr hc) (le_of_lt ε0) hε).mono hε (subset.refl _)
end,
continuous_to_fun := hf.continuous_on,
continuous_inv_fun := hf.inverse_continuous_on hc }
end
@[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs : E → F) = f := rfl
@[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs).source = s := rfl
@[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) :
(hf.to_local_homeomorph f s hc hs).target = f '' s := rfl
lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c)
(hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) :
closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target :=
(hf.surj_on_closed_ball hc ε0 hε).mono hε (subset.refl _)
end approximates_linear_on
/-!
### Inverse function theorem
Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector
space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict
sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood
of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse
function. -/
namespace has_strict_fderiv_at
/-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'`
with constant `c` on some neighborhood of `a`. -/
lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E}
(hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) :
∃ s ∈ 𝓝 a, approximates_linear_on f f' s c :=
begin
cases hc with hE hc,
{ refine ⟨univ, mem_nhds_sets is_open_univ trivial, λ x hx y hy, _⟩,
simp [@subsingleton.elim E hE x y] },
have := hf.def hc,
rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this,
rcases this with ⟨s, has, hs⟩,
exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩
end
variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E}
lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∃ (s : set E) (hs : a ∈ s ∧ is_open s),
approximates_linear_on f (f' : E →L[𝕜] F) s ((nnnorm (f'.symm : F →L[𝕜] E))⁻¹ / 2) :=
begin
refine ((nhds_basis_opens a).exists_iff _).1 _,
exact (λ s t, approximates_linear_on.mono_set),
exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $
λ hf', nnreal.half_pos $ nnreal.inv_pos.2 $ hf')
end
include cs
variable (f)
/-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph`
with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem.
The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function
of this `local_homeomorph` has derivative `f'.symm`. -/
def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F :=
approximates_linear_on.to_local_homeomorph f
(classical.some hf.approximates_deriv_on_open_nhds)
(classical.some_spec hf.approximates_deriv_on_open_nhds).snd
(f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $
nnreal.inv_pos.2 $ hf')
(classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2
variable {f}
@[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
(hf.to_local_homeomorph f : E → F) = f := rfl
lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
a ∈ (hf.to_local_homeomorph f).source :=
(classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1
lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
f a ∈ (hf.to_local_homeomorph f).target :=
(hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source
variables (f f' a)
/-- Given a function `f` with an invertible derivative, returns a function that is locally inverse
to `f`. -/
def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E :=
(hf.to_local_homeomorph f).symm
variables {f f' a}
lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x :=
(hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source
lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
hf.local_inverse f f' a (f a) = a :=
hf.eventually_left_inverse.self_of_nhds
lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y :=
(hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source
lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
continuous_at (hf.local_inverse f f' a) (f a) :=
(hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target
lemma local_inverse_tendsto (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
tendsto (hf.local_inverse f f' a) (𝓝 $ f a) (𝓝 a) :=
(hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source
lemma local_inverse_unique (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E}
(hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
∀ᶠ y in 𝓝 (f a), g y = local_inverse f f' a hf y :=
eventually_eq_of_left_inv_of_right_inv hg hf.eventually_right_inverse $
(hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source
/-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`,
then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/
theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) :
has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) :=
begin
have : has_strict_fderiv_at f (f' : E →L[𝕜] F) (hf.local_inverse f f' a (f a)),
{ rwa hf.local_inverse_apply_image },
exact this.of_local_left_inverse hf.local_inverse_continuous_at hf.eventually_right_inverse
end
/-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability
and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`.
For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]`
see `of_local_left_inverse`. -/
theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E}
(hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) :=
hf.to_local_inverse.congr_of_mem_sets $ (hf.local_inverse_unique hg).mono $ λ _, eq.symm
end has_strict_fderiv_at
/-!
### Inverse function theorem, 1D case
In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`.
We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and
`f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`.
-/
namespace has_strict_deriv_at
variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a)
(hf' : f' ≠ 0)
include cs
variables (f f' a)
/-- A function that is inverse to `f` near `a`. -/
@[reducible] def local_inverse : 𝕜 → 𝕜 :=
(hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _
variables {f f' a}
theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) :=
(hf.has_strict_fderiv_at_equiv hf').to_local_inverse
theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) :
has_strict_deriv_at g f'⁻¹ (f a) :=
(hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg
end has_strict_deriv_at
|
e24c5d40ec5e0cfe6de5c3d5e8174ab25b21afac | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/equiv/encodable/basic.lean | cbb813a0cba6071f00bdf1f5b7e28682f1b73a22 | [
"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 | 18,108 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.equiv.nat
import order.rel_iso
import order.directed
/-!
# Encodable types
This file defines encodable (constructively countable) types as a typeclass.
This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that
those functions are inverses of each other.
The difference with `denumerable` is that finite types are encodable. For infinite types,
`encodable` and `denumerable` agree.
## Main declarations
* `encodable α`: States that there exists an explicit encoding function `encode : α → ℕ` with a
partial inverse `decode : ℕ → option α`.
* `decode₂`: Version of `decode` that is equal to `none` outside of the range of `encode`. Useful as
we do not require this in the definition of `decode`.
* `ulower α`: Any encodable type has an equivalent type living in the lowest universe, namely a
subtype of `ℕ`. `ulower α` finds it.
## Implementation notes
The point of asking for an explicit partial inverse `decode : ℕ → option α` to `encode : α → ℕ` is
to make the range of `encode` decidable even when the finiteness of `α` is not.
-/
open option list nat function
/-- Constructively countable type. Made from an explicit injection `encode : α → ℕ` and a partial
inverse `decode : ℕ → option α`. Note that finite types *are* countable. See `denumerable` if you
wish to enforce infiniteness. -/
class encodable (α : Type*) :=
(encode : α → ℕ)
(decode [] : ℕ → option α)
(encodek : ∀ a, decode (encode a) = some a)
attribute [simp] encodable.encodek
namespace encodable
variables {α : Type*} {β : Type*}
universe u
theorem encode_injective [encodable α] : function.injective (@encode α _)
| x y e := option.some.inj $ by rw [← encodek, e, encodek]
lemma surjective_decode_iget (α : Type*) [encodable α] [inhabited α] :
surjective (λ n, (encodable.decode α n).iget) :=
λ x, ⟨encodable.encode x, by simp_rw [encodable.encodek]⟩
/-- An encodable type has decidable equality. Not set as an instance because this is usually not the
best way to infer decidability. -/
def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α
| a b := decidable_of_iff _ encode_injective.eq_iff
/-- If `α` is encodable and there is an injection `f : β → α`, then `β` is encodable as well. -/
def of_left_injection [encodable α]
(f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β :=
⟨λ b, encode (f b),
λ n, (decode α n).bind finv,
λ b, by simp [encodable.encodek, linv]⟩
/-- If `α` is encodable and `f : β → α` is invertible, then `β` is encodable as well. -/
def of_left_inverse [encodable α]
(f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β :=
of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b))
/-- Encodability is preserved by equivalence. -/
def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β :=
of_left_inverse e e.symm e.left_inv
@[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) :
@encode _ (of_equiv _ e) b = encode (e b) := rfl
@[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) :
@decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl
instance nat : encodable ℕ :=
⟨id, some, λ a, rfl⟩
@[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl
@[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl
instance empty : encodable empty :=
⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩
instance unit : encodable punit :=
⟨λ_, zero, λ n, nat.cases_on n (some punit.star) (λ _, none), λ _, by simp⟩
@[simp] theorem encode_star : encode punit.star = 0 := rfl
@[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl
@[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl
/-- If `α` is encodable, then so is `option α`. -/
instance option {α : Type*} [h : encodable α] : encodable (option α) :=
⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)),
λ n, nat.cases_on n (some none) (λ m, (decode α m).map some),
λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩
@[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl
@[simp] theorem encode_some [encodable α] (a : α) :
encode (some a) = succ (encode a) := rfl
@[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl
@[simp] theorem decode_option_succ [encodable α] (n) :
decode (option α) (succ n) = (decode α n).map some := rfl
/-- Failsafe variant of `decode`. `decode₂ α n` returns the preimage of `n` under `encode` if it
exists, and returns `none` if it doesn't. This requirement could be imposed directly on `decode` but
is not to help make the definition easier to use. -/
def decode₂ (α) [encodable α] (n : ℕ) : option α :=
(decode α n).bind (option.guard (λ a, encode a = n))
theorem mem_decode₂' [encodable α] {n : ℕ} {a : α} :
a ∈ decode₂ α n ↔ a ∈ decode α n ∧ encode a = n :=
by simp [decode₂]; exact
⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩
theorem mem_decode₂ [encodable α] {n : ℕ} {a : α} :
a ∈ decode₂ α n ↔ encode a = n :=
mem_decode₂'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _)
theorem decode₂_ne_none_iff [encodable α] {n : ℕ} :
decode₂ α n ≠ none ↔ n ∈ set.range (encode : α → ℕ) :=
by simp_rw [set.range, set.mem_set_of_eq, ne.def, option.eq_none_iff_forall_not_mem,
encodable.mem_decode₂, not_forall, not_not]
theorem decode₂_is_partial_inv [encodable α] : is_partial_inv encode (decode₂ α) :=
λ a n, mem_decode₂
theorem decode₂_inj [encodable α] {n : ℕ} {a₁ a₂ : α}
(h₁ : a₁ ∈ decode₂ α n) (h₂ : a₂ ∈ decode₂ α n) : a₁ = a₂ :=
encode_injective $ (mem_decode₂.1 h₁).trans (mem_decode₂.1 h₂).symm
theorem encodek₂ [encodable α] (a : α) : decode₂ α (encode a) = some a :=
mem_decode₂.2 rfl
/-- The encoding function has decidable range. -/
def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (∈ set.range (@encode α _)) :=
λ x, decidable_of_iff (option.is_some (decode₂ α x))
⟨λ h, ⟨option.get h, by rw [← decode₂_is_partial_inv (option.get h), option.some_get]⟩,
λ ⟨n, hn⟩, by rw [← hn, encodek₂]; exact rfl⟩
/-- An encodable type is equivalent to the range of its encoding function. -/
def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) :=
{ to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩,
inv_fun := λ n, option.get (show is_some (decode₂ α n.1),
by cases n.2 with x hx; rw [← hx, encodek₂]; exact rfl),
left_inv := λ a, by dsimp;
rw [← option.some_inj, option.some_get, encodek₂],
right_inv := λ ⟨n, x, hx⟩, begin
apply subtype.eq,
dsimp,
conv {to_rhs, rw ← hx},
rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek₂],
end }
/-- A type with unique element is encodable. -/
@[priority 100] instance _root_.unique.encodable [unique α] : encodable α :=
⟨λ _, 0, λ _, some (default α), unique.forall_iff.2 rfl⟩
section sum
variables [encodable α] [encodable β]
/-- Explicit encoding function for the sum of two encodable types. -/
def encode_sum : α ⊕ β → ℕ
| (sum.inl a) := bit0 $ encode a
| (sum.inr b) := bit1 $ encode b
/-- Explicit decoding function for the sum of two encodable types. -/
def decode_sum (n : ℕ) : option (α ⊕ β) :=
match bodd_div2 n with
| (ff, m) := (decode α m).map sum.inl
| (tt, m) := (decode β m).map sum.inr
end
/-- If `α` and `β` are encodable, then so is their sum. -/
instance sum : encodable (α ⊕ β) :=
⟨encode_sum, decode_sum, λ s,
by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩
@[simp] theorem encode_inl (a : α) :
@encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl
@[simp] theorem encode_inr (b : β) :
@encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl
@[simp] theorem decode_sum_val (n : ℕ) :
decode (α ⊕ β) n = decode_sum n := rfl
end sum
instance bool : encodable bool :=
of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit
@[simp] theorem encode_tt : encode tt = 1 := rfl
@[simp] theorem encode_ff : encode ff = 0 := rfl
@[simp] theorem decode_zero : decode bool 0 = some ff := rfl
@[simp] theorem decode_one : decode bool 1 = some tt := rfl
theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none :=
begin
suffices : decode_sum n = none,
{ change (decode_sum n).map _ = none, rw this, refl },
have : 1 ≤ div2 n,
{ rw [div2_val, nat.le_div_iff_mul_le],
exacts [h, dec_trivial] },
cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e,
simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl
end
noncomputable instance «Prop» : encodable Prop :=
of_equiv bool equiv.Prop_equiv_bool
section sigma
variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)]
/-- Explicit encoding function for `sigma γ` -/
def encode_sigma : sigma γ → ℕ
| ⟨a, b⟩ := mkpair (encode a) (encode b)
/-- Explicit decoding function for `sigma γ` -/
def decode_sigma (n : ℕ) : option (sigma γ) :=
let (n₁, n₂) := unpair n in
(decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a
instance sigma : encodable (sigma γ) :=
⟨encode_sigma, decode_sigma, λ ⟨a, b⟩,
by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩
@[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n =
(decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) :=
show decode_sigma._match_1 _ = _, by cases n.unpair; refl
@[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ =
mkpair (encode a) (encode b) := rfl
end sigma
section prod
variables [encodable α] [encodable β]
/-- If `α` and `β` are encodable, then so is their product. -/
instance prod : encodable (α × β) :=
of_equiv _ (equiv.sigma_equiv_prod α β).symm
@[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n =
(decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) :=
show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _,
by simp; cases decode α n.unpair.1; simp;
cases decode β n.unpair.2; refl
@[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) =
mkpair (encode a) (encode b) := rfl
end prod
section subtype
open subtype decidable
variables {P : α → Prop} [encA : encodable α] [decP : decidable_pred P]
include encA
/-- Explicit encoding function for a decidable subtype of an encodable type -/
def encode_subtype : {a : α // P a} → ℕ
| ⟨v, h⟩ := encode v
include decP
/-- Explicit decoding function for a decidable subtype of an encodable type -/
def decode_subtype (v : ℕ) : option {a : α // P a} :=
(decode α v).bind $ λ a,
if h : P a then some ⟨a, h⟩ else none
/-- A decidable subtype of an encodable type is encodable. -/
instance subtype : encodable {a : α // P a} :=
⟨encode_subtype, decode_subtype,
λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩
lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val :=
by cases a; refl
end subtype
instance fin (n) : encodable (fin n) :=
of_equiv _ (equiv.fin_equiv_subtype _)
instance int : encodable ℤ :=
of_equiv _ equiv.int_equiv_nat
instance pnat : encodable ℕ+ :=
of_equiv _ equiv.pnat_equiv_nat
/-- The lift of an encodable type is encodable. -/
instance ulift [encodable α] : encodable (ulift α) :=
of_equiv _ equiv.ulift
/-- The lift of an encodable type is encodable. -/
instance plift [encodable α] : encodable (plift α) :=
of_equiv _ equiv.plift
/-- If `β` is encodable and there is an injection `f : α → β`, then `α` is encodable as well. -/
noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α :=
of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl)
end encodable
section ulower
local attribute [instance, priority 100] encodable.decidable_range_encode
/-- `ulower α : Type` is an equivalent type in the lowest universe, given `encodable α`. -/
@[derive decidable_eq, derive encodable]
def ulower (α : Type*) [encodable α] : Type :=
set.range (encodable.encode : α → ℕ)
end ulower
namespace ulower
variables (α : Type*) [encodable α]
/-- The equivalence between the encodable type `α` and `ulower α : Type`. -/
def equiv : α ≃ ulower α :=
encodable.equiv_range_encode α
variables {α}
/-- Lowers an `a : α` into `ulower α`. -/
def down (a : α) : ulower α := equiv α a
instance [inhabited α] : inhabited (ulower α) := ⟨down (default _)⟩
/-- Lifts an `a : ulower α` into `α`. -/
def up (a : ulower α) : α := (equiv α).symm a
@[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _
@[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _
@[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b :=
equiv.apply_eq_iff_eq _
@[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b :=
equiv.apply_eq_iff_eq _
@[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b :=
up_eq_up.1
end ulower
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α :=
choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) :
p (choose ex) :=
-/
namespace encodable
section find_a
variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p]
private def good : option α → Prop
| (some a) := p a
| none := false
private def decidable_good : decidable_pred (good p)
| n := by cases n; unfold good; apply_instance
local attribute [instance] decidable_good
open encodable
variable {p}
/-- Constructive choice function for a decidable subtype of an encodable type. -/
def choose_x (h : ∃ x, p x) : {a : α // p a} :=
have ∃ n, good p (decode α n), from
let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩,
match _, nat.find_spec this : ∀ o, good p o → {a // p a} with
| some a, h := ⟨a, h⟩
end
/-- Constructive choice function for a decidable predicate over an encodable type. -/
def choose (h : ∃ x, p x) : α := (choose_x h).1
lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2
end find_a
theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop}
[Π a, encodable (β a)] [∀ x y, decidable (R x y)]
(H : ∀ x, ∃ y, R x y) : ∃ f : Π a, β a, ∀ x, R x (f x) :=
⟨λ x, choose (H x), λ x, choose_spec (H x)⟩
theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop}
[c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] :
(∀ x, ∃ y, P x y) ↔ ∃ f : Π a, β a, (∀ x, P x (f x)) :=
⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩
/-
There is a total ordering on the elements of an encodable type, induced by the map to ℕ.
-/
/-- The `encode` function, viewed as an embedding. -/
def encode' (α) [encodable α] : α ↪ ℕ :=
⟨encodable.encode, encodable.encode_injective⟩
instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_trans
instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_antisymm
instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_total
end encodable
namespace directed
open encodable
variables {α : Type*} {β : Type*} [encodable α] [inhabited α]
/-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type,
construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))`
and `r (f a) (f (x (encode a + 1))`. -/
protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α
| 0 := default α
| (n + 1) :=
let p := sequence n in
match decode α n with
| none := classical.some (hf p p)
| (some a) := classical.some (hf p a)
end
lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) :
r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) :=
begin
dsimp [directed.sequence],
generalize eq : hf.sequence f n = p,
cases h : decode α n with a,
{ exact (classical.some_spec (hf p p)).1 },
{ exact (classical.some_spec (hf p a)).1 }
end
lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) :
r (f a) (f (hf.sequence f (encode a + 1))) :=
begin
simp only [directed.sequence, encodek],
exact (classical.some_spec (hf _ a)).2
end
variables [preorder β] {f : α → β} (hf : directed (≤) f)
lemma sequence_mono : monotone (f ∘ (hf.sequence f)) :=
monotone_nat_of_le_succ $ hf.sequence_mono_nat
lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) :=
hf.rel_sequence a
end directed
section quotient
open encodable quotient
variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α]
/-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid
on an encodable type. -/
def quotient.rep (q : quotient s) : α :=
choose (exists_rep q)
theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q :=
choose_spec (exists_rep q)
/-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/
def encodable_quotient : encodable (quotient s) :=
⟨λ q, encode q.rep,
λ n, quotient.mk <$> decode α n,
by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩
end quotient
|
5def2125664fa5bcfcc0467aaa0105de486aff0f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/new_obtain3.lean | e44a084af6b438bef285daf08326f5ceb36e1760 | [
"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 | 600 | lean | import data.set
open set function eq.ops
variables {X Y Z : Type}
lemma image_compose (f : Y → X) (g : X → Y) (a : set X) : (f ∘ g) ' a = f ' (g ' a) :=
ext (take z,
iff.intro
(assume Hz : z ∈ (f ∘ g) ' a,
obtain x (Hx₁ : x ∈ a) (Hx₂ : f (g x) = z), from Hz,
have Hgx : g x ∈ g ' a, from mem_image Hx₁ rfl,
show z ∈ f ' (g ' a), from mem_image Hgx Hx₂)
(assume Hz : z ∈ f ' (g ' a),
obtain y [x (Hz₁ : x ∈ a) (Hz₂ : g x = y)] (Hy₂ : f y = z), from Hz,
show z ∈ (f ∘ g) ' a, from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂)))
|
77dc054c11bacfc5cf0757757584f565b7fb457f | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/metric_space/gromov_hausdorff_realized.lean | 911125846cb3ac023846d8bbc86e72111f40a9e3 | [
"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 | 27,420 | 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 topology.metric_space.gluing
import topology.metric_space.hausdorff_distance
import topology.continuous_function.bounded
/-!
# The Gromov-Hausdorff distance is realized
In this file, we construct of a good coupling between nonempty compact metric spaces, minimizing
their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff
distance between nonempty compact metric spaces.
Given two nonempty compact metric spaces `X` and `Y`, we define `optimal_GH_coupling X Y` as a
compact metric space, together with two isometric embeddings `optimal_GH_injl` and `optimal_GH_injr`
respectively of `X` and `Y` into `optimal_GH_coupling X Y`. The main property of the optimal
coupling is that the Hausdorff distance between `X` and `Y` in `optimal_GH_coupling X Y` is smaller
than the corresponding distance in any other coupling. We do not prove completely this fact in this
file, but we show a good enough approximation of this fact in `Hausdorff_dist_optimal_le_HD`, that
will suffice to obtain the full statement once the Gromov-Hausdorff distance is properly defined,
in `Hausdorff_dist_optimal`.
The key point in the construction is that the set of possible distances coming from isometric
embeddings of `X` and `Y` in metric spaces is a set of equicontinuous functions. By Arzela-Ascoli,
it is compact, and one can find such a distance which is minimal. This distance defines a premetric
space structure on `X ⊕ Y`. The corresponding metric quotient is `optimal_GH_coupling X Y`.
-/
noncomputable theory
open_locale classical topological_space nnreal
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section Gromov_Hausdorff_realized
/- This section shows that the Gromov-Hausdorff distance
is realized. For this, we consider candidate distances on the disjoint union
`X ⊕ Y` of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff
distance, and show that they form a compact family by applying Arzela-Ascoli
theorem. The existence of a minimizer follows. -/
section definitions
variables (X : Type u) (Y : Type v)
[metric_space X] [compact_space X] [nonempty X]
[metric_space Y] [compact_space Y] [nonempty Y]
@[reducible] private def prod_space_fun : Type* := ((X ⊕ Y) × (X ⊕ Y)) → ℝ
@[reducible] private def Cb : Type* := bounded_continuous_function ((X ⊕ Y) × (X ⊕ Y)) ℝ
private def max_var : ℝ≥0 :=
2 * ⟨diam (univ : set X), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Y), diam_nonneg⟩
private lemma one_le_max_var : 1 ≤ max_var X Y := calc
(1 : real) = 2 * 0 + 1 + 2 * 0 : by simp
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) :
by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num
/-- The set of functions on `X ⊕ Y` that are candidates distances to realize the
minimum of the Hausdorff distances between `X` and `Y` in a coupling -/
def candidates : set (prod_space_fun X Y) :=
{f | (((((∀ x y : X, f (sum.inl x, sum.inl y) = dist x y)
∧ (∀ x y : Y, f (sum.inr x, sum.inr y) = dist x y))
∧ (∀ x y, f (x, y) = f (y, x)))
∧ (∀ x y z, f (x, z) ≤ f (x, y) + f (y, z)))
∧ (∀ x, f (x, x) = 0))
∧ (∀ x y, f (x, y) ≤ max_var X Y) }
/-- Version of the set of candidates in bounded_continuous_functions, to apply
Arzela-Ascoli -/
private def candidates_b : set (Cb X Y) := {f : Cb X Y | (f : _ → ℝ) ∈ candidates X Y}
end definitions --section
section constructions
variables {X : Type u} {Y : Type v}
[metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y]
{f : prod_space_fun X Y} {x y z t : X ⊕ Y}
local attribute [instance, priority 10] inhabited_of_nonempty'
private lemma max_var_bound : dist x y ≤ max_var X Y := calc
dist x y ≤ diam (univ : set (X ⊕ Y)) :
dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _)
... = diam (inl '' (univ : set X) ∪ inr '' (univ : set Y)) :
by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self]
... ≤ diam (inl '' (univ : set X)) + dist (inl (default X)) (inr (default Y)) +
diam (inr '' (univ : set Y)) :
diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _))
... = diam (univ : set X) + (dist (default X) (default X) + 1 + dist (default Y) (default Y)) +
diam (univ : set Y) :
by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl }
... = 1 * diam (univ : set X) + 1 + 1 * diam (univ : set Y) : by simp
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) :
begin
apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl],
norm_num, norm_num
end
private lemma candidates_symm (fA : f ∈ candidates X Y) : f (x, y) = f (y, x) := fA.1.1.1.2 x y
private lemma candidates_triangle (fA : f ∈ candidates X Y) : f (x, z) ≤ f (x, y) + f (y, z) :=
fA.1.1.2 x y z
private lemma candidates_refl (fA : f ∈ candidates X Y) : f (x, x) = 0 := fA.1.2 x
private lemma candidates_nonneg (fA : f ∈ candidates X Y) : 0 ≤ f (x, y) :=
begin
have : 0 ≤ 2 * f (x, y) := calc
0 = f (x, x) : (candidates_refl fA).symm
... ≤ f (x, y) + f (y, x) : candidates_triangle fA
... = f (x, y) + f (x, y) : by rw [candidates_symm fA]
... = 2 * f (x, y) : by ring,
by linarith
end
private lemma candidates_dist_inl (fA : f ∈ candidates X Y) (x y: X) :
f (inl x, inl y) = dist x y :=
fA.1.1.1.1.1 x y
private lemma candidates_dist_inr (fA : f ∈ candidates X Y) (x y : Y) :
f (inr x, inr y) = dist x y :=
fA.1.1.1.1.2 x y
private lemma candidates_le_max_var (fA : f ∈ candidates X Y) : f (x, y) ≤ max_var X Y :=
fA.2 x y
/-- candidates are bounded by `max_var X Y` -/
private lemma candidates_dist_bound (fA : f ∈ candidates X Y) :
∀ {x y : X ⊕ Y}, f (x, y) ≤ max_var X Y * dist x y
| (inl x) (inl y) := calc
f (inl x, inl y) = dist x y : candidates_dist_inl fA x y
... = dist (inl x) (inl y) : by { rw @sum.dist_eq X Y, refl }
... = 1 * dist (inl x) (inl y) : by simp
... ≤ max_var X Y * dist (inl x) (inl y) :
mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg
| (inl x) (inr y) := calc
f (inl x, inr y) ≤ max_var X Y : candidates_le_max_var fA
... = max_var X Y * 1 : by simp
... ≤ max_var X Y * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y))
| (inr x) (inl y) := calc
f (inr x, inl y) ≤ max_var X Y : candidates_le_max_var fA
... = max_var X Y * 1 : by simp
... ≤ max_var X Y * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y))
| (inr x) (inr y) := calc
f (inr x, inr y) = dist x y : candidates_dist_inr fA x y
... = dist (inr x) (inr y) : by { rw @sum.dist_eq X Y, refl }
... = 1 * dist (inr x) (inr y) : by simp
... ≤ max_var X Y * dist (inr x) (inr y) :
mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg
/-- Technical lemma to prove that candidates are Lipschitz -/
private lemma candidates_lipschitz_aux (fA : f ∈ candidates X Y) :
f (x, y) - f (z, t) ≤ 2 * max_var X Y * dist (x, y) (z, t) :=
calc
f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _
... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) :
sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _
... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc]
... ≤ max_var X Y * dist x z + max_var X Y * dist t y :
add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA)
... ≤ max_var X Y * max (dist x z) (dist t y) + max_var X Y * max (dist x z) (dist t y) :
begin
apply add_le_add,
apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y))
(zero_le_one.trans (one_le_max_var X Y)),
apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y))
(zero_le_one.trans (one_le_max_var X Y)),
end
... = 2 * max_var X Y * max (dist x z) (dist y t) :
by { simp [dist_comm], ring }
... = 2 * max_var X Y * dist (x, y) (z, t) : by refl
/-- Candidates are Lipschitz -/
private lemma candidates_lipschitz (fA : f ∈ candidates X Y) :
lipschitz_with (2 * max_var X Y) f :=
begin
apply lipschitz_with.of_dist_le_mul,
rintros ⟨x, y⟩ ⟨z, t⟩,
rw [real.dist_eq, abs_sub_le_iff],
use candidates_lipschitz_aux fA,
rw [dist_comm],
exact candidates_lipschitz_aux fA
end
/-- candidates give rise to elements of bounded_continuous_functions -/
def candidates_b_of_candidates (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : Cb X Y :=
bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩
lemma candidates_b_of_candidates_mem (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) :
candidates_b_of_candidates f fA ∈ candidates_b X Y := fA
/-- The distance on `X ⊕ Y` is a candidate -/
private lemma dist_mem_candidates : (λp : (X ⊕ Y) × (X ⊕ Y), dist p.1 p.2) ∈ candidates X Y :=
begin
simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true,
and_self, sum.forall, set.mem_set_of_eq, dist_self],
repeat { split
<|> exact (λa y z, dist_triangle_left _ _ _)
<|> exact (λx y, by refl)
<|> exact (λx y, max_var_bound) }
end
/-- The distance on `X ⊕ Y` as a candidate -/
def candidates_b_dist (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [inhabited X]
[metric_space Y] [compact_space Y] [inhabited Y] : Cb X Y :=
candidates_b_of_candidates _ dist_mem_candidates
lemma candidates_b_dist_mem_candidates_b : candidates_b_dist X Y ∈ candidates_b X Y :=
candidates_b_of_candidates_mem _ _
private lemma candidates_b_nonempty : (candidates_b X Y).nonempty :=
⟨_, candidates_b_dist_mem_candidates_b⟩
/-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and
equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/
private lemma closed_candidates_b : is_closed (candidates_b X Y) :=
begin
have I1 : ∀ x y, is_closed {f : Cb X Y | f (inl x, inl y) = dist x y} :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I2 : ∀ x y, is_closed {f : Cb X Y | f (inr x, inr y) = dist x y } :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I3 : ∀ x y, is_closed {f : Cb X Y | f (x, y) = f (y, x)} :=
λx y, is_closed_eq continuous_evalx continuous_evalx,
have I4 : ∀ x y z, is_closed {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)} :=
λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx),
have I5 : ∀ x, is_closed {f : Cb X Y | f (x, x) = 0} :=
λx, is_closed_eq continuous_evalx continuous_const,
have I6 : ∀ x y, is_closed {f : Cb X Y | f (x, y) ≤ max_var X Y} :=
λx y, is_closed_le continuous_evalx continuous_const,
have : candidates_b X Y = (⋂x y, {f : Cb X Y | f ((@inl X Y x), (@inl X Y y)) = dist x y})
∩ (⋂x y, {f : Cb X Y | f ((@inr X Y x), (@inr X Y y)) = dist x y})
∩ (⋂x y, {f : Cb X Y | f (x, y) = f (y, x)})
∩ (⋂x y z, {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)})
∩ (⋂x, {f : Cb X Y | f (x, x) = 0})
∩ (⋂x y, {f : Cb X Y | f (x, y) ≤ max_var X Y}),
{ ext, simp only [candidates_b, candidates, mem_inter_eq, mem_Inter, mem_set_of_eq] },
rw this,
repeat { apply is_closed.inter _ _
<|> apply is_closed_Inter _
<|> apply I1 _ _
<|> apply I2 _ _
<|> apply I3 _ _
<|> apply I4 _ _ _
<|> apply I5 _
<|> apply I6 _ _
<|> assume x },
end
/-- Compactness of candidates (in bounded_continuous_functions) follows. -/
private lemma compact_candidates_b : is_compact (candidates_b X Y) :=
begin
refine arzela_ascoli₂ (Icc 0 (max_var X Y)) is_compact_Icc (candidates_b X Y)
closed_candidates_b _ _,
{ rintros f ⟨x1, x2⟩ hf,
simp only [set.mem_Icc],
exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ },
{ refine equicontinuous_of_continuity_modulus (λt, 2 * max_var X Y * t) _ _ _,
{ have : tendsto (λ (t : ℝ), 2 * (max_var X Y : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var X Y * 0)) :=
tendsto_const_nhds.mul tendsto_id,
simpa using this },
{ assume x y f hf,
exact (candidates_lipschitz hf).dist_le_mul _ _ } }
end
/-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not
in a metric space setting, so we need to define our custom version of Hausdorff distance,
called HD, and prove its basic properties. -/
def HD (f : Cb X Y) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y))
/- We will show that HD is continuous on bounded_continuous_functions, to deduce that its
minimum on the compact set candidates_b is attained. Since it is defined in terms of
infimum and supremum on `ℝ`, which is only conditionnally complete, we will need all the time
to check that the defining sets are bounded below or above. This is done in the next few
technical lemmas -/
lemma HD_below_aux1 {f : Cb X Y} (C : ℝ) {x : X} :
bdd_below (range (λ (y : Y), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩
private lemma HD_bound_aux1 (f : Cb X Y) (C : ℝ) :
bdd_above (range (λ (x : X), ⨅ y, f (inl x, inr y) + C)) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩,
calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default Y)) + C :
cinfi_le (HD_below_aux1 C) (default Y)
... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _)
end
lemma HD_below_aux2 {f : Cb X Y} (C : ℝ) {y : Y} :
bdd_below (range (λ (x : X), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩
private lemma HD_bound_aux2 (f : Cb X Y) (C : ℝ) :
bdd_above (range (λ (y : Y), ⨅ x, f (inl x, inr y) + C)) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩,
calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default X), inr y) + C :
cinfi_le (HD_below_aux2 C) (default X)
... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _)
end
/-- Explicit bound on `HD (dist)`. This means that when looking for minimizers it will
be sufficient to look for functions with `HD(f)` bounded by this bound. -/
lemma HD_candidates_b_dist_le :
HD (candidates_b_dist X Y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) :=
begin
refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)),
{ have A : (⨅ y, candidates_b_dist X Y (inl x, inr y)) ≤
candidates_b_dist X Y (inl x, inr (default Y)) :=
cinfi_le (by simpa using HD_below_aux1 0) (default Y),
have B : dist (inl x) (inr (default Y)) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc
dist (inl x) (inr (default Y)) = dist x (default X) + 1 + dist (default Y) (default Y) : rfl
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ },
any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ },
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
end,
exact le_trans A B },
{ have A : (⨅ x, candidates_b_dist X Y (inl x, inr y)) ≤
candidates_b_dist X Y (inl (default X), inr y) :=
cinfi_le (by simpa using HD_below_aux2 0) (default X),
have B : dist (inl (default X)) (inr y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc
dist (inl (default X)) (inr y) = dist (default X) (default X) + 1 + dist (default Y) y : rfl
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ },
any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ },
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _)
end,
exact le_trans A B },
end
/- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we
prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/
private lemma HD_lipschitz_aux1 (f g : Cb X Y) :
(⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g :=
csupr_le_csupr (HD_bound_aux1 _ (dist f g))
(λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀ x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g,
{ assume x,
refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ show bdd_below (range (λ (y : Y), g (inl x, inr y))),
from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } },
have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g,
{ refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux1 _ 0 } },
-- deduce the result from the above two steps
simpa [E2, E1, function.comp]
end
private lemma HD_lipschitz_aux2 (f g : Cb X Y) :
(⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g :=
csupr_le_csupr (HD_bound_aux2 _ (dist f g))
(λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀ y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g,
{ assume y,
refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ show bdd_below (range (λx:X, g (inl x, inr y))),
from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } },
have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g,
{ refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux2 _ 0 } },
-- deduce the result from the above two steps
simpa [E2, E1]
end
private lemma HD_lipschitz_aux3 (f g : Cb X Y) : HD f ≤ HD g + dist f g :=
max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _))
(le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _))
/-- Conclude that HD, being Lipschitz, is continuous -/
private lemma HD_continuous : continuous (HD : Cb X Y → ℝ) :=
lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3)
end constructions --section
section consequences
variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y]
[compact_space Y] [nonempty Y]
/- Now that we have proved that the set of candidates is compact, and that HD is continuous,
we can finally select a candidate minimizing HD. This will be the candidate realizing the
optimal coupling. -/
private lemma exists_minimizer : ∃ f ∈ candidates_b X Y, ∀ g ∈ candidates_b X Y, HD f ≤ HD g :=
compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on
private definition optimal_GH_dist : Cb X Y := classical.some (exists_minimizer X Y)
private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist X Y ∈ candidates_b X Y :=
by cases (classical.some_spec (exists_minimizer X Y)); assumption
private lemma HD_optimal_GH_dist_le (g : Cb X Y) (hg : g ∈ candidates_b X Y) :
HD (optimal_GH_dist X Y) ≤ HD g :=
let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer X Y) in Z2 g hg
/-- With the optimal candidate, construct a premetric space structure on `X ⊕ Y`, on which the
predistance is given by the candidate. Then, we will identify points at `0` predistance
to obtain a genuine metric space -/
def premetric_optimal_GH_dist : pseudo_metric_space (X ⊕ Y) :=
{ dist := λp q, optimal_GH_dist X Y (p, q),
dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b X Y),
dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b X Y),
dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b X Y) }
local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid
/-- A metric space which realizes the optimal coupling between `X` and `Y` -/
@[derive metric_space, nolint has_inhabited_instance]
definition optimal_GH_coupling : Type* :=
pseudo_metric_quot (X ⊕ Y)
/-- Injection of `X` in the optimal coupling between `X` and `Y` -/
def optimal_GH_injl (x : X) : optimal_GH_coupling X Y := ⟦inl x⟧
/-- The injection of `X` in the optimal coupling between `X` and `Y` is an isometry. -/
lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl X Y) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y,
exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b X Y) _ _,
end
/-- Injection of `Y` in the optimal coupling between `X` and `Y` -/
def optimal_GH_injr (y : Y) : optimal_GH_coupling X Y := ⟦inr y⟧
/-- The injection of `Y` in the optimal coupling between `X` and `Y` is an isometry. -/
lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr X Y) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y,
exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b X Y) _ _,
end
/-- The optimal coupling between two compact spaces `X` and `Y` is still a compact space -/
instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling X Y) :=
⟨begin
have : (univ : set (optimal_GH_coupling X Y)) =
(optimal_GH_injl X Y '' univ) ∪ (optimal_GH_injr X Y '' univ),
{ refine subset.antisymm (λxc hxc, _) (subset_univ _),
rcases quotient.exists_rep xc with ⟨x, hx⟩,
cases x; rw ← hx,
{ have : ⟦inl x⟧ = optimal_GH_injl X Y x := rfl,
rw this,
exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) },
{ have : ⟦inr x⟧ = optimal_GH_injr X Y x := rfl,
rw this,
exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } },
rw this,
exact (compact_univ.image (isometry_optimal_GH_injl X Y).continuous).union
(compact_univ.image (isometry_optimal_GH_injr X Y).continuous)
end⟩
/-- For any candidate `f`, `HD(f)` is larger than or equal to the Hausdorff distance in the
optimal coupling. This follows from the fact that HD of the optimal candidate is exactly
the Hausdorff distance in the optimal coupling, although we only prove here the inequality
we need. -/
lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b X Y) :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD f :=
begin
refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le X Y f h),
have A : ∀ x ∈ range (optimal_GH_injl X Y), ∃ y ∈ range (optimal_GH_injr X Y), dist x y ≤ r,
{ assume x hx,
rcases mem_range.1 hx with ⟨z, hz⟩,
rw ← hz,
have I1 : (⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y)) < r :=
lt_of_le_of_lt (le_max_left _ _) hr,
have I2 : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) ≤
⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y) :=
le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _),
have I : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injr X Y z', mem_range_self _],
have : (optimal_GH_dist X Y) (inl z, inr z') ≤ r, by { rw hz', exact le_of_lt hr' },
exact this },
refine Hausdorff_dist_le_of_mem_dist _ A _,
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : optimal_GH_injl X Y xX ∈ range (optimal_GH_injl X Y) := mem_range_self _,
rcases A _ this with ⟨y, yrange, hy⟩,
exact le_trans dist_nonneg hy },
{ assume y hy,
rcases mem_range.1 hy with ⟨z, hz⟩,
rw ← hz,
have I1 : (⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y)) < r :=
lt_of_le_of_lt (le_max_right _ _) hr,
have I2 : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) ≤
⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y) :=
le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _),
have I : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injl X Y z', mem_range_self _],
have : (optimal_GH_dist X Y) (inl z', inr z) ≤ r, by { rw hz', exact le_of_lt hr' },
rw dist_comm,
exact this }
end
end consequences
/- We are done with the construction of the optimal coupling -/
end Gromov_Hausdorff_realized
end Gromov_Hausdorff
|
a75aecbd2c29dc20e633487f475a36dfe1c7aacb | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/topology/continuous_on.lean | 5d8a922818c9f3a5e500e92edb9907a5d07cbbde | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,594 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.constructions
/-!
# Neighborhoods and continuity relative to a subset
This file defines relative versions
* `nhds_within` of `nhds`
* `continuous_on` of `continuous`
* `continuous_within_at` of `continuous_at`
and proves their basic properties, including the relationships between
these restricted notions and the corresponding notions for the subtype
equipped with the subspace topology.
## Notation
* `𝓝 x`: the filter of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`.
-/
open set filter
open_locale topological_space filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α]
@[simp] lemma nhds_bind_nhds_within {a : α} {s : set α} :
(𝓝 a).bind (λ x, 𝓝[s] x) = 𝓝[s] a :=
bind_inf_principal.trans $ congr_arg2 _ nhds_bind_nhds rfl
@[simp] lemma eventually_nhds_nhds_within {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
filter.ext_iff.1 nhds_bind_nhds_within {x | p x}
lemma eventually_nhds_within_iff {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x :=
eventually_inf_principal
@[simp] lemma eventually_nhds_within_nhds_within {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
begin
refine ⟨λ h, _, λ h, (eventually_nhds_nhds_within.2 h).filter_mono inf_le_left⟩,
simp only [eventually_nhds_within_iff] at h ⊢,
exact h.mono (λ x hx hxs, (hx hxs).self_of_nhds hxs)
end
theorem nhds_within_eq (a : α) (s : set α) :
𝓝[s] a = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) :=
((nhds_basis_opens a).inf_principal s).eq_binfi
theorem nhds_within_univ (a : α) : 𝓝[set.univ] a = 𝓝 a :=
by rw [nhds_within, principal_univ, inf_top_eq]
lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s)
(t : set α) :
(𝓝[t] a).has_basis p (λ i, s i ∩ t) :=
h.inf_principal t
lemma nhds_within_basis_open (a : α) (t : set α) :
(𝓝[t] a).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) :=
nhds_within_has_basis (nhds_basis_opens a) t
theorem mem_nhds_within {t : set α} {a : α} {s : set α} :
t ∈ 𝓝[s] a ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t :=
by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff
lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} :
t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t :=
(nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff
lemma diff_mem_nhds_within_compl {X : Type*} [topological_space X] {x : X} {s : set X}
(hs : s ∈ 𝓝 x) (t : set X) : s \ t ∈ 𝓝[tᶜ] x :=
diff_mem_inf_principal_compl hs t
lemma nhds_of_nhds_within_of_nhds
{s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : (t ∈ 𝓝 a) :=
begin
rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩,
exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw,
end
lemma preimage_nhds_within_coinduced' {π : α → β} {s : set β} {t : set α} {a : α}
(h : a ∈ t) (ht : is_open t)
(hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) :
π ⁻¹' s ∈ 𝓝[t] a :=
begin
letI := topological_space.coinduced (λ x : t, π x) subtype.topological_space,
rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩,
refine mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨π ⁻¹' V, mem_nhds_iff.mpr ⟨t ∩ π ⁻¹' V,
inter_subset_right t (π ⁻¹' V), _, mem_sep h mem_V⟩, subset.trans (inter_subset_left _ _)
(preimage_mono hVs)⟩,
obtain ⟨u, hu1, hu2⟩ := is_open_induced_iff.mp (is_open_coinduced.1 V_op),
rw [preimage_comp] at hu2,
rw [set.inter_comm, ←(subtype.preimage_coe_eq_preimage_coe_iff.mp hu2)],
exact hu1.inter ht,
end
lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) :
s ∈ 𝓝[t] a :=
mem_inf_of_left h
theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ 𝓝[s] a :=
mem_inf_of_right (mem_principal_self s)
theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) :
s ∩ t ∈ 𝓝[s] a :=
inter_mem self_mem_nhds_within (mem_inf_of_left h)
theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : 𝓝[s] a ≤ 𝓝[t] a :=
inf_le_inf_left _ (principal_mono.mpr h)
lemma pure_le_nhds_within {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a :=
le_inf (pure_le_nhds a) (le_principal_iff.2 ha)
lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) :
a ∈ t :=
pure_le_nhds_within ha ht
lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α}
(h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x :=
mem_of_mem_nhds_within hx h
lemma tendsto_const_nhds_within {l : filter β} {s : set α} {a : α} (ha : a ∈ s) :
tendsto (λ x : β, a) l (𝓝[s] a) :=
tendsto_const_pure.mono_right $ pure_le_nhds_within ha
theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝[s] a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
le_antisymm
(le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhds_within h)))
(inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _)))
theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhds_within_restrict'' s $ mem_inf_of_left h
theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhds_within_restrict' s (is_open.mem_nhds h₁ h₀)
theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) :
𝓝[t] a ≤ 𝓝[s] a :=
begin
rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩,
have : 𝓝[t] a = 𝓝[t ∩ u] a := nhds_within_restrict _ au u_open,
rw [this, inter_comm],
exact nhds_within_mono _ uts
end
theorem nhds_within_le_nhds {a : α} {s : set α} : 𝓝[s] a ≤ 𝓝 a :=
by { rw ← nhds_within_univ, apply nhds_within_le_of_mem, exact univ_mem }
lemma nhds_within_eq_nhds_within' {a : α} {s t u : set α}
(hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a :=
by rw [nhds_within_restrict' t hs, nhds_within_restrict' u hs, h₂]
theorem nhds_within_eq_nhds_within {a : α} {s t u : set α}
(h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) :
𝓝[t] a = 𝓝[u] a :=
by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂]
theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) :
𝓝[s] a = 𝓝 a :=
inf_eq_left.2 $ le_principal_iff.2 $ is_open.mem_nhds h₁ h₀
lemma preimage_nhds_within_coinduced {π : α → β} {s : set β} {t : set α} {a : α}
(h : a ∈ t) (ht : is_open t)
(hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) :
π ⁻¹' s ∈ 𝓝 a :=
by { rw ←nhds_within_eq_of_open h ht, exact preimage_nhds_within_coinduced' h ht hs }
@[simp] theorem nhds_within_empty (a : α) : 𝓝[∅] a = ⊥ :=
by rw [nhds_within, principal_empty, inf_bot_eq]
theorem nhds_within_union (a : α) (s t : set α) :
𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a :=
by { delta nhds_within, rw [←inf_sup_left, sup_principal] }
theorem nhds_within_inter (a : α) (s t : set α) :
𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a :=
by { delta nhds_within, rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] }
theorem nhds_within_inter' (a : α) (s t : set α) :
𝓝[s ∩ t] a = (𝓝[s] a) ⊓ 𝓟 t :=
by { delta nhds_within, rw [←inf_principal, inf_assoc] }
theorem nhds_within_inter_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) :
𝓝[s ∩ t] a = 𝓝[t] a :=
by { rw [nhds_within_inter, inf_eq_right], exact nhds_within_le_of_mem h }
@[simp] theorem nhds_within_singleton (a : α) : 𝓝[{a}] a = pure a :=
by rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)]
@[simp] theorem nhds_within_insert (a : α) (s : set α) :
𝓝[insert a s] a = pure a ⊔ 𝓝[s] a :=
by rw [← singleton_union, nhds_within_union, nhds_within_singleton]
lemma mem_nhds_within_insert {a : α} {s t : set α} :
t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a :=
by simp
lemma insert_mem_nhds_within_insert {a : α} {s t : set α} (h : t ∈ 𝓝[s] a) :
insert a t ∈ 𝓝[insert a s] a :=
by simp [mem_of_superset h]
lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β]
(a : α) (b : β) (s : set α) (t : set β) :
𝓝[s.prod t] (a, b) = 𝓝[s] a ×ᶠ 𝓝[t] b :=
by { delta nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] }
lemma nhds_within_prod {α : Type*} [topological_space α] {β : Type*} [topological_space β]
{s u : set α} {t v : set β} {a : α} {b : β}
(hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) :
(u.prod v) ∈ 𝓝[s.prod t] (a, b) :=
by { rw nhds_within_prod_eq, exact prod_mem_prod hu hv, }
lemma nhds_within_pi_eq' {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi I s] x = ⨅ i, comap (λ x, x i) (𝓝 (x i) ⊓ ⨅ (hi : i ∈ I), 𝓟 (s i)) :=
by simp only [nhds_within, nhds_pi, comap_inf, comap_infi, pi_def, comap_principal,
← infi_principal_finite hI, ← infi_inf_eq]
lemma nhds_within_pi_eq {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi I s] x = (⨅ i ∈ I, comap (λ x, x i) (𝓝[s i] (x i))) ⊓
⨅ (i ∉ I), comap (λ x, x i) (𝓝 (x i)) :=
begin
simp only [nhds_within, nhds_pi, pi_def, ← infi_principal_finite hI, comap_inf, comap_principal,
function.eval],
rw [infi_split _ (λ i, i ∈ I), inf_right_comm],
simp only [infi_inf_eq]
end
lemma nhds_within_pi_univ_eq {ι : Type*} {α : ι → Type*} [fintype ι] [Π i, topological_space (α i)]
(s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi univ s] x = ⨅ i, comap (λ x, x i) 𝓝[s i] (x i) :=
by simpa [nhds_within] using nhds_within_pi_eq finite_univ s x
lemma nhds_within_pi_univ_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{s : Π i, set (α i)} {x : Π i, α i} :
𝓝[pi univ s] x = ⊥ ↔ ∃ i, 𝓝[s i] (x i) = ⊥ :=
begin
classical,
split,
{ haveI : Π i, inhabited (α i) := λ i, ⟨x i⟩,
simp only [nhds_within, nhds_pi, inf_principal_eq_bot, mem_infi', mem_comap],
rintro ⟨I, hIf, V, hV, hVs⟩, choose! t htx htV using hV,
contrapose! hVs,
change ∀ i, ∃ᶠ y in 𝓝 (x i), y ∈ s i at hVs,
have : ∀ i ∈ I, (s i ∩ t i).nonempty, from λ i hi, ((hVs i).and_eventually (htx i hi)).exists,
choose! y hys hyt,
choose z hzs using λ i, (hVs i).exists,
suffices : I.piecewise y z ∈ (⋂ i ∈ I, V i) ∩ (pi univ s),
{ intro H, simpa [← H] },
refine ⟨mem_bInter $ λ i hi, htV i hi _, λ i hi', _⟩,
{ simp only [mem_preimage, piecewise_eq_of_mem _ _ _ hi, hyt i hi] },
{ by_cases hi : i ∈ I; simp * } },
{ rintro ⟨i, eq⟩,
rw [← @map_eq_bot_iff _ _ _ (λ x : Π i, α i, x i)],
refine eq_bot_mono _ eq,
exact ((continuous_apply i).tendsto x).inf
(tendsto_principal_principal.2 $ λ y hy, hy i trivial) }
end
lemma nhds_within_pi_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] (x i) = ⊥ :=
begin
classical,
rw [← univ_pi_piecewise I, nhds_within_pi_univ_eq_bot],
refine exists_congr (λ i, _),
by_cases hi : i ∈ I; simp [*, nhds_within_univ, nhds_ne_bot.ne]
end
lemma nhds_within_pi_ne_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
(𝓝[pi I s] x).ne_bot ↔ ∀ i ∈ I, (𝓝[s i] (x i)).ne_bot :=
by simp [ne_bot_iff, nhds_within_pi_eq_bot]
theorem filter.tendsto.piecewise_nhds_within {f g : α → β} {t : set α} [∀ x, decidable (x ∈ t)]
{a : α} {s : set α} {l : filter β}
(h₀ : tendsto f (𝓝[s ∩ t] a) l) (h₁ : tendsto g (𝓝[s ∩ tᶜ] a) l) :
tendsto (piecewise t f g) (𝓝[s] a) l :=
by apply tendsto.piecewise; rwa ← nhds_within_inter'
theorem filter.tendsto.if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p]
{a : α} {s : set α} {l : filter β}
(h₀ : tendsto f (𝓝[s ∩ {x | p x}] a) l)
(h₁ : tendsto g (𝓝[s ∩ {x | ¬ p x}] a) l) :
tendsto (λ x, if p x then f x else g x) (𝓝[s] a) l :=
h₀.piecewise_nhds_within h₁
lemma map_nhds_within (f : α → β) (a : α) (s : set α) :
map f (𝓝[s] a) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (f '' (t ∩ s)) :=
((nhds_within_basis_open a s).map f).eq_binfi
theorem tendsto_nhds_within_mono_left {f : α → β} {a : α}
{s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (𝓝[t] a) l) :
tendsto f (𝓝[s] a) l :=
h.mono_left $ nhds_within_mono a hst
theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β}
{a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (𝓝[s] a)) :
tendsto f l (𝓝[t] a) :=
h.mono_right (nhds_within_mono a hst)
theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α}
{s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) :
tendsto f (𝓝[s] a) l :=
h.mono_left inf_le_left
theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) :
𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) :=
by rw [comap_principal, set.preimage_image_eq _ subtype.coe_injective]
lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) :
ne_bot (𝓝[s] x) :=
mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx
lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s)
{x : α} (hx : ne_bot $ 𝓝[s] x) : x ∈ s :=
by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx
lemma dense_range.nhds_within_ne_bot {ι : Type*} {f : ι → α} (h : dense_range f) (x : α) :
ne_bot (𝓝[range f] x) :=
mem_closure_iff_cluster_pt.1 (h x)
lemma mem_closure_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) :=
by simp only [mem_closure_iff_nhds_within_ne_bot, nhds_within_pi_ne_bot]
lemma closure_pi_set {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
(I : set ι) (s : Π i, set (α i)) :
closure (pi I s) = pi I (λ i, closure (s i)) :=
set.ext $ λ x, mem_closure_pi
lemma dense_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)}
(I : set ι) (hs : ∀ i ∈ I, dense (s i)) :
dense (pi I s) :=
by simp only [dense_iff_closure_eq, closure_pi_set,
pi_congr rfl (λ i hi, (hs i hi).closure_eq), pi_univ]
lemma eventually_eq_nhds_within_iff {f g : α → β} {s : set α} {a : α} :
(f =ᶠ[𝓝[s] a] g) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x :=
mem_inf_principal
lemma eventually_eq_nhds_within_of_eq_on {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) :
f =ᶠ[𝓝[s] a] g :=
mem_inf_of_right h
lemma set.eq_on.eventually_eq_nhds_within {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) :
f =ᶠ[𝓝[s] a] g :=
eventually_eq_nhds_within_of_eq_on h
lemma tendsto_nhds_within_congr {f g : α → β} {s : set α} {a : α} {l : filter β}
(hfg : ∀ x ∈ s, f x = g x) (hf : tendsto f (𝓝[s] a) l) : tendsto g (𝓝[s] a) l :=
(tendsto_congr' $ eventually_eq_nhds_within_of_eq_on hfg).1 hf
lemma eventually_nhds_with_of_forall {s : set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) :
∀ᶠ x in 𝓝[s] a, p x :=
mem_inf_of_right h
lemma tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {a : α} {l : filter β}
{s : set α} (f : β → α) (h1 : tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) :
tendsto f l (𝓝[s] a) :=
tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩
@[simp] lemma tendsto_nhds_within_range {a : α} {l : filter β} {f : β → α} :
tendsto f l (𝓝[range f] a) ↔ tendsto f l (𝓝 a) :=
⟨λ h, h.mono_right inf_le_left, λ h, tendsto_inf.2
⟨h, tendsto_principal.2 $ eventually_of_forall mem_range_self⟩⟩
lemma filter.eventually_eq.eq_of_nhds_within {s : set α} {f g : α → β} {a : α}
(h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a :=
h.self_of_nhds_within hmem
lemma eventually_nhds_within_of_eventually_nhds {α : Type*} [topological_space α]
{s : set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) :
∀ᶠ x in 𝓝[s] a, p x :=
mem_nhds_within_of_mem_nhds h
/-!
### `nhds_within` and subtypes
-/
theorem mem_nhds_within_subtype {s : set α} {a : {x // x ∈ s}} {t u : set {x // x ∈ s}} :
t ∈ 𝓝[u] a ↔ t ∈ comap (coe : s → α) (𝓝[coe '' u] a) :=
by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within]
theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) :
𝓝[t] a = comap (coe : s → α) (𝓝[coe '' t] a) :=
filter.ext $ λ u, mem_nhds_within_subtype
theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) :
𝓝[s] a = map (coe : s → α) (𝓝 ⟨a, h⟩) :=
by simpa only [subtype.range_coe] using (embedding_subtype_coe.map_nhds_eq ⟨a, h⟩).symm
theorem mem_nhds_subtype_iff_nhds_within {s : set α} {a : s} {t : set s} :
t ∈ 𝓝 a ↔ coe '' t ∈ 𝓝[s] (a : α) :=
by rw [nhds_within_eq_map_subtype_coe a.coe_prop, mem_map,
preimage_image_eq _ subtype.coe_injective, subtype.coe_eta]
theorem preimage_coe_mem_nhds_subtype {s t : set α} {a : s} :
coe ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a :=
by simp only [mem_nhds_subtype_iff_nhds_within, subtype.image_preimage_coe, inter_mem_iff,
self_mem_nhds_within, and_true]
theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) :
tendsto f (𝓝[s] a) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l :=
by simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map, restrict]
variables [topological_space β] [topological_space γ] [topological_space δ]
/-- A function between topological spaces is continuous at a point `x₀` within a subset `s`
if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/
def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop :=
tendsto f (𝓝[s] x) (𝓝 (f x))
/-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition.
We register this fact for use with the dot notation, especially to use `tendsto.comp` as
`continuous_within_at.comp` will have a different meaning. -/
lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) :
tendsto f (𝓝[s] x) (𝓝 (f x)) := h
/-- A function between topological spaces is continuous on a subset `s`
when it's continuous at every point of `s` within `s`. -/
def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x
lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s)
(hx : x ∈ s) : continuous_within_at f s x :=
hf x hx
theorem continuous_within_at_univ (f : α → β) (x : α) :
continuous_within_at f set.univ x ↔ continuous_at f x :=
by rw [continuous_at, continuous_within_at, nhds_within_univ]
theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α}
(h : x ∈ s) :
continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ :=
tendsto_nhds_within_iff_subtype h f _
theorem continuous_within_at.tendsto_nhds_within {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : maps_to f s t) :
tendsto f (𝓝[s] x) (𝓝[t] (f x)) :=
tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_of_right $ mem_principal.2 $ ht⟩
theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α}
(h : continuous_within_at f s x) :
tendsto f (𝓝[s] x) (𝓝[f '' s] (f x)) :=
h.tendsto_nhds_within (maps_to_image _ _)
lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β}
{x : α} {y : β}
(hf : continuous_within_at f s x) (hg : continuous_within_at g t y) :
continuous_within_at (prod.map f g) (s.prod t) (x, y) :=
begin
unfold continuous_within_at at *,
rw [nhds_within_prod_eq, prod.map, nhds_prod_eq],
exact hf.prod_map hg,
end
lemma continuous_within_at_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
{f : α → Π i, π i} {s : set α} {x : α} :
continuous_within_at f s x ↔ ∀ i, continuous_within_at (λ y, f y i) s x :=
tendsto_pi
lemma continuous_on_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
{f : α → Π i, π i} {s : set α} :
continuous_on f s ↔ ∀ i, continuous_on (λ y, f y i) s :=
⟨λ h i x hx, tendsto_pi.1 (h x hx) i, λ h x hx, tendsto_pi.2 (λ i, h i x hx)⟩
theorem continuous_on_iff {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧
u ∩ s ⊆ f ⁻¹' t :=
by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within]
theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} :
continuous_on f s ↔ continuous (s.restrict f) :=
begin
rw [continuous_on, continuous_iff_continuous_at], split,
{ rintros h ⟨x, xs⟩,
exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) },
intros h x xs,
exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩)
end
theorem continuous_on_iff' {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s,
begin
intro t,
rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp],
simp only [subtype.preimage_coe_eq_preimage_coe_iff],
split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ }
end,
by rw [continuous_on_iff_continuous_restrict, continuous_def]; simp only [this]
theorem continuous_on_iff_is_closed {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s :=
have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s,
begin
intro t,
rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp],
simp only [subtype.preimage_coe_eq_preimage_coe_iff, eq_comm]
end,
by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this]
lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β}
(hf : continuous_on f s) (hg : continuous_on g t) :
continuous_on (prod.map f g) (s.prod t) :=
λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy)
lemma continuous_on_empty (f : α → β) : continuous_on f ∅ :=
λ x, false.elim
theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) :
𝓝[s] x ≤ comap f (𝓝[f '' s] (f x)) :=
map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image
theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} :
continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) :=
tendsto_iff_ptendsto _ _ _ _
lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ :=
by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at,
nhds_within_univ]
lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x)
(hs : s ⊆ t) : continuous_within_at f s x :=
h.mono_left (nhds_within_mono x hs)
lemma continuous_within_at.mono_of_mem {f : α → β} {s t : set α} {x : α}
(h : continuous_within_at f t x) (hs : t ∈ 𝓝[s] x) : continuous_within_at f s x :=
h.mono_left (nhds_within_le_of_mem hs)
lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝[s] x) :
continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x :=
by simp [continuous_within_at, nhds_within_restrict'' s h]
lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) :
continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x :=
by simp [continuous_within_at, nhds_within_restrict' s h]
lemma continuous_within_at_union {f : α → β} {s t : set α} {x : α} :
continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x :=
by simp only [continuous_within_at, nhds_within_union, tendsto_sup]
lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α}
(hs : continuous_within_at f s x) (ht : continuous_within_at f t x) :
continuous_within_at f (s ∪ t) x :=
continuous_within_at_union.2 ⟨hs, ht⟩
lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) :=
by haveI := (mem_closure_iff_nhds_within_ne_bot.1 hx);
exact (mem_closure_of_tendsto h $
mem_of_superset self_mem_nhds_within (subset_preimage_image f s))
lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β}
(h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A :=
closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx)
lemma continuous_within_at.image_closure {f : α → β} {s : set α}
(hf : ∀ x ∈ closure s, continuous_within_at f s x) :
f '' (closure s) ⊆ closure (f '' s) :=
begin
rintros _ ⟨x, hx, rfl⟩,
exact (hf x hx).mem_closure_image hx
end
lemma continuous_on.image_closure {f : α → β} {s : set α} (hf : continuous_on f (closure s)) :
f '' (closure s) ⊆ closure (f '' s) :=
continuous_within_at.image_closure $ λ x hx, (hf x hx).mono subset_closure
@[simp] lemma continuous_within_at_singleton {f : α → β} {x : α} : continuous_within_at f {x} x :=
by simp only [continuous_within_at, nhds_within_singleton, tendsto_pure_nhds]
@[simp] lemma continuous_within_at_insert_self {f : α → β} {x : α} {s : set α} :
continuous_within_at f (insert x s) x ↔ continuous_within_at f s x :=
by simp only [← singleton_union, continuous_within_at_union, continuous_within_at_singleton,
true_and]
alias continuous_within_at_insert_self ↔ _ continuous_within_at.insert_self
lemma continuous_within_at.diff_iff {f : α → β} {s t : set α} {x : α}
(ht : continuous_within_at f t x) :
continuous_within_at f (s \ t) x ↔ continuous_within_at f s x :=
⟨λ h, (h.union ht).mono $ by simp only [diff_union_self, subset_union_left],
λ h, h.mono (diff_subset _ _)⟩
@[simp] lemma continuous_within_at_diff_self {f : α → β} {s : set α} {x : α} :
continuous_within_at f (s \ {x}) x ↔ continuous_within_at f s x :=
continuous_within_at_singleton.diff_iff
theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α}
(h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) :
continuous_on finv (f '' s) :=
begin
refine continuous_on_iff'.2 (λ t ht, ⟨f '' (t ∩ s), _, _⟩),
{ rw ← image_restrict, exact h _ (ht.preimage continuous_subtype_coe) },
{ rw [inter_eq_self_of_subset_left (image_subset f (inter_subset_right t s)),
hleft.image_inter'] },
end
theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f)
{finv : β → α} (hleft : function.left_inverse finv f) :
continuous_on finv (range f) :=
begin
rw [← image_univ],
exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x)
end
lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s)
(h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ :=
begin
assume x hx,
unfold continuous_within_at,
have A := (h x (h₁ hx)).mono h₁,
unfold continuous_within_at at A,
rw ← h' hx at A,
exact A.congr' h'.eventually_eq_nhds_within.symm
end
lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) :
continuous_on g s :=
h.congr_mono h' (subset.refl _)
lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) :
continuous_on g s ↔ continuous_on f s :=
⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩
lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) :
continuous_within_at f s x :=
continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _)
lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x :=
begin
have : s = univ ∩ s, by rw univ_inter,
rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h
end
lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α}
(h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x :=
(h x (mem_of_mem_nhds hx)).continuous_at hx
lemma continuous_at.continuous_on {f : α → β} {s : set α} (hcont : ∀ x ∈ s, continuous_at f x) :
continuous_on f s :=
λ x hx, (hcont x hx).continuous_within_at
lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α}
(hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) :
continuous_within_at (g ∘ f) s x :=
hg.tendsto.comp (hf.tendsto_nhds_within h)
lemma continuous_within_at.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α}
(hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) :
continuous_within_at (g ∘ f) (s ∩ f⁻¹' t) x :=
hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma continuous_at.comp_continuous_within_at {g : β → γ} {f : α → β} {s : set α} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_within_at f s x) :
continuous_within_at (g ∘ f) s x :=
hg.continuous_within_at.comp hf subset_preimage_univ
lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β}
(hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) :
continuous_on (g ∘ f) s :=
λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h
lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) :
continuous_on f t :=
λx hx, (hf x (h hx)).mono_left (nhds_within_mono _ h)
lemma continuous_on.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β}
(hg : continuous_on g t) (hf : continuous_on f s) :
continuous_on (g ∘ f) (s ∩ f⁻¹' t) :=
hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) :
continuous_on f s :=
begin
rw continuous_iff_continuous_on_univ at h,
exact h.mono (subset_univ _)
end
lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) :
continuous_within_at f s x :=
h.continuous_at.continuous_within_at
lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α}
(hg : continuous g) (hf : continuous_on f s) :
continuous_on (g ∘ f) s :=
hg.continuous_on.comp hf subset_preimage_univ
lemma continuous_on.comp_continuous {g : β → γ} {f : α → β} {s : set β}
(hg : continuous_on g s) (hf : continuous f) (hs : ∀ x, f x ∈ s) : continuous (g ∘ f) :=
begin
rw continuous_iff_continuous_on_univ at *,
exact hg.comp hf (λ x _, hs x),
end
lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x :=
h ht
lemma set.left_inv_on.map_nhds_within_eq {f : α → β} {g : β → α} {x : β} {s : set β}
(h : left_inv_on f g s) (hx : f (g x) = x) (hf : continuous_within_at f (g '' s) (g x))
(hg : continuous_within_at g s x) :
map g (𝓝[s] x) = 𝓝[g '' s] (g x) :=
begin
apply le_antisymm,
{ exact hg.tendsto_nhds_within (maps_to_image _ _) },
{ have A : g ∘ f =ᶠ[𝓝[g '' s] (g x)] id,
from h.right_inv_on_image.eq_on.eventually_eq_of_mem self_mem_nhds_within,
refine le_map_of_right_inverse A _,
simpa only [hx] using hf.tendsto_nhds_within (h.maps_to (surj_on_image _ _)) }
end
lemma function.left_inverse.map_nhds_eq {f : α → β} {g : β → α} {x : β}
(h : function.left_inverse f g) (hf : continuous_within_at f (range g) (g x))
(hg : continuous_at g x) :
map g (𝓝 x) = 𝓝[range g] (g x) :=
by simpa only [nhds_within_univ, image_univ]
using (h.left_inv_on univ).map_nhds_within_eq (h x) (by rwa image_univ) hg.continuous_within_at
lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : t ∈ 𝓝[f '' s] (f x)) :
f ⁻¹' t ∈ 𝓝[s] x :=
h.tendsto_nhds_within (maps_to_image _ _) ht
lemma continuous_within_at.congr_of_eventually_eq {f f₁ : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
continuous_within_at f₁ s x :=
by rwa [continuous_within_at, filter.tendsto, hx, filter.map_congr h₁]
lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
continuous_within_at f₁ s x :=
h.congr_of_eventually_eq (mem_of_superset self_mem_nhds_within h₁) hx
lemma continuous_within_at.congr_mono {f g : α → β} {s s₁ : set α} {x : α}
(h : continuous_within_at f s x) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x):
continuous_within_at g s₁ x :=
(h.mono h₁).congr h' hx
lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s :=
continuous_const.continuous_on
lemma continuous_within_at_const {b : β} {s : set α} {x : α} :
continuous_within_at (λ _:α, b) s x :=
continuous_const.continuous_within_at
lemma continuous_on_id {s : set α} : continuous_on id s :=
continuous_id.continuous_on
lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x :=
continuous_id.continuous_within_at
lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) :
continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) :=
begin
rw continuous_on_iff',
split,
{ assume h t ht,
rcases h t ht with ⟨u, u_open, hu⟩,
rw [inter_comm, hu],
apply is_open.inter u_open hs },
{ assume h t ht,
refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩,
rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] }
end
lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) :=
(continuous_on_open_iff hs).1 hf t ht
lemma continuous_on.is_open_preimage {f : α → β} {s : set α} {t : set β} (h : continuous_on f s)
(hs : is_open s) (hp : f ⁻¹' t ⊆ s) (ht : is_open t) : is_open (f ⁻¹' t) :=
begin
convert (continuous_on_open_iff hs).mp h t ht,
rw [inter_comm, inter_eq_self_of_subset_left hp],
end
lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) :=
begin
rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩,
rw [inter_comm, hu.2],
apply is_closed.inter hu.1 hs
end
lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) :=
calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) :
interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset))
(hf.preimage_open_of_open hs is_open_interior)
... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, hs.interior_eq]
lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α}
(h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s :=
begin
assume x xs,
rcases h x xs with ⟨t, open_t, xt, ct⟩,
have := ct x ⟨xs, xt⟩,
rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this
end
lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β}
(hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) :
@continuous_on α β _ (topological_space.generate_from T) f s :=
begin
rw continuous_on_open_iff,
assume t ht,
induction ht with u hu u v Tu Tv hu hv U hU hU',
{ exact h u hu },
{ simp only [preimage_univ, inter_univ], exact hs },
{ have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v),
by { ext x, simp, split, finish, finish },
rw this,
exact is_open.inter hu hv },
{ rw [preimage_sUnion, inter_bUnion],
exact is_open_bUnion hU' },
{ exact hs }
end
lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (λx, (f x, g x)) s x :=
hf.prod_mk_nhds hg
lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α}
(hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s :=
λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
lemma inducing.continuous_on_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
begin
simp only [continuous_on_iff_continuous_restrict, restrict_eq],
conv_rhs { rw [function.comp.assoc, ← (inducing.continuous_iff hg)] },
end
lemma embedding.continuous_on_iff {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
inducing.continuous_on_iff hg.1
lemma continuous_within_at_of_not_mem_closure {f : α → β} {s : set α} {x : α} :
x ∉ closure s → continuous_within_at f s x :=
begin
intros hx,
rw [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, not_not] at hx,
rw [continuous_within_at, hx],
exact tendsto_bot,
end
lemma continuous_on.piecewise' {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)]
(hpf : ∀ a ∈ s ∩ frontier t, tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a)))
(hpg : ∀ a ∈ s ∩ frontier t, tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a)))
(hf : continuous_on f $ s ∩ t) (hg : continuous_on g $ s ∩ tᶜ) :
continuous_on (piecewise t f g) s :=
begin
intros x hx,
by_cases hx' : x ∈ frontier t,
{ exact (hpf x ⟨hx, hx'⟩).piecewise_nhds_within (hpg x ⟨hx, hx'⟩) },
{ rw [← inter_univ s, ← union_compl_self t, inter_union_distrib_left] at hx ⊢,
cases hx,
{ apply continuous_within_at.union,
{ exact (hf x hx).congr (λ y hy, piecewise_eq_of_mem _ _ _ hy.2)
(piecewise_eq_of_mem _ _ _ hx.2) },
{ have : x ∉ closure tᶜ,
from λ h, hx' ⟨subset_closure hx.2, by rwa closure_compl at h⟩,
exact continuous_within_at_of_not_mem_closure
(λ h, this (closure_inter_subset_inter_closure _ _ h).2) } },
{ apply continuous_within_at.union,
{ have : x ∉ closure t,
from (λ h, hx' ⟨h, (λ (h' : x ∈ interior t), hx.2 (interior_subset h'))⟩),
exact continuous_within_at_of_not_mem_closure
(λ h, this (closure_inter_subset_inter_closure _ _ h).2) },
{ exact (hg x hx).congr
(λ y hy, piecewise_eq_of_not_mem _ _ _ hy.2)
(piecewise_eq_of_not_mem _ _ _ hx.2) } } }
end
lemma continuous_on.if' {s : set α} {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hpf : ∀ a ∈ s ∩ frontier {a | p a},
tendsto f (𝓝[s ∩ {a | p a}] a) (𝓝 $ if p a then f a else g a))
(hpg : ∀ a ∈ s ∩ frontier {a | p a},
tendsto g (𝓝[s ∩ {a | ¬p a}] a) (𝓝 $ if p a then f a else g a))
(hf : continuous_on f $ s ∩ {a | p a}) (hg : continuous_on g $ s ∩ {a | ¬p a}) :
continuous_on (λ a, if p a then f a else g a) s :=
hf.piecewise' hpf hpg hg
lemma continuous_on.if {α β : Type*} [topological_space α] [topological_space β] {p : α → Prop}
[∀ a, decidable (p a)] {s : set α} {f g : α → β}
(hp : ∀ a ∈ s ∩ frontier {a | p a}, f a = g a) (hf : continuous_on f $ s ∩ closure {a | p a})
(hg : continuous_on g $ s ∩ closure {a | ¬ p a}) :
continuous_on (λa, if p a then f a else g a) s :=
begin
apply continuous_on.if',
{ rintros a ha,
simp only [← hp a ha, if_t_t],
apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure),
exact hf a ⟨ha.1, ha.2.1⟩ },
{ rintros a ha,
simp only [hp a ha, if_t_t],
apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure),
rcases ha with ⟨has, ⟨_, ha⟩⟩,
rw [← mem_compl_iff, ← closure_compl] at ha,
apply hg a ⟨has, ha⟩ },
{ exact hf.mono (inter_subset_inter_right s subset_closure) },
{ exact hg.mono (inter_subset_inter_right s subset_closure) }
end
lemma continuous_on.piecewise {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)]
(ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : continuous_on f $ s ∩ closure t)
(hg : continuous_on g $ s ∩ closure tᶜ) :
continuous_on (piecewise t f g) s :=
hf.if ht hg
lemma continuous_if' {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hpf : ∀ a ∈ frontier {x | p x}, tendsto f (𝓝[{x | p x}] a) (𝓝 $ ite (p a) (f a) (g a)))
(hpg : ∀ a ∈ frontier {x | p x}, tendsto g (𝓝[{x | ¬p x}] a) (𝓝 $ ite (p a) (f a) (g a)))
(hf : continuous_on f {x | p x}) (hg : continuous_on g {x | ¬p x}) :
continuous (λ a, ite (p a) (f a) (g a)) :=
begin
rw continuous_iff_continuous_on_univ,
apply continuous_on.if'; simp *; assumption
end
lemma continuous_if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous_on f (closure {x | p x}))
(hg : continuous_on g (closure {x | ¬p x})) :
continuous (λ a, if p a then f a else g a) :=
begin
rw continuous_iff_continuous_on_univ,
apply continuous_on.if; simp; assumption
end
lemma continuous.if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λ a, if p a then f a else g a) :=
continuous_if hp hf.continuous_on hg.continuous_on
lemma continuous_piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)]
(hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous_on f (closure s))
(hg : continuous_on g (closure sᶜ)) :
continuous (piecewise s f g) :=
continuous_if hs hf hg
lemma continuous.piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)]
(hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (piecewise s f g) :=
hf.if hs hg
lemma is_open.ite' {s s' t : set α}
(hs : is_open s) (hs' : is_open s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') :
is_open (t.ite s s') :=
begin
classical,
simp only [is_open_iff_continuous_mem, set.ite] at *,
convert continuous_piecewise (λ x hx, propext (ht x hx)) hs.continuous_on hs'.continuous_on,
ext x, by_cases hx : x ∈ t; simp [hx]
end
lemma is_open.ite {s s' t : set α} (hs : is_open s) (hs' : is_open s')
(ht : s ∩ frontier t = s' ∩ frontier t) :
is_open (t.ite s s') :=
hs.ite' hs' $ λ x hx, by simpa [hx] using ext_iff.1 ht x
lemma ite_inter_closure_eq_of_inter_frontier_eq {s s' t : set α}
(ht : s ∩ frontier t = s' ∩ frontier t) :
t.ite s s' ∩ closure t = s ∩ closure t :=
by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left,
ite_inter_self, ite_inter_of_inter_eq _ ht]
lemma ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : set α}
(ht : s ∩ frontier t = s' ∩ frontier t) :
t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ :=
by { rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq], rwa [frontier_compl, eq_comm] }
lemma continuous_on_piecewise_ite' {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)]
(h : continuous_on f (s ∩ closure t)) (h' : continuous_on f' (s' ∩ closure tᶜ))
(H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) :
continuous_on (t.piecewise f f') (t.ite s s') :=
begin
apply continuous_on.piecewise,
{ rwa ite_inter_of_inter_eq _ H },
{ rwa ite_inter_closure_eq_of_inter_frontier_eq H },
{ rwa ite_inter_closure_compl_eq_of_inter_frontier_eq H }
end
lemma continuous_on_piecewise_ite {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)]
(h : continuous_on f s) (h' : continuous_on f' s')
(H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) :
continuous_on (t.piecewise f f') (t.ite s s') :=
continuous_on_piecewise_ite' (h.mono (inter_subset_left _ _)) (h'.mono (inter_subset_left _ _))
H Heq
lemma continuous_on_fst {s : set (α × β)} : continuous_on prod.fst s :=
continuous_fst.continuous_on
lemma continuous_within_at_fst {s : set (α × β)} {p : α × β} :
continuous_within_at prod.fst s p :=
continuous_fst.continuous_within_at
lemma continuous_on_snd {s : set (α × β)} : continuous_on prod.snd s :=
continuous_snd.continuous_on
lemma continuous_within_at_snd {s : set (α × β)} {p : α × β} :
continuous_within_at prod.snd s p :=
continuous_snd.continuous_within_at
lemma continuous_within_at.fst {f : α → β × γ} {s : set α} {a : α}
(h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).fst) s a :=
continuous_at_fst.comp_continuous_within_at h
lemma continuous_within_at.snd {f : α → β × γ} {s : set α} {a : α}
(h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).snd) s a :=
continuous_at_snd.comp_continuous_within_at h
lemma continuous_within_at_prod_iff {f : α → β × γ} {s : set α} {x : α} :
continuous_within_at f s x ↔ continuous_within_at (prod.fst ∘ f) s x ∧
continuous_within_at (prod.snd ∘ f) s x :=
⟨λ h, ⟨h.fst, h.snd⟩, by { rintro ⟨h1, h2⟩, convert h1.prod h2, ext, refl, refl }⟩
|
c53dedbbfee3e0463400fd6aa1e3a16817f6c628 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/tactic/abel.lean | 7815857ad7b7499ce5c7695efb5e5c6f01320996 | [
"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 | 15,313 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.norm_num
/-!
# The `abel` tactic
Evaluate expressions in the language of additive, commutative monoids and groups.
-/
namespace tactic
namespace abel
/-- The `context` for a call to `abel`.
Stores a few options for this call, and caches some common subexpressions
such as typeclass instances and `0 : α`.
-/
meta structure context :=
(red : transparency)
(α : expr)
(univ : level)
(α0 : expr)
(is_group : bool)
(inst : expr)
/-- Populate a `context` object for evaluating `e`, up to reducibility level `red`. -/
meta def mk_context (red : transparency) (e : expr) : tactic context :=
do α ← infer_type e,
c ← mk_app ``add_comm_monoid [α] >>= mk_instance,
cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance),
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
α0 ← expr.of_nat α 0,
match cg with
| (some cg) := return ⟨red, α, u, α0, tt, cg⟩
| _ := return ⟨red, α, u, α0, ff, c⟩
end
/-- Apply the function `n : ∀ {α} [inst : add_whatever α], _` to the
implicit parameters in the context, and the given list of arguments. -/
meta def context.app (c : context) (n : name) (inst : expr) : list expr → expr :=
(@expr.const tt n [c.univ] c.α inst).mk_app
/-- Apply the function `n : ∀ {α} [inst α], _` to the implicit parameters in the
context, and the given list of arguments.
Compared to `context.app`, this takes the name of the typeclass, rather than an
inferred typeclass instance.
-/
meta def context.mk_app (c : context) (n inst : name) (l : list expr) : tactic expr :=
do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l
/-- Add the letter "g" to the end of the name, e.g. turning `term` into `termg`.
This is used to choose between declarations taking `add_comm_monoid` and those
taking `add_comm_group` instances.
-/
meta def add_g : name → name
| (name.mk_string s p) := name.mk_string (s ++ "g") p
| n := n
/-- Apply the function `n : ∀ {α} [add_comm_{monoid,group} α]` to the given
list of arguments.
Will use the `add_comm_{monoid,group}` instance that has been cached in the context.
-/
meta def context.iapp (c : context) (n : name) : list expr → expr :=
c.app (if c.is_group then add_g n else n) c.inst
def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := n • x + a
def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := n • x + a
/-- Evaluate a term with coefficient `n`, atom `x` and successor terms `a`. -/
meta def context.mk_term (c : context) (n x a : expr) : expr := c.iapp ``term [n, x, a]
/-- Interpret an integer as a coefficient to a term. -/
meta def context.int_to_expr (c : context) (n : ℤ) : tactic expr :=
expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n
meta inductive normal_expr : Type
| zero (e : expr) : normal_expr
| nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr
meta def normal_expr.e : normal_expr → expr
| (normal_expr.zero e) := e
| (normal_expr.nterm e _ _ _) := e
meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩
meta instance : has_coe_to_fun normal_expr (λ _, expr → expr) := ⟨λ e, ⇑(e : expr)⟩
meta def normal_expr.term' (c : context) (n : expr × ℤ) (x : expr) (a : normal_expr) :
normal_expr :=
normal_expr.nterm (c.mk_term n.1 x a) n x a
meta def normal_expr.zero' (c : context) : normal_expr := normal_expr.zero c.α0
meta def normal_expr.to_list : normal_expr → list (ℤ × expr)
| (normal_expr.zero _) := []
| (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list
open normal_expr
meta def normal_expr.to_string (e : normal_expr) : string :=
" + ".intercalate $ (to_list e).map $
λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")"
meta def normal_expr.pp (e : normal_expr) : tactic format :=
do l ← (to_list e).mmap (λ ⟨n, e⟩, do
pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")),
return $ format.join $ l.intersperse ↑" + "
meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩
meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') :
k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl
theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') :
k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl
theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') :
@term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc]
theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') :
@termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc]
theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a')
(h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') :
@term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' :=
by simp [h₁.symm, h₂.symm, term, add_nsmul]; ac_refl
theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a')
(h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') :
@termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' :=
by simp [h₁.symm, h₂.symm, termg, add_zsmul]; ac_refl
theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a :=
by simp [term, zero_nsmul, one_nsmul]
theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a :=
by simp [termg]
meta def eval_add (c : context) : normal_expr → normal_expr → tactic (normal_expr × expr)
| (zero _) e₂ := do
p ← mk_app ``zero_add [e₂],
return (e₂, p)
| e₁ (zero _) := do
p ← mk_app ``add_zero [e₁],
return (e₁, p)
| he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) :=
(do
is_def_eq x₁ x₂ c.red,
(n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.eval_field,
(a', h₂) ← eval_add a₁ a₂,
let k := n₁.2 + n₂.2,
let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂],
if k = 0 then do
p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']),
return (a', p)
else return (term' c (n', k) x₁ a', p₁))
<|> if expr.lex_lt x₁ x₂ then do
(a', h) ← eval_add a₁ he₂,
return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h])
else do
(a', h) ← eval_add he₁ a₂,
return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h])
theorem term_neg {α} [add_comm_group α] (n x a n' a')
(h₁ : -n = n') (h₂ : -a = a') :
-@termg α _ n x a = termg n' x a' :=
by simp [h₂.symm, h₁.symm, termg]; ac_refl
meta def eval_neg (c : context) : normal_expr → tactic (normal_expr × expr)
| (zero e) := do
p ← c.mk_app ``neg_zero ``add_group [],
return (zero' c, p)
| (nterm e n x a) := do
(n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.eval_field,
(a', h₂) ← eval_neg a,
return (term' c (n', -n.2) x a',
c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂])
def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := n • x
def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := n • x
theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 :=
by simp [smul, nsmul_zero]
theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 :=
by simp [smulg]
theorem term_smul {α} [add_comm_monoid α] (c n x a n' a')
(h₁ : c * n = n') (h₂ : smul c a = a') :
smul c (@term α _ n x a) = term n' x a' :=
by simp [h₂.symm, h₁.symm, term, smul, nsmul_add, mul_nsmul]
theorem term_smulg {α} [add_comm_group α] (c n x a n' a')
(h₁ : c * n = n') (h₂ : smulg c a = a') :
smulg c (@termg α _ n x a) = termg n' x a' :=
by simp [h₂.symm, h₁.symm, termg, smulg, zsmul_add, mul_zsmul]
meta def eval_smul (c : context) (k : expr × ℤ) :
normal_expr → tactic (normal_expr × expr)
| (zero _) := return (zero' c, c.iapp ``zero_smul [k.1])
| (nterm e n x a) := do
(n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.eval_field,
(a', h₂) ← eval_smul a,
return (term' c (n', k.2 * n.2) x a',
c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂])
theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 :=
by simp [term]
theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 :=
by simp [termg]
meta def eval_atom (c : context) (e : expr) : tactic (normal_expr × expr) :=
do n1 ← c.int_to_expr 1,
return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e])
lemma unfold_sub {α} [add_group α] (a b c : α)
(h : a + -b = c) : a - b = c :=
by rw [sub_eq_add_neg, h]
theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α)
(h : smul n x = y) : n • x = y := h
theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α)
(h : smulg (int.of_nat n) x = y) : (n : ℤ) • x = y := h
theorem unfold_zsmul {α} [add_comm_group α] (n : ℤ) (x y : α)
(h : smulg n x = y) : n • x = y := h
lemma subst_into_smul {α} [add_comm_monoid α]
(l r tl tr t) (prl : l = tl) (prr : r = tr)
(prt : @smul α _ tl tr = t) : smul l r = t :=
by simp [prl, prr, prt]
lemma subst_into_smulg {α} [add_comm_group α]
(l r tl tr t) (prl : l = tl) (prr : r = tr)
(prt : @smulg α _ tl tr = t) : smulg l r = t :=
by simp [prl, prr, prt]
/-- Deal with a `smul` term of the form `e₁ • e₂`, handling both natural and integer `e₁`. -/
meta def eval_smul' (c : context) (eval : expr → tactic (normal_expr × expr))
(e₁ e₂ : expr) : tactic (normal_expr × expr) :=
do (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁,
n ← if c.is_group then e₁'.to_int else coe <$> e₁'.to_nat,
(e₂', p₂) ← eval e₂,
(e', p) ← eval_smul c (e₁', n) e₂',
return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p])
meta def eval (c : context) : expr → tactic (normal_expr × expr)
| `(%%e₁ + %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_add c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| `(%%e₁ - %%e₂) := do
e₂' ← mk_app ``has_neg.neg [e₂],
e ← mk_app ``has_add.add [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p],
return (e', p')
| `(- %%e) := do
(e₁, p₁) ← eval e,
(e₂, p₂) ← eval_neg c e₁,
p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂],
return (e₂, p)
| `(add_monoid.nsmul %%e₁ %%e₂) := do
n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁,
(e', p) ← eval $ c.iapp ``smul [n, e₂],
return (e', c.iapp ``unfold_smul [e₁, e₂, e', p])
| `(sub_neg_monoid.zsmul %%e₁ %%e₂) := do
guardb c.is_group,
(e', p) ← eval $ c.iapp ``smul [e₁, e₂],
return (e', c.app ``unfold_zsmul c.inst [e₁, e₂, e', p])
| `(@has_scalar.smul nat _ add_monoid.has_scalar_nat %%e₁ %%e₂) := eval_smul' c eval e₁ e₂
| `(@has_scalar.smul int _ sub_neg_monoid.has_scalar_int %%e₁ %%e₂) := eval_smul' c eval e₁ e₂
| `(smul %%e₁ %%e₂) := eval_smul' c eval e₁ e₂
| `(smulg %%e₁ %%e₂) := eval_smul' c eval e₁ e₂
| e := eval_atom c e
meta def eval' (c : context) (e : expr) : tactic (expr × expr) :=
do (e', p) ← eval c e, return (e', p)
@[derive has_reflect]
inductive normalize_mode | raw | term
instance : inhabited normalize_mode := ⟨normalize_mode.term⟩
meta def normalize (red : transparency) (mode := normalize_mode.term) (e : expr) :
tactic (expr × expr) := do
pow_lemma ← simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.term :=
[``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``one_nsmul, ``one_zsmul,
``zsmul_zero]
| _ := []
end,
lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
c ← mk_context red e,
(new_e, pr) ← match mode with
| normalize_mode.raw := eval' c
| normalize_mode.term := trans_conv (eval' c)
(λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf))
end e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, ff))
(λ _ _ _ _ _, failed) `eq e,
return (e', pr)
end abel
namespace interactive
open tactic.abel
setup_tactic_parser
/-- Tactic for solving equations in the language of
*additive*, commutative monoids and groups.
This version of `abel` fails if the target is not an equality
that is provable by the axioms of commutative monoids/groups.
`abel1!` will use a more aggressive reducibility setting to identify atoms.
This can prove goals that `abel` cannot, but is more expensive.
-/
meta def abel1 (red : parse (tk "!")?) : tactic unit :=
do `(%%e₁ = %%e₂) ← target,
c ← mk_context (if red.is_some then semireducible else reducible) e₁,
(e₁', p₁) ← eval c e₁,
(e₂', p₂) ← eval c e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
meta def abel.mode : lean.parser abel.normalize_mode :=
with_desc "(raw|term)?" $
do mode ← ident?, match mode with
| none := return abel.normalize_mode.term
| some `term := return abel.normalize_mode.term
| some `raw := return abel.normalize_mode.raw
| _ := failed
end
/--
Evaluate expressions in the language of *additive*, commutative monoids and groups.
It attempts to prove the goal outright if there is no `at`
specifier and the target is an equality, but if this
fails, it falls back to rewriting all monoid expressions into a normal form.
If there is an `at` specifier, it rewrites the given target into a normal form.
`abel!` will use a more aggressive reducibility setting to identify atoms.
This can prove goals that `abel` cannot, but is more expensive.
```lean
example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel
example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel
example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 :=
by { abel at hyp, exact hyp }
example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - (id a + b) = 0 := by abel!
```
-/
meta def abel (red : parse (tk "!")?) (SOP : parse abel.mode) (loc : parse location) :
tactic unit :=
match loc with
| interactive.loc.ns [none] := abel1 red
| _ := failed
end <|>
do ns ← loc.get_locals,
let red := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize red SOP) ns loc.include_goal
| fail "abel failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "abel",
category := doc_category.tactic,
decl_names := [`tactic.interactive.abel],
tags := ["arithmetic", "decision procedure"] }
end interactive
end tactic
|
d2dbe58937d458a59d277f74df7597124aeeaf38 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/topology/metric_space/emetric_space.lean | 03f5963a474711393dae900cbb99bfdf3a075459 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 36,158 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.real.nnreal data.real.ennreal
import topology.uniform_space.separation topology.uniform_space.uniform_embedding topology.uniform_space.pi
import topology.bases
/-!
# Extended metric spaces
This file is devoted to the definition and study of `emetric_spaces`, i.e., metric
spaces in which the distance is allowed to take the value ∞. This extended distance is
called `edist`, and takes values in `ennreal`.
Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
The class `emetric_space` therefore extends `uniform_space` (and `topological_space`).
-/
open lattice set filter classical
noncomputable theory
open_locale uniformity topological_space
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Characterizing uniformities associated to a (generalized) distance function `D`
in terms of the elements of the uniformity. -/
theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β)
(H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) :
U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} :=
le_antisymm
(le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩)
(λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in
mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h)
class has_edist (α : Type*) := (edist : α → α → ennreal)
export has_edist (edist)
/- Design note: one could define an `emetric_space` just by giving `edist`, and then
derive an instance of `uniform_space` by taking the natural uniform structure
associated to the distance. This creates diamonds problem for products, as the
uniform structure on the product of two emetric spaces could be obtained first
by obtaining two uniform spaces and then taking their products, or by taking
the product of the emetric spaces and then the associated uniform structure.
The two uniform structure we have just described are equal, but not defeq, which
creates a lot of problem.
The idea is to add, in the very definition of an `emetric_space`, a uniform structure
with a uniformity which equal to the one given by the distance, but maybe not defeq.
And the instance from `emetric_space` to `uniform_space` uses this uniformity.
In this way, when we create the product of emetric spaces, we put in the product
the uniformity corresponding to the product of the uniformities. There is one more
proof obligation, that this product uniformity is equal to the uniformity corresponding
to the product metric. But the diamond problem disappears.
The same trick is used in the definition of a metric space, where one stores as well
a uniform structure and an edistance. -/
/-- Creating a uniform space from an extended distance. -/
def uniform_space_of_edist
(edist : α → α → ennreal)
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt},
comp :=
le_infi $ assume ε, le_infi $ assume h,
have (2 : ennreal) = (2 : ℕ) := by simp,
have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩,
lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $
have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε,
from assume a b c hac hcb,
calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _
... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb
... = ε : by rw [ennreal.add_halves],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Extended metric spaces, with an extended distance `edist` possibly taking the
value ∞
Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. There is a default value for the uniformity, that can be substituted
in cases of interest, for instance when instantiating an `emetric_space` structure
on a product.
Continuity of `edist` is finally proving in `topology.instances.ennreal`
-/
class emetric_space (α : Type u) extends has_edist α : Type u :=
(edist_self : ∀ x : α, edist x x = 0)
(eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z)
(to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle)
(uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac)
end prio
/- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated
namespace, while notions associated to metric spaces are mostly in the root namespace. -/
variables [emetric_space α]
@[priority 100] -- see Note [lower instance priority]
instance emetric_space.to_uniform_space' : uniform_space α :=
emetric_space.to_uniform_space α
export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle)
attribute [simp] edist_self
/-- Characterize the equality of points by the vanishing of their extended distance -/
@[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y :=
iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _)
@[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y :=
iff.intro (assume h, eq_of_edist_eq_zero (h.symm))
(assume : x = y, this ▸ (edist_self _).symm)
theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y :=
le_zero_iff_eq.trans edist_eq_zero
/-- Triangle inequality for the extended distance -/
theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y :=
by rw edist_comm z; apply edist_triangle
theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z :=
by rw edist_comm y; apply edist_triangle
lemma edist_triangle4 (x y z t : α) :
edist x t ≤ edist x y + edist y z + edist z t :=
calc
edist x t ≤ edist x z + edist z t : edist_triangle x z t
... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z)
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) :
edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) :=
begin
revert n,
refine nat.le_induction _ _,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self],
-- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too.
exact le_refl (0:ennreal) },
{ assume n hn hrec,
calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _
... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _)
... = (finset.Ico m (n+1)).sum _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) :
edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n)
/-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f m) (f n) ≤ (finset.Ico m n).sum d :=
le_trans (edist_le_Ico_sum_edist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f 0) (f n) ≤ (finset.range n).sum d :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd)
/-- Two points coincide if their distance is `< ε` for all positive ε -/
theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y :=
eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h)
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_edist' : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) :=
emetric_space.uniformity_edist _
/-- Reformulation of the uniform structure in terms of the extended distance on a subtype -/
theorem uniformity_edist'' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) :=
by simp [infi_subtype]; exact uniformity_edist'
theorem uniformity_edist_nnreal :
𝓤 α = (⨅(ε:nnreal) (h : ε > 0), principal {p:α×α | edist p.1 p.2 < ε}) :=
begin
rw [uniformity_edist', ennreal.infi_ennreal, inf_of_le_left],
{ congr, funext ε, refine infi_congr_Prop ennreal.coe_pos _, assume h, refl },
refine le_infi (assume h, infi_le_of_le 1 $ infi_le_of_le ennreal.zero_lt_one $ _),
exact principal_mono.2 (assume p h, lt_of_lt_of_le h le_top)
end
/-- Characterization of the elements of the uniformity in terms of the extended distance -/
theorem mem_uniformity_edist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
begin
rw [uniformity_edist'', mem_infi],
simp [subset_def],
exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩,
exact ⟨⟨1, ennreal.zero_lt_one⟩⟩
end
/-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/
theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) :
{p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩
namespace emetric
/-- ε-δ characterization of uniform continuity on emetric spaces -/
theorem uniform_continuous_iff [emetric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε :=
uniform_continuous_def.trans
⟨λ H ε ε0, mem_uniformity_edist.1 $ H _ $ edist_mem_uniformity ε0,
λ H r ru,
let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in
mem_uniformity_edist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩
/-- ε-δ characterization of uniform embeddings on emetric spaces -/
theorem uniform_embedding_iff [emetric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [emetric_space β] {f : α → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : edist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : edist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
/-- ε-δ characterization of Cauchy sequences on emetric spaces -/
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε :=
cauchy_iff.trans $ and_congr iff.rfl
⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (edist_mem_uniformity ε0) in
⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩,
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, tf, h⟩ := H ε ε0 in
⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩
end emetric
open emetric
/-- An emetric space is separated -/
@[priority 100] -- see Note [lower instance priority]
instance to_separated : separated α :=
separated_def.2 $ λ x y h, eq_of_forall_edist_le $
λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0))
/-- Auxiliary function to replace the uniformity on an emetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct an emetric space with a
specified uniformity. -/
def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α)
(H : @uniformity _ U = @uniformity _ (emetric_space.to_uniform_space α)) :
emetric_space α :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) }
/-- The extended metric induced by an injective function taking values in an emetric space. -/
def emetric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : emetric_space β) : emetric_space α :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h),
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Emetric space instance on subsets of emetric spaces -/
instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) :=
t.induced subtype.val (λ x y, subtype.eq)
/-- The extended distance on a subset of an emetric space is the restriction of
the original distance, by definition -/
theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist x.1 y.1 := rfl
/-- The product of two emetric spaces, with the max distance, is an extended
metric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) :=
{ edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
have A : x.fst = y.fst := edist_le_zero.1 h₁,
have B : x.snd = y.snd := edist_le_zero.1 h₂,
exact prod.ext_iff.2 ⟨A, B⟩
end,
edist_comm := λ x y, by simp [edist_comm],
edist_triangle := λ x y z, max_le
(le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _)))
(le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))),
uniformity_edist := begin
refine uniformity_prod.trans _,
simp [emetric_space.uniformity_edist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of emetric spaces, with the max distance, is still
an emetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) :=
{ edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_self := assume f, bot_unique $ finset.sup_le $ by simp,
edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _,
edist_triangle := assume f g h,
begin
simp only [finset.sup_le_iff],
assume b hb,
exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb))
end,
eq_of_edist_eq_zero := assume f g eq0,
begin
have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0,
simp only [finset.sup_le_iff] at eq1,
exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b),
end,
to_uniform_space := Pi.uniform_space _,
uniformity_edist := begin
simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq,
comap_principal],
rw infi_comm, congr, funext ε,
rw infi_comm, congr, funext εpos,
change 0 < ε at εpos,
simp [ext_iff, εpos]
end }
end pi
namespace emetric
variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α}
/-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/
def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl
/-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/
def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y, by simp; intros h; apply le_of_lt h
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt (zero_le _) hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show edist x x < ε, by rw edist_self; assumption
theorem mem_closed_ball_self : x ∈ closed_ball x ε :=
show edist x x ≤ ε, by rw edist_self; exact bot_le
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [edist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (edist_triangle_left x y z)
(lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h)
theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, calc
edist z y ≤ edist z x + edist x y : edist_triangle _ _ _
... = edist x y + edist z x : add_comm _ _
... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx
... ≤ ε₂ : h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
begin
have : 0 < ε - edist y x := by simpa using h,
refine ⟨ε - edist y x, this, ball_subset _ _⟩,
{ rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _},
{ have : edist y x ≠ ⊤ := lattice.ne_top_of_lt h, apply lt_top_iff_ne_top.2 this }
end
theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))),
λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩
theorem nhds_eq : 𝓝 x = (⨅ε:{ε:ennreal // ε>0}, principal (ball x ε.val)) :=
begin
rw [nhds_eq_uniformity, uniformity_edist'', lift'_infi],
{ apply congr_arg, funext ε,
rw [lift'_principal],
{ simp [ball, edist_comm] },
{ exact monotone_preimage } },
{ exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ },
{ intros, refl }
end
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
begin
rw [nhds_eq, mem_infi],
{ simp },
{ intros y z, cases y with y hy, cases z with z hz,
refine ⟨⟨min y z, lt_min hy hz⟩, _⟩,
simp [ball_subset_ball, min_le_left, min_le_right, (≥)] },
{ exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }
end
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
/-- ε-characterization of the closure in emetric spaces -/
theorem mem_closure_iff' :
x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε :=
⟨begin
intros hx ε hε,
have A : ball x ε ∩ s ≠ ∅ := mem_closure_iff.1 hx _ is_open_ball (mem_ball_self hε),
cases ne_empty_iff_exists_mem.1 A with y hy,
simp,
exact ⟨y, ⟨hy.2, by have B := hy.1; simpa [mem_ball'] using B⟩⟩
end,
begin
intros H,
apply mem_closure_iff.2,
intros o ho xo,
rcases is_open_iff.1 ho x xo with ⟨ε, ⟨εpos, hε⟩⟩,
rcases H ε εpos with ⟨y, ⟨ys, ydist⟩⟩,
have B : y ∈ o ∩ s := ⟨hε (by simpa [edist_comm]), ys⟩,
apply ne_empty_of_mem B
end⟩
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, edist (u x) a < ε :=
⟨λ H ε ε0, ⟨u⁻¹' (ball a ε), H (ball_mem_nhds _ ε0), by simp⟩,
λ H s hs,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in
f.sets_of_superset δ0 (λx xδ, hε (hδ x xδ))⟩
theorem tendsto_at_top [inhabited β] [semilattice_sup β] (u : β → α) {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε :=
begin
rw tendsto_nhds,
apply forall_congr,
intro ε,
apply forall_congr,
intro hε,
simp,
exact ⟨λ ⟨s, ⟨N, hN⟩, hs⟩, ⟨N, λn hn, hs _ (hN _ hn)⟩, λ ⟨N, hN⟩, ⟨{n | n ≥ N}, ⟨⟨N, by simp⟩, hN⟩⟩⟩,
end
/-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually,
the edistance between its elements is arbitrarily small -/
theorem cauchy_seq_iff [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u n) (u m) < ε :=
begin
simp only [cauchy_seq, emetric.cauchy_iff, true_and, exists_prop, filter.mem_at_top_sets,
filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq],
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩,
exact ⟨N, λm n hm hn, ht _ _ (hN _ hn) (hN _ hm)⟩ },
{ intros H ε εpos,
rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩,
existsi ball (u N) (ε/2),
split,
{ exact ⟨N, λx hx, hN _ _ (le_refl N) hx⟩ },
{ exact λx y hx hy, calc
edist x y ≤ edist x (u N) + edist y (u N) : edist_triangle_right _ _ _
... < ε/2 + ε/2 : ennreal.add_lt_add hx hy
... = ε : ennreal.add_halves _ } }
end
/-- A variation around the emetric characterization of Cauchy sequences -/
theorem cauchy_seq_iff' [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε :=
begin
rw cauchy_seq_iff,
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨N, hN⟩,
exact ⟨N, λn hn, hN _ _ (le_refl N) hn⟩ },
{ intros H ε εpos,
rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩,
exact ⟨N, λ m n hm hn, calc
edist (u n) (u m) ≤ edist (u n) (u N) + edist (u m) (u N) : edist_triangle_right _ _ _
... < ε/2 + ε/2 : ennreal.add_lt_add (hN _ hn) (hN _ hm)
... = ε : ennreal.add_halves _⟩ }
end
/-- A variation of the emetric characterization of Cauchy sequences that deals with
`nnreal` upper bounds. -/
theorem cauchy_seq_iff_nnreal [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u N) (u n) < ε :=
begin
refine cauchy_seq_iff'.trans
⟨λ H ε εpos, (H ε (ennreal.coe_pos.2 εpos)).imp $
λ N hN n hn, edist_comm (u n) (u N) ▸ hN n hn,
λ H ε εpos, _⟩,
specialize H ((min 1 ε).to_nnreal)
(ennreal.to_nnreal_pos_iff.2 ⟨lt_min ennreal.zero_lt_one εpos,
ennreal.lt_top_iff_ne_top.1 $ min_lt_iff.2 $ or.inl ennreal.coe_lt_top⟩),
refine H.imp (λ N hN n hn, edist_comm (u N) (u n) ▸ lt_of_lt_of_le (hN n hn) _),
refine ennreal.coe_le_iff.2 _,
rintros ε rfl,
rw [← ennreal.coe_one, ← ennreal.coe_min, ennreal.to_nnreal_coe],
apply min_le_right
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
theorem totally_bounded_iff' {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, _, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
section compact
/-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/
lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) :
∃ t ⊆ s, (countable t ∧ s = closure t) :=
begin
have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) :=
totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1,
-- assume e, finite_cover_balls_of_compact hs,
have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)),
{ intro e,
cases le_or_gt e 0 with h,
{ exact ⟨∅, by finish⟩ },
{ rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }},
/-The desired countable set is obtained by taking for each `n` the centers of a finite cover
by balls of radius `1/n`, and then the union over `n`. -/
choose T T_in_s finite_T using B,
let t := ⋃n:ℕ, T n⁻¹,
have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end,
have T₂ : countable t := by finish [countable_Union, countable_finite],
have T₃ : s ⊆ closure t,
{ intros x x_in_s,
apply mem_closure_iff'.2,
intros ε εpos,
rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩,
have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot],
have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) :=
mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos),
rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩,
simp at Dxy, -- Dxy : edist x y < 1 / ↑n
have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)),
have : edist x y < ε := lt_trans Dxy hn,
exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ },
have T₄ : closure t ⊆ s := calc
closure t ⊆ closure s : closure_mono T₁
... = s : closure_eq_of_is_closed (closed_of_compact _ hs),
exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩
end
end compact
section first_countable
@[priority 100] -- see Note [lower instance priority]
instance (α : Type u) [emetric_space α] :
topological_space.first_countable_topology α :=
⟨assume a, ⟨⋃ i:ℕ, {ball a i⁻¹},
countable_Union $ assume n, countable_singleton _,
suffices (⨅ i:{ i : ennreal // i > 0}, principal (ball a i)) = ⨅ (n : ℕ), principal (ball a n⁻¹),
by simpa [nhds_eq, @infi_comm _ _ ℕ],
begin
apply le_antisymm,
{ refine le_infi (assume n, infi_le_of_le _ _),
exact ⟨n⁻¹, by apply bot_lt_iff_ne_bot.2; simp⟩,
exact le_refl _ },
refine le_infi (assume ε, _),
rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 ε.2) with ⟨n, εn⟩,
exact infi_le_of_le n (principal_mono.2 $ ball_subset_ball $ le_of_lt εn)
end⟩⟩
end first_countable
section second_countable
open topological_space
/-- A separable emetric space is second countable: one obtains a countable basis by taking
the balls centered at points in a dense subset, and with rational radii. We do not register
this as an instance, as there is already an instance going in the other direction
from second countable spaces to separable spaces, and we want to avoid loops. -/
lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] :
second_countable_topology α :=
let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ α in
⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)},
⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)},
{ apply countable_bUnion S_countable,
intros a aS,
apply countable_Union,
simp },
show uniform_space.to_topological_space α = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}),
{ have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u,
{ simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib],
intros u x hx i u_ball,
rw [u_ball],
exact is_open_ball },
have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))),
{ refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _),
rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩,
have : ε / 2 > 0 := ennreal.half_pos εpos,
/- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)`
containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and
then `x` in `S` at distance at most `n⁻¹` of `a` -/
rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩,
have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot],
have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp,
rcases mem_closure_iff'.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩,
existsi ball x (↑n)⁻¹,
have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc
edist y a = edist a y : edist_comm _ _
... ≤ edist a x + edist y x : edist_triangle_right _ _ _
... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist
... < ε/2 + ε/2 : ennreal.add_lt_add εn εn
... = ε : ennreal.add_halves _,
simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff],
exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ },
exact B.2.2 }⟩⟩⟩
end second_countable
section diam
/-- The diameter of a set in an emetric space, named `emetric.diam` -/
def diam (s : set α) := Sup ((λp : α × α, edist p.1 p.2) '' (set.prod s s))
/-- If two points belong to some set, their edistance is bounded by the diameter of the set -/
lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s :=
le_Sup ((mem_image _ _ _).2 ⟨(⟨x, y⟩ : α × α), by simp [hx, hy]⟩)
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀x y ∈ s, edist x y ≤ d) : diam s ≤ d :=
begin
apply Sup_le _,
simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists],
assume b x y xs ys dxy,
rw ← dxy,
exact h x y xs ys
end
/-- The diameter of the empty set vanishes -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
by simp [diam]
/-- The diameter of a singleton vanishes -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
by simp [diam]
/-- The diameter is monotonous with respect to inclusion -/
lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t :=
begin
refine Sup_le_Sup (λp hp, _),
simp only [set.mem_image, set.mem_prod, prod.exists] at hp,
rcases hp with ⟨x, y, ⟨⟨xs, ys⟩, dxy⟩⟩,
exact (mem_image _ _ _).2 ⟨⟨x, y⟩, ⟨⟨h xs, h ys⟩, dxy⟩⟩
end
/-- The diameter of a union is controlled by the diameter of the sets, and the edistance
between two points in the sets. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t :=
begin
have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc
edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _
... ≤ diam s + edist x y + diam t :
add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb),
refine diam_le_of_forall_edist_le (λa b ha hb, _),
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b
... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _)
... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [edist_comm] at Z },
{ calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b
... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) }
end
lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t :=
let ⟨x, ⟨xs, xt⟩⟩ := ne_empty_iff_exists_mem.1 h in by simpa using diam_union xs xt
lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_edist_le $ λa b ha hb, calc
edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add' ha hb
... = 2 * r : by simp [mul_two, mul_comm]
lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball
end diam
end emetric --namespace
|
68bf117b3cefae42db7fe7dc624ab4d9e6247db9 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/abelian/transfer.lean | 80335de073b91bc93938fc41d8c98bd3582bc53d | [
"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 | 8,013 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.preadditive.additive_functor
import category_theory.abelian.basic
import category_theory.limits.preserves.shapes.kernels
import category_theory.adjunction.limits
/-!
# Transferring "abelian-ness" across a functor
If `C` is an additive category, `D` is an abelian category,
we have `F : C ⥤ D` `G : D ⥤ C` (both preserving zero morphisms),
`G` is left exact (that is, preserves finite limits),
and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`,
then `C` is also abelian.
See <https://stacks.math.columbia.edu/tag/03A3>
## Notes
The hypotheses, following the statement from the Stacks project,
may appear suprising: we don't ask that the counit of the adjunction is an isomorphism,
but just that we have some potentially unrelated isomorphism `i : F ⋙ G ≅ 𝟭 C`.
However Lemma A1.1.1 from [Elephant] shows that in this situation the counit itself
must be an isomorphism, and thus that `C` is a reflective subcategory of `D`.
Someone may like to formalize that lemma, and restate this theorem in terms of `reflective`.
(That lemma has a nice string diagrammatic proof that holds in any bicategory.)
-/
noncomputable theory
namespace category_theory
open category_theory.limits
universes v u₁ u₂
namespace abelian_of_adjunction
variables {C : Type u₁} [category.{v} C] [preadditive C]
variables {D : Type u₂} [category.{v} D] [abelian D]
variables (F : C ⥤ D)
variables (G : D ⥤ C) [functor.preserves_zero_morphisms G]
variables (i : F ⋙ G ≅ 𝟭 C) (adj : G ⊣ F)
include i
/-- No point making this an instance, as it requires `i`. -/
lemma has_kernels [preserves_finite_limits G] : has_kernels C :=
{ has_limit := λ X Y f, begin
have := nat_iso.naturality_1 i f,
simp at this,
rw ←this,
haveI : has_kernel (G.map (F.map f) ≫ i.hom.app _) := limits.has_kernel_comp_mono _ _,
apply limits.has_kernel_iso_comp,
end }
include adj
/-- No point making this an instance, as it requires `i` and `adj`. -/
lemma has_cokernels : has_cokernels C :=
{ has_colimit := λ X Y f, begin
haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits,
have := nat_iso.naturality_1 i f,
simp at this,
rw ←this,
haveI : has_cokernel (G.map (F.map f) ≫ i.hom.app _) := limits.has_cokernel_comp_iso _ _,
apply limits.has_cokernel_epi_comp,
end }
variables [limits.has_cokernels C]
/-- Auxiliary construction for `coimage_iso_image` -/
def cokernel_iso {X Y : C} (f : X ⟶ Y) : G.obj (cokernel (F.map f)) ≅ cokernel f :=
begin
-- We have to write an explicit `preserves_colimits` type here,
-- as `left_adjoint_preserves_colimits` has universe variables.
haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits,
calc G.obj (cokernel (F.map f))
≅ cokernel (G.map (F.map f)) : (as_iso (cokernel_comparison _ G)).symm
... ≅ cokernel (_ ≫ f ≫ _) : cokernel_iso_of_eq (nat_iso.naturality_2 i f).symm
... ≅ cokernel (f ≫ _) : cokernel_epi_comp _ _
... ≅ cokernel f : cokernel_comp_is_iso _ _
end
variables [limits.has_kernels C] [preserves_finite_limits G]
/-- Auxiliary construction for `coimage_iso_image` -/
def coimage_iso_image_aux {X Y : C} (f : X ⟶ Y) :
kernel (G.map (cokernel.π (F.map f))) ≅ kernel (cokernel.π f) :=
begin
haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits,
calc kernel (G.map (cokernel.π (F.map f)))
≅ kernel (cokernel.π (G.map (F.map f)) ≫ cokernel_comparison (F.map f) G)
: kernel_iso_of_eq (π_comp_cokernel_comparison _ _).symm
... ≅ kernel (cokernel.π (G.map (F.map f))) : kernel_comp_mono _ _
... ≅ kernel (cokernel.π (_ ≫ f ≫ _) ≫ (cokernel_iso_of_eq _).hom)
: kernel_iso_of_eq (π_comp_cokernel_iso_of_eq_hom (nat_iso.naturality_2 i f)).symm
... ≅ kernel (cokernel.π (_ ≫ f ≫ _)) : kernel_comp_mono _ _
... ≅ kernel (cokernel.π (f ≫ i.inv.app Y) ≫ (cokernel_epi_comp (i.hom.app X) _).inv)
: kernel_iso_of_eq (by simp only [cokernel.π_desc, cokernel_epi_comp_inv])
... ≅ kernel (cokernel.π (f ≫ _)) : kernel_comp_mono _ _
... ≅ kernel (inv (i.inv.app Y) ≫ cokernel.π f ≫ (cokernel_comp_is_iso f (i.inv.app Y)).inv)
: kernel_iso_of_eq (by simp only [cokernel.π_desc, cokernel_comp_is_iso_inv,
iso.hom_inv_id_app_assoc, nat_iso.inv_inv_app])
... ≅ kernel (cokernel.π f ≫ _) : kernel_is_iso_comp _ _
... ≅ kernel (cokernel.π f) : kernel_comp_mono _ _
end
variables [functor.preserves_zero_morphisms F]
/--
Auxiliary definition: the abelian coimage and abelian image agree.
We still need to check that this agrees with the canonical morphism.
-/
def coimage_iso_image {X Y : C} (f : X ⟶ Y) : abelian.coimage f ≅ abelian.image f :=
begin
haveI : preserves_limits F := adj.right_adjoint_preserves_limits,
haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits,
calc abelian.coimage f
≅ cokernel (kernel.ι f) : iso.refl _
... ≅ G.obj (cokernel (F.map (kernel.ι f))) : (cokernel_iso _ _ i adj _).symm
... ≅ G.obj (cokernel (kernel_comparison f F ≫ (kernel.ι (F.map f))))
: G.map_iso (cokernel_iso_of_eq (by simp))
... ≅ G.obj (cokernel (kernel.ι (F.map f))) : G.map_iso (cokernel_epi_comp _ _)
... ≅ G.obj (abelian.coimage (F.map f)) : iso.refl _
... ≅ G.obj (abelian.image (F.map f)) : G.map_iso (abelian.coimage_iso_image _)
... ≅ G.obj (kernel (cokernel.π (F.map f))) : iso.refl _
... ≅ kernel (G.map (cokernel.π (F.map f))) : preserves_kernel.iso _ _
... ≅ kernel (cokernel.π f) : coimage_iso_image_aux F G i adj f
... ≅ abelian.image f : iso.refl _,
end
local attribute [simp] cokernel_iso coimage_iso_image coimage_iso_image_aux
-- The account of this proof in the Stacks project omits this calculation.
-- Happily it's little effort: our `[ext]` and `[simp]` lemmas only need a little guidance.
lemma coimage_iso_image_hom {X Y : C} (f : X ⟶ Y) :
(coimage_iso_image F G i adj f).hom = abelian.coimage_image_comparison f :=
by { ext, simpa [-functor.map_comp, ←G.map_comp_assoc] using nat_iso.naturality_1 i f, }
end abelian_of_adjunction
open abelian_of_adjunction
/--
If `C` is an additive category, `D` is an abelian category,
we have `F : C ⥤ D` `G : D ⥤ C` (both preserving zero morphisms),
`G` is left exact (that is, preserves finite limits),
and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`,
then `C` is also abelian.
See <https://stacks.math.columbia.edu/tag/03A3>
-/
def abelian_of_adjunction
{C : Type u₁} [category.{v} C] [preadditive C] [has_finite_products C]
{D : Type u₂} [category.{v} D] [abelian D]
(F : C ⥤ D) [functor.preserves_zero_morphisms F]
(G : D ⥤ C) [functor.preserves_zero_morphisms G] [preserves_finite_limits G]
(i : F ⋙ G ≅ 𝟭 C) (adj : G ⊣ F) : abelian C :=
begin
haveI := has_kernels F G i, haveI := has_cokernels F G i adj,
haveI : ∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f),
{ intros X Y f, rw ←coimage_iso_image_hom F G i adj f, apply_instance, },
apply abelian.of_coimage_image_comparison_is_iso,
end
/--
If `C` is an additive category equivalent to an abelian category `D`
via a functor that preserves zero morphisms,
then `C` is also abelian.
-/
def abelian_of_equivalence
{C : Type u₁} [category.{v} C] [preadditive C] [has_finite_products C]
{D : Type u₂} [category.{v} D] [abelian D]
(F : C ⥤ D) [functor.preserves_zero_morphisms F] [is_equivalence F] : abelian C :=
abelian_of_adjunction F F.inv F.as_equivalence.unit_iso.symm F.as_equivalence.symm.to_adjunction
end category_theory
|
8d8ce3358bb508819e8bd80f962fc6f20e48ef7e | ebb7367fa8ab324601b5abf705720fd4cc0e8598 | /algebra/subgroup.hlean | 0f64dbfbcdd8f6fed6b9617ccdc5419e6cd08b91 | [
"Apache-2.0"
] | permissive | radams78/Spectral | 3e34916d9bbd0939ee6a629e36744827ff27bfc2 | c8145341046cfa2b4960ef3cc5a1117d12c43f63 | refs/heads/master | 1,610,421,583,830 | 1,481,232,014,000 | 1,481,232,014,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,262 | 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
Basic concepts of group theory
-/
import algebra.group_theory
open eq algebra is_trunc sigma sigma.ops prod trunc
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 --/
/-- Question: Why is this called subgroup_rel. Because it is a unary relation? --/
structure subgroup_rel (G : Group) : Type :=
(R : G → Prop)
(Rone : R one)
(Rmul : Π{g h}, R g → R h → R (g * h))
(Rinv : Π{g}, R g → R (g⁻¹))
attribute subgroup_rel.R [coercion]
/-- Every group G has at least two subgroups, the trivial subgroup containing only one, and the full subgroup. --/
definition trivial_subgroup.{u} (G : Group.{u}) : subgroup_rel.{u u} G :=
begin
fapply subgroup_rel.mk,
{ intro g, fapply trunctype.mk, exact (g = one), exact _ },
{ esimp },
{ intros g h p q, esimp at *, rewrite p, rewrite q, exact mul_one one},
{ intros g p, esimp at *, rewrite p, exact one_inv }
end
definition is_trivial_subgroup (G : Group) (R : subgroup_rel G) : Type :=
(Π g : G, R g → g = 1)
definition full_subgroup.{u} (G : Group.{u}) : subgroup_rel.{u 0} G :=
begin
fapply subgroup_rel.mk,
{ intro g, fapply trunctype.mk, exact unit, exact _}, -- instead of the unit type, we take g = g, because the unit type is in Type₀ and not in Type.{u}
{ esimp, constructor },
{ intros g h p q, esimp, constructor },
{ intros g p, esimp, constructor }
end
definition is_full_subgroup (G : Group) (R : subgroup_rel G) : Prop :=
trunctype.mk' -1 (Π g : G, R g)
/-- 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. --/
/-- TODO. We need to find some reasonable way of dealing with universe levels. The reason why it currently is what it is, is because lean is inflexible with universe leves once tactic mode is started --/
definition image_subgroup.{u1 u2} {G : Group.{u1}} {H : Group.{u2}} (f : G →g H) : subgroup_rel.{u2 (max u1 u2)} H :=
begin
fapply subgroup_rel.mk,
-- definition of the subset
{ intro h, apply ttrunc, exact fiber f h},
-- subset contains 1
{ apply trunc.tr, fapply fiber.mk, exact 1, apply respect_one},
-- subset is closed under multiplication
{ intro h h', intro u v,
induction u with p, induction v with q,
induction p with x p, induction q with y q,
induction p, induction q,
apply tr, apply fiber.mk (x * y), apply respect_mul},
-- subset is closed under inverses
{ intro g, intro t, induction t, induction a with x p, induction p,
apply tr, apply fiber.mk x⁻¹, apply respect_inv }
end
section kernels
variables {G₁ G₂ : Group}
-- TODO: maybe define this in more generality for pointed sets?
definition kernel_pred [constructor] (φ : G₁ →g G₂) (g : G₁) : Prop := trunctype.mk (φ g = 1) _
theorem kernel_mul (φ : G₁ →g G₂) (g h : G₁) (H₁ : kernel_pred φ g) (H₂ : kernel_pred φ h) : kernel_pred φ (g *[G₁] h) :=
begin
esimp at *,
exact calc
φ (g * h) = (φ g) * (φ h) : to_respect_mul
... = 1 * (φ h) : H₁
... = 1 * 1 : H₂
... = 1 : one_mul
end
theorem kernel_inv (φ : G₁ →g G₂) (g : G₁) (H : kernel_pred φ g) : kernel_pred φ (g⁻¹) :=
begin
esimp at *,
exact calc
φ g⁻¹ = (φ g)⁻¹ : to_respect_inv
... = 1⁻¹ : H
... = 1 : one_inv
end
definition kernel_subgroup [constructor] (φ : G₁ →g G₂) : subgroup_rel G₁ :=
⦃ subgroup_rel,
R := kernel_pred φ,
Rone := respect_one φ,
Rmul := kernel_mul φ,
Rinv := kernel_inv φ
⦄
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 [constructor] {G : Group} (R : G → Prop) : Prop :=
trunctype.mk (Π{g} h, R g → R (h * g * h⁻¹)) _
structure normal_subgroup_rel (G : Group) extends subgroup_rel G :=
(is_normal_subgroup : is_normal R)
attribute subgroup_rel.R [coercion]
abbreviation subgroup_to_rel [unfold 2] := @subgroup_rel.R
abbreviation subgroup_has_one [unfold 2] := @subgroup_rel.Rone
abbreviation subgroup_respect_mul [unfold 2] := @subgroup_rel.Rmul
abbreviation subgroup_respect_inv [unfold 2] := @subgroup_rel.Rinv
abbreviation is_normal_subgroup [unfold 2] := @normal_subgroup_rel.is_normal_subgroup
variables {G G' : Group} (H : subgroup_rel G) (N : normal_subgroup_rel G) {g g' h h' k : G}
{A B : AbGroup}
theorem is_normal_subgroup' (h : G) (r : N g) : N (h⁻¹ * g * h) :=
inv_inv h ▸ is_normal_subgroup N h⁻¹ r
definition normal_subgroup_rel_ab.{u} [constructor] (R : subgroup_rel.{_ u} A)
: normal_subgroup_rel.{_ u} A :=
⦃normal_subgroup_rel, R,
is_normal_subgroup := 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 : N (h * g * h⁻¹)) : N g :=
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' N h r
theorem is_normal_subgroup_rev' (h : G) (r : N (h⁻¹ * g * h)) : N g :=
is_normal_subgroup_rev N h⁻¹ ((inv_inv h)⁻¹ ▸ r)
theorem normal_subgroup_insert (r : N k) (r' : N (g * h)) : N (g * (k * h)) :=
have H1 : N ((g * h) * (h⁻¹ * k * h)), from
subgroup_respect_mul N r' (is_normal_subgroup' N 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₁)
: kernel_pred φ g → kernel_pred φ (h * g * h⁻¹) :=
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
/-- Thus, we extend the kernel subgroup to a normal subgroup --/
definition normal_subgroup_kernel [constructor] {G₁ G₂ : Group} (φ : G₁ →g G₂) : normal_subgroup_rel G₁ :=
⦃ normal_subgroup_rel,
kernel_subgroup φ,
is_normal_subgroup := is_normal_subgroup_kernel φ
⦄
-- this is just (Σ(g : G), H g), but only defined if (H g) is a prop
definition sg : Type := {g : G | H g}
local attribute sg [reducible]
variable {H}
definition subgroup_one [constructor] : sg H := ⟨one, !subgroup_has_one⟩
definition subgroup_inv [unfold 3] : sg H → sg H :=
λv, ⟨v.1⁻¹, subgroup_respect_inv H v.2⟩
definition subgroup_mul [unfold 3 4] : sg H → sg H → sg H :=
λv w, ⟨v.1 * w.1, subgroup_respect_mul H v.2 w.2⟩
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 : subgroup_rel G} (g h : sg H)
: g * h = 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)
definition ab_group_sg [constructor] {G : AbGroup} (H : subgroup_rel G)
: ab_group (sg H) :=
⦃ab_group, group_sg H, mul_comm := subgroup_mul_comm⦄
definition ab_subgroup [constructor] {G : AbGroup} (H : subgroup_rel G)
: AbGroup :=
AbGroup.mk _ (ab_group_sg H)
definition kernel {G H : Group} (f : G →g H) : Group := subgroup (kernel_subgroup f)
definition ab_kernel {G H : AbGroup} (f : G →g H) : AbGroup := ab_subgroup (kernel_subgroup f)
definition incl_of_subgroup [constructor] {G : Group} (H : subgroup_rel G) : 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 subgroup_rel_of_subgroup {G : Group} (H1 H2 : subgroup_rel G) (hyp : Π (g : G), subgroup_rel.R H1 g → subgroup_rel.R H2 g) : subgroup_rel (subgroup H2) :=
subgroup_rel.mk
-- definition of the subset
(λ h, H1 (incl_of_subgroup H2 h))
-- contains 1
(subgroup_has_one H1)
-- closed under multiplication
(λ g h p q, subgroup_respect_mul H1 p q)
-- closed under inverses
(λ h p, subgroup_respect_inv H1 p)
definition image {G H : Group} (f : G →g H) : Group :=
subgroup (image_subgroup f)
definition AbGroup_of_Group.{u} (G : Group.{u}) (H : Π (g h : G), mul g h = mul h g) : AbGroup.{u} :=
begin
induction G,
induction struct,
fapply AbGroup.mk,
exact carrier,
fapply ab_group.mk,
repeat assumption,
exact H
end
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 p, induction s with q, induction p with g p, induction q 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_subgroup f)
definition comm_image_incl {A B : AbGroup} (f : A →g B) : ab_image f →g B := incl_of_subgroup (image_subgroup f)
definition hom_lift {G H : Group} (f : G →g H) (K : subgroup_rel H) (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 image_lift {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 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 x, induction x with g p,
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
end group
|
023b02185f4b2b953fab05bea487505633243c5f | c46a31beec236d29b6c02e7d7683691bcfbb3014 | /src/quiz05.lean | ebad2064d0009513a1ae800d0265953f11584c88 | [] | no_license | UVM-M52/quiz-5-maddiestrauss | a88b9bfbdd486a521ee280f9b7b551bcb48f23c6 | 214529615e08bbcdd3d6600c89432ec985e6ba3a | refs/heads/master | 1,617,897,187,103 | 1,584,922,038,000 | 1,584,922,038,000 | 248,787,429 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 690 | lean | -- Math 52: Quiz 5
-- Open this file in a folder that contains 'utils'.
import utils
open classical
definition divides (a b : ℤ) : Prop := ∃ (k : ℤ), b = a * k
local infix ∣ := divides
axiom not_3_divides : ∀ (m : ℤ), ¬ (3 ∣ m) ↔ 3 ∣ m - 1 ∨ 3 ∣ m + 1
lemma not_3_divides_of_3_divides_minus_1 :
∀ (m : ℤ), 3 ∣ m - 1 → ¬ (3 ∣ m) :=
begin
intros m H,
rw not_3_divides,
left,
assumption,
end
lemma not_3_divides_of_3_divides_plus_1 :
∀ (m : ℤ), 3 ∣ m + 1 → ¬ (3 ∣ m) :=
begin
intros m H,
rw not_3_divides,
right,
assumption,
end
theorem main : ∀ (n : ℤ), 3 ∣ n * n - 1 → ¬ (3 ∣ n) :=
begin
intro n,
by_contrapositive,
end
|
2f94ed2c2e131e353617bad4876fb64f86611efe | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /stage0/src/Lean/Elab/Tactic/Match.lean | a8bc42d33c3d83c12f0e8ff80215fc05c56a1d35 | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 2,781 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Parser.Term
import Lean.Elab.Match
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Induction
namespace Lean.Elab.Tactic
open Meta
/- Erase auxiliary `_discr` variables introduced by `match`-expression elaborator -/
@[builtinTactic Lean.Parser.Tactic.eraseAuxDiscrs]
def evalEraseAuxDiscrs : Tactic := fun _ => do
withMainContext do
let lctx ← getLCtx
let auxDecls := lctx.foldl (init := []) fun auxDecls localDecl =>
if Term.isAuxDiscrName localDecl.userName then
localDecl.fvarId :: auxDecls
else
auxDecls
let mut mvarId ← getMainGoal
for auxDecl in auxDecls do
mvarId ← tryClear mvarId auxDecl
replaceMainGoal [mvarId]
structure AuxMatchTermState where
nextIdx : Nat := 1
«cases» : Array Syntax := #[]
private def mkAuxiliaryMatchTermAux (parentTag : Name) (matchTac : Syntax) : StateT AuxMatchTermState MacroM Syntax := do
let matchAlts := matchTac[4]
let alts := matchAlts[0].getArgs
let newAlts ← alts.mapM fun alt => do
let alt := alt.setKind ``Parser.Term.matchAlt
let holeOrTacticSeq := alt[3]
if holeOrTacticSeq.isOfKind ``Parser.Term.syntheticHole then
pure alt
else if holeOrTacticSeq.isOfKind ``Parser.Term.hole then
let s ← get
let tag := if alts.size > 1 then parentTag ++ (`match).appendIndexAfter s.nextIdx else parentTag
let holeName := mkIdentFrom holeOrTacticSeq tag
let newHole ← `(?$holeName:ident)
modify fun s => { s with nextIdx := s.nextIdx + 1}
pure <| alt.setArg 3 newHole
else withFreshMacroScope do
let newHole ← `(?rhs)
let newHoleId := newHole[1]
let newCase ← `(tactic| case $newHoleId =>%$(alt[2]) eraseAuxDiscrs!; ($holeOrTacticSeq:tacticSeq) )
modify fun s => { s with cases := s.cases.push newCase }
pure <| alt.setArg 3 newHole
let result := matchTac.setKind ``Parser.Term.«match»
let result := result.setArg 4 (mkNode ``Parser.Term.matchAlts #[mkNullNode newAlts])
pure result
private def mkAuxiliaryMatchTerm (parentTag : Name) (matchTac : Syntax) : MacroM (Syntax × Array Syntax) := do
let (matchTerm, s) ← mkAuxiliaryMatchTermAux parentTag matchTac |>.run {}
pure (matchTerm, s.cases)
@[builtinTactic Lean.Parser.Tactic.match]
def evalMatch : Tactic := fun stx => do
let tag ← getMainTag
let (matchTerm, cases) ← liftMacroM <| mkAuxiliaryMatchTerm tag stx
let refineMatchTerm ← `(tactic| refine $matchTerm)
let stxNew := mkNullNode (#[refineMatchTerm] ++ cases)
withMacroExpansion stx stxNew <| evalTactic stxNew
end Lean.Elab.Tactic
|
91499248892f9a4940e53d579bcb7b825d05b7c0 | 1d265c7dd8cb3d0e1d645a19fd6157a2084c3921 | /src/lessons/hello.lean | 0220c38b676a8266515a894fde22754df0169259 | [
"MIT"
] | permissive | hanzhi713/lean-proofs | de432372f220d302be09b5ca4227f8986567e4fd | 4d8356a878645b9ba7cb036f87737f3f1e68ede5 | refs/heads/master | 1,585,580,245,658 | 1,553,646,623,000 | 1,553,646,623,000 | 151,342,188 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 810 | lean | /-theorem interesting: 1 = 1 := rfl. -/
#check ¬ (1 = 0)
#check ∀ T: Type, ∀ t: T, t = t
lemma zeqz: 0 = 0 := rfl
lemma oeqo: 1 = 1 := rfl
theorem helloTheorem: "hello" = "hello" := rfl
theorem twooneone: 2 = 1 + 1 := rfl
theorem tthof: 2 + 3 = 1 + 4 := rfl
theorem holeqhl: "Hello " ++ "Logic!" = "Hello Logic!" := rfl
theorem zeqz_and_oeqo: 0 = 0 ∧ 1 = 1 := and.intro zeqz oeqo
theorem haha: 0 = 0 ∧ 1 = 1 := and.intro rfl rfl
theorem negation: tt = ¬ ff := rfl
variable a: bool
#check ¬ (a = ¬ a)
lemma ft: 5 = 1 + 4 := rfl
lemma st: "S" ++ "trike" = "Strike" := rfl
theorem ftst: 5 = 1 + 4 ∧ "S" ++ "trike" = "Strike" := and.intro ft st
#check rfl
constant T: Type
variable t: T
#check "Heoo"
theorem eee: t = t := rfl
#check (eq.refl tt)
#check (eq.refl "Hello")
constant a: Prop |
fe84228d837bc05acb9d02a4bd54ed253365ff90 | 398b53a5e02ce35196531591f84bb2f6b034ce5a | /tpil/chapter7.lean | c5369ebdb5f27884ff74e96d17ef350556150f41 | [
"MIT"
] | permissive | crockeo/math-exercises | 64f07a9371a72895bbd97f49a854dcb6821b18ab | cf9150ef9e025f1b7929ba070a783e7a71f24f31 | refs/heads/master | 1,607,910,221,030 | 1,581,231,762,000 | 1,581,231,762,000 | 234,595,189 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,726 | lean | ------------------
-- Random Notes --
--
-- 7.1. Enumerated Types
--
namespace s71
inductive weekday : Type
| sunday : weekday
| monday : weekday
| tuesday : weekday
| wednesday : weekday
| thursday : weekday
| friday : weekday
| saturday : weekday
namespace weekday
def next (d : weekday) : weekday :=
weekday.cases_on d
monday
tuesday
wednesday
thursday
friday
saturday
sunday
def previous (d : weekday) : weekday :=
weekday.cases_on d
saturday
sunday
monday
tuesday
wednesday
thursday
friday
theorem next_previous (d : weekday) : next (previous d) = d :=
begin
apply weekday.cases_on d;
refl,
end
theorem previous_next (d : weekday) : previous (next d) = d :=
begin
apply weekday.cases_on d;
refl,
end
end weekday
end s71
--
-- 7.2. Constructors with Arguments
--
namespace s72
universes u v
inductive prod (α : Type u) (β : Type v)
| mk : α → β → prod
namespace prod
def fst {α : Type u} {β : Type v} (p : prod α β) : α :=
prod.rec_on p (λa b, a)
def snd {α : Type u} {β : Type v} (p : prod α β) : β :=
prod.rec_on p (λa b, b)
section
variables (α : Type u) (β : Type v) (p : prod α β)
variables (a : α) (b : β)
#reduce mk a b
#reduce fst (mk a b)
#reduce snd (mk a b)
end
end prod
-- Defining the necessary conditions for a group as a structure.
--
-- Now how would one actually use this definition?
universe t
structure Group :=
(carrier : Type t)
(ident : carrier)
(inverse : carrier → carrier)
(mul : carrier → carrier → carrier)
(ident_mul_eq : ∀ a : carrier, mul ident a = a)
(mul_ident_eq : ∀ a : carrier, mul a ident = a)
(inverse_mul_eq_ident : ∀ a : carrier, mul (inverse a) a = ident)
(mul_inverse_eq_ident : ∀ a : carrier, mul a (inverse a) = ident)
(mul_assoc : ∀ a b c : carrier, mul (mul a b) c = mul a (mul b c))
end s72
---------------
-- Exercises --
-- Exercise 1
--
-- Try defining other operations on the natural numbers, such as multiplication,
-- the predecessor function (with pred 0 = 0), truncated subtraction (with
-- n - m = 0 when m is greater than or equal to n), and exponentiation. Then try
-- proving some of their basic properties, building on the theorems we have
-- already proved.
--
-- Since many of these are already defined in Lean’s core library, you should
-- work within a namespace named hide, or something like that, in order to avoid
-- name clashes.
namespace hidden
variables (x y : ℕ)
-- Defining our operations
def add (x y : ℕ) : ℕ :=
nat.rec_on
x
y
(λ _ add_x_y, nat.succ add_x_y)
def mul (x y : ℕ) : ℕ :=
nat.rec_on
x
0
(λ _ mul_x_y, add mul_x_y y)
def pred (n : ℕ) : ℕ :=
nat.rec_on
n
0
(λ n pred_n, n)
def sub (x y : ℕ) : ℕ :=
nat.rec_on
y
x
(λ n sub_x_y, pred sub_x_y)
-- TODO: Define infix operators
-- Defining some theorems. Skipping most of them because I did them in NN Game
theorem add_sub_inverse : ∀ (x y : ℕ), x + y - y = x :=
begin
intros x y,
induction y with d hd,
{
rw add_zero,
-- rw sub_zero,
sorry,
},
{
sorry,
},
end
end hidden
-- TODO
-- Exericse 2
--
-- Define some operations on lists, like a length function or the reverse
-- function. Prove some properties, such as the following:
--
-- length (s ++ t) = length s + length t
--
-- length (reverse t) = length t
--
-- reverse (reverse t) = t
-- TODO
-- Exericse 3
--
-- Define an inductive data type consisting of terms built up from the following
-- constructors:
--
-- const n, a constant denoting the natural number n
--
-- var n, a variable, numbered n
--
-- plus s t, denoting the sum of s and t
--
-- times s t, denoting the product of s and t
--
-- Recursively define a function that evaluates any such term with respect to an
-- assignment of values to the variables.
-- Exercise 4
--
-- Similarly, define the type of propositional formulas, as well as functions on
-- the type of such formulas: an evaluation function, functions that measure the
-- complexity of a formula, and a function that substitutes another formula for
-- a given variable.
-- TODO
-- Exercise 5
--
-- Simulate the mutual inductive definition of even and odd described in Section 7.9 with an ordinary inductive type, using an index to encode the choice between them in the target type.
-- TODO
|
74c6570f22e36671a591e216724484b8524314ef | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Elab/LetRec.lean | c4f79476de35a8bc477f9687410288471ec78dbc | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,035 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Attributes
import Lean.Elab.Binders
import Lean.Elab.DeclModifiers
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclarationRange
namespace Lean.Elab.Term
open Meta
structure LetRecDeclView where
ref : Syntax
attrs : Array Attribute
shortDeclName : Name
declName : Name
numParams : Nat
type : Expr
mvar : Expr -- auxiliary metavariable used to lift the 'let rec'
valStx : Syntax
structure LetRecView where
decls : Array LetRecDeclView
body : Syntax
/- group ("let " >> nonReservedSymbol "rec ") >> sepBy1 (group (optional «attributes» >> letDecl)) ", " >> "; " >> termParser -/
private def mkLetRecDeclView (letRec : Syntax) : TermElabM LetRecView := do
let decls ← letRec[1][0].getSepArgs.mapM fun (attrDeclStx : Syntax) => do
let docStr? ← expandOptDocComment? attrDeclStx[0]
let attrOptStx := attrDeclStx[1]
let attrs ← if attrOptStx.isNone then pure #[] else elabDeclAttrs attrOptStx[0]
let decl := attrDeclStx[2][0]
if decl.isOfKind `Lean.Parser.Term.letPatDecl then
throwErrorAt decl "patterns are not allowed in 'let rec' expressions"
else if decl.isOfKind `Lean.Parser.Term.letIdDecl || decl.isOfKind `Lean.Parser.Term.letEqnsDecl then
let declId := decl[0]
let shortDeclName := declId.getId
let currDeclName? ← getDeclName?
let declName := currDeclName?.getD Name.anonymous ++ shortDeclName
checkNotAlreadyDeclared declName
applyAttributesAt declName attrs AttributeApplicationTime.beforeElaboration
addDocString' declName docStr?
addAuxDeclarationRanges declName decl declId
let binders := decl[1].getArgs
let typeStx := expandOptType declId decl[2]
let (type, numParams) ← elabBinders binders fun xs => do
let type ← elabType typeStx
registerCustomErrorIfMVar type typeStx "failed to infer 'let rec' declaration type"
let type ← mkForallFVars xs type
pure (type, xs.size)
let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque
let valStx ←
if decl.isOfKind `Lean.Parser.Term.letIdDecl then
pure decl[4]
else
liftMacroM $ expandMatchAltsIntoMatch decl decl[3]
pure {
ref := decl,
attrs := attrs,
shortDeclName := shortDeclName,
declName := declName,
numParams := numParams,
type := type,
mvar := mvar,
valStx := valStx
: LetRecDeclView }
else
throwUnsupportedSyntax
pure {
decls := decls,
body := letRec[3]
}
private partial def withAuxLocalDecls {α} (views : Array LetRecDeclView) (k : Array Expr → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α :=
if h : i < views.size then
let view := views.get ⟨i, h⟩
withLocalDeclD view.shortDeclName view.type fun fvar => loop (i+1) (fvars.push fvar)
else
k fvars
loop 0 #[]
private def elabLetRecDeclValues (view : LetRecView) : TermElabM (Array Expr) :=
view.decls.mapM fun view => do
forallBoundedTelescope view.type view.numParams fun xs type =>
withDeclName view.declName do
let value ← elabTermEnsuringType view.valStx type
mkLambdaFVars xs value
private def registerLetRecsToLift (views : Array LetRecDeclView) (fvars : Array Expr) (values : Array Expr) : TermElabM Unit := do
let letRecsToLiftCurr := (← get).letRecsToLift
for view in views do
if letRecsToLiftCurr.any fun toLift => toLift.declName == view.declName then
withRef view.ref do
throwError "'{view.declName}' has already been declared"
let lctx ← getLCtx
let localInsts ← getLocalInstances
let toLift := views.mapIdx fun i view => {
ref := view.ref,
fvarId := fvars[i].fvarId!,
attrs := view.attrs,
shortDeclName := view.shortDeclName,
declName := view.declName,
lctx := lctx,
localInstances := localInsts,
type := view.type,
val := values[i],
mvarId := view.mvar.mvarId!
: LetRecToLift }
modify fun s => { s with letRecsToLift := toLift.toList ++ s.letRecsToLift }
@[builtinTermElab «letrec»] def elabLetRec : TermElab := fun stx expectedType? => do
let view ← mkLetRecDeclView stx
withAuxLocalDecls view.decls fun fvars => do
for decl in view.decls, fvar in fvars do
addTermInfo (isBinder := true) decl.ref[0] fvar
let values ← elabLetRecDeclValues view
let body ← elabTermEnsuringType view.body expectedType?
registerLetRecsToLift view.decls fvars values
let mvars := view.decls.map (·.mvar)
pure $ mkAppN (← mkLambdaFVars fvars body) mvars
end Lean.Elab.Term
|
f467d4315b75b5df4d981900e73401961242e342 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/data/padics/padic_norm.lean | 41412020e459afb2ad38bd4b611581952989bbc1 | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 13,302 | 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
Define the p-adic valuation on ℤ and ℚ, and the p-adic norm on ℚ
-/
import data.rat.basic algebra.gcd_domain algebra.field_power
import ring_theory.multiplicity tactic.ring
import data.real.cau_seq
import tactic.norm_cast
universe u
open nat
attribute [class] nat.prime
local infix `/.`:70 := rat.mk
open multiplicity
def padic_val_rat (p : ℕ) (q : ℚ) : ℤ :=
if h : q ≠ 0 ∧ p ≠ 1
then (multiplicity (p : ℤ) q.num).get
(multiplicity.finite_int_iff.2 ⟨h.2, rat.num_ne_zero_of_ne_zero h.1⟩) -
(multiplicity (p : ℤ) q.denom).get
(multiplicity.finite_int_iff.2 ⟨h.2, by exact_mod_cast rat.denom_ne_zero _⟩)
else 0
lemma padic_val_rat_def (p : ℕ) [hp : p.prime] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q =
(multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp.ne_one, rat.num_ne_zero_of_ne_zero hq⟩) -
(multiplicity (p : ℤ) q.denom).get (finite_int_iff.2 ⟨hp.ne_one, by exact_mod_cast rat.denom_ne_zero _⟩) :=
dif_pos ⟨hq, hp.ne_one⟩
namespace padic_val_rat
open multiplicity
section padic_val_rat
variables {p : ℕ}
@[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q :=
begin
unfold padic_val_rat,
split_ifs,
{ simp [-add_comm]; refl },
{ exfalso, simp * at * },
{ exfalso, simp * at * },
{ refl }
end
@[simp] protected lemma one : padic_val_rat p 1 = 0 :=
by unfold padic_val_rat; split_ifs; simp *
@[simp] lemma padic_val_rat_self (hp : 1 < p) : padic_val_rat p p = 1 :=
by unfold padic_val_rat; split_ifs; simp [*, nat.one_lt_iff_ne_zero_and_ne_one] at *
lemma padic_val_rat_of_int (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) :
padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get
(finite_int_iff.2 ⟨hp, hz⟩) :=
by rw [padic_val_rat, dif_pos]; simp *; refl
end padic_val_rat
section padic_val_rat
open multiplicity
variables (p : ℕ) [p_prime : nat.prime p]
include p_prime
lemma finite_int_prime_iff {p : ℕ} [p_prime : p.prime] {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 :=
by simp [finite_int_iff, ne.symm (ne_of_lt (p_prime.gt_one))]
protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) :
padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2
⟨ne.symm $ ne_of_lt p_prime.gt_one, λ hn, by simp * at *⟩) -
(multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.gt_one,
λ hd, by simp * at *⟩) :=
have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf,
have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf,
let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hn hd qdf in
by rw [padic_val_rat, dif_pos];
simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime),
(ne.symm (ne_of_lt p_prime.gt_one)), hqz]
protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r :=
have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by rw_mod_cast rat.mul_num_denom,
have hq' : q.num /. q.denom ≠ 0, by rw ← rat.num_denom q; exact hq,
have hr' : r.num /. r.denom ≠ 0, by rw ← rat.num_denom r; exact hr,
have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 p_prime,
begin
rw [padic_val_rat.defn p (mul_ne_zero hq hr) this],
conv_rhs { rw [rat.num_denom q, padic_val_rat.defn p hq',
rat.num_denom r, padic_val_rat.defn p hr'] },
rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp
end
protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} :
padic_val_rat p (q ^ k) = k * padic_val_rat p q :=
by induction k; simp [*, padic_val_rat.mul _ hq (pow_ne_zero _ hq),
_root_.pow_succ, add_mul]
protected lemma inv {q : ℚ} (hq : q ≠ 0) :
padic_val_rat p (q⁻¹) = -padic_val_rat p q :=
by rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul p (inv_ne_zero hq) hq,
inv_mul_cancel hq, padic_val_rat.one]
protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r :=
by rw [div_eq_mul_inv, padic_val_rat.mul p hq (inv_ne_zero hr),
padic_val_rat.inv p hr, sub_eq_add_neg]
lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ}
(hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) :
padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔
∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ :=
have hf1 : finite (p : ℤ) (n₁ * d₂),
from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂),
have hf2 : finite (p : ℤ) (n₂ * d₁),
from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁),
by conv {
to_lhs,
rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl,
padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl,
sub_le_iff_le_add',
← add_sub_assoc,
le_sub_iff_add_le],
norm_cast,
rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf1, add_comm,
← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf2,
enat.get_le_get, multiplicity_le_multiplicity_iff]
}
theorem le_padic_val_rat_add_of_le {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0)
(h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_val_rat p q ≤ padic_val_rat p (q + r) :=
have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq,
have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr,
have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hqdv : q.num /. q.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hqn hqd,
have hrdv : r.num /. r.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hrn hrd,
have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)),
from rat.add_num_denom _ _,
have hqrd : q.num * ↑(r.denom) + ↑(q.denom) * r.num ≠ 0,
from rat.mk_num_ne_zero_of_ne_zero hqr hqreq,
begin
conv_lhs { rw rat.num_denom q },
rw [hqreq, padic_val_rat_le_padic_val_rat_iff p hqn hqrd hqd (mul_ne_zero hqd hrd),
← multiplicity_le_multiplicity_iff, mul_left_comm,
multiplicity.mul (nat.prime_iff_prime_int.1 p_prime), add_mul],
rw [rat.num_denom q, rat.num_denom r, padic_val_rat_le_padic_val_rat_iff p hqn hrn hqd hrd,
← multiplicity_le_multiplicity_iff] at h,
calc _ ≤ min (multiplicity ↑p (q.num * ↑(r.denom) * ↑(q.denom)))
(multiplicity ↑p (↑(q.denom) * r.num * ↑(q.denom))) : (le_min
(by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 p_prime), add_comm])
(by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ)
(_ * _) (nat.prime_iff_prime_int.1 p_prime)];
exact add_le_add_left' h))
... ≤ _ : min_le_multiplicity_add
end
theorem min_le_padic_val_rat_add {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) :
min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) :=
(le_total (padic_val_rat p q) (padic_val_rat p r)).elim
(λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le _ hq hr hqr h)
(λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le _ hr hq
(by rwa add_comm) h)
end padic_val_rat
end padic_val_rat
def padic_norm (p : ℕ) (q : ℚ) : ℚ :=
if q = 0 then 0 else (↑p : ℚ) ^ (-(padic_val_rat p q))
namespace padic_norm
section padic_norm
open padic_val_rat
variables (p : ℕ) [hp : p.prime]
include hp
@[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm]
@[simp] protected lemma one : padic_norm p 1 = 1 := by simp [padic_norm]
@[simp] protected lemma eq_fpow_of_nonzero {q : ℚ} (hq : q ≠ 0) :
padic_norm p q = p ^ (-(padic_val_rat p q)) :=
by simp [hq, padic_norm]
protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 :=
begin
rw padic_norm.eq_fpow_of_nonzero p hq,
apply fpow_ne_zero_of_ne_zero,
exact_mod_cast ne_of_gt hp.pos
end
@[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q :=
if hq : q = 0 then by simp [hq]
else by simp [padic_norm, hq, hp.gt_one]
lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 :=
begin
apply by_contradiction, intro hq,
unfold padic_norm at h, rw if_neg hq at h,
apply absurd h,
apply fpow_ne_zero_of_ne_zero,
exact_mod_cast hp.ne_zero
end
protected lemma nonneg (q : ℚ) : padic_norm p q ≥ 0 :=
if hq : q = 0 then by simp [hq]
else
begin
unfold padic_norm; split_ifs,
apply fpow_nonneg_of_nonneg,
exact_mod_cast nat.zero_le _
end
@[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r :=
if hq : q = 0 then
by simp [hq]
else if hr : r = 0 then
by simp [hr]
else
have q*r ≠ 0, from mul_ne_zero hq hr,
have (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp],
by simp [padic_norm, *, padic_val_rat.mul, fpow_add this]
@[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r :=
if hr : r = 0 then by simp [hr] else
eq_div_of_mul_eq _ _ (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr])
protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 :=
if hz : z = 0 then by simp [hz] else
begin
unfold padic_norm,
rw [if_neg _],
{ refine fpow_le_one_of_nonpos _ _,
{ exact_mod_cast le_of_lt hp.gt_one, },
{ rw [padic_val_rat_of_int _ hp.ne_one hz, neg_nonpos],
norm_cast, simp }},
exact_mod_cast hz
end
--TODO: p implicit
private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _,
have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _,
if hq : q = 0 then
by simp [hq, max_eq_right hnrp, le_max_right]
else if hr : r = 0 then
by simp [hr, max_eq_left hnqp, le_max_left]
else if hqr : q + r = 0 then
le_trans (by simpa [hqr] using hnqp) (le_max_left _ _)
else
begin
unfold padic_norm, split_ifs,
apply le_max_iff.2,
left,
apply fpow_le_of_le,
{ exact_mod_cast le_of_lt hp.gt_one },
{ apply neg_le_neg,
have : padic_val_rat p q =
min (padic_val_rat p q) (padic_val_rat p r),
from (min_eq_left h).symm,
rw this,
apply min_le_padic_val_rat_add; assumption }
end
protected theorem nonarchimedean {q r : ℚ} :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r],
exact nonarchimedean_aux p hle
end
theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r :=
calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p
... ≤ padic_norm p q + padic_norm p r :
max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _)
protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) :=
by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean
lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) :
padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r],
have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm,
have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc
padic_norm p q = padic_norm p (q + r - r) : by congr; ring
... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p
... = max (padic_norm p (q + r)) (padic_norm p r) : by simp,
have hnge : padic_norm p r ≤ padic_norm p (q + r),
{ apply le_of_not_gt,
intro hgt,
rw max_eq_right_of_lt hgt at this,
apply not_lt_of_ge this,
assumption },
have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this,
apply _root_.le_antisymm,
{ apply padic_norm.nonarchimedean p },
{ rw max_eq_left_of_lt hlt,
assumption }
end
protected theorem image {q : ℚ} (hq : q ≠ 0) : ∃ n : ℤ, padic_norm p q = p ^ (-n) :=
⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩
instance : is_absolute_value (padic_norm p) :=
{ abv_nonneg := padic_norm.nonneg p,
abv_eq_zero :=
begin
intros,
constructor; intro,
{ apply zero_of_padic_norm_eq_zero p, assumption },
{ simp [*] }
end,
abv_add := padic_norm.triangle_ineq p,
abv_mul := padic_norm.mul p }
lemma le_of_dvd {n : ℕ} {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ ↑p ^ (-n : ℤ) :=
begin
unfold padic_norm, split_ifs with hz hz,
{ apply fpow_nonneg_of_nonneg,
exact_mod_cast le_of_lt hp.pos },
{ apply fpow_le_of_le,
exact_mod_cast le_of_lt hp.gt_one,
apply neg_le_neg,
rw padic_val_rat_of_int _ hp.ne_one _,
{ norm_cast,
rw [← enat.coe_le_coe, enat.coe_get],
apply multiplicity.le_multiplicity_of_pow_dvd,
exact_mod_cast hd },
{ exact_mod_cast hz }}
end
end padic_norm
end padic_norm
|
37a6de63f334c4c00210ff2b71ef563d13456bad | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/big_operators/multiset/lemmas.lean | dadbcc8381e52f263406dc5ad28551b0e01dc46a | [
"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,427 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Bhavik Mehta, Eric Wieser
-/
import data.list.big_operators.lemmas
import algebra.big_operators.multiset.basic
/-! # Lemmas about `multiset.sum` and `multiset.prod` requiring extra algebra imports
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
variables {ι α β γ : Type*}
namespace multiset
lemma dvd_prod [comm_monoid α] {s : multiset α} {a : α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
@[to_additive]
lemma prod_eq_one_iff [canonically_ordered_monoid α] {m : multiset α} :
m.prod = 1 ↔ ∀ x ∈ m, x = (1 : α) :=
quotient.induction_on m $ λ l, by simpa using list.prod_eq_one_iff l
end multiset
open multiset
namespace commute
variables [non_unital_non_assoc_semiring α] {a : α} {s : multiset ι} {f : ι → α}
lemma multiset_sum_right (s : multiset α) (a : α) (h : ∀ b ∈ s, commute a b) :
commute a s.sum :=
begin
induction s using quotient.induction_on,
rw [quot_mk_to_coe, coe_sum],
exact commute.list_sum_right _ _ h,
end
lemma multiset_sum_left (s : multiset α) (b : α) (h : ∀ a ∈ s, commute a b) :
commute s.sum b :=
(commute.multiset_sum_right _ _ $ λ a ha, (h _ ha).symm).symm
end commute
|
4157b974268ac1f222b2c6934f5a78624202b2b3 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/number_theory/legendre_symbol/mul_character.lean | 820fc0682d8136fa9c1809b789c47e416f64aa67 | [
"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 | 16,071 | lean | /-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import ring_theory.integral_domain
/-!
# Multiplicative characters of finite rings and fields
Let `R` and `R'` be a commutative rings.
A *multiplicative character* of `R` with values in `R'` is a morphism of
monoids from the multiplicative monoid of `R` into that of `R'`
that sends non-units to zero.
We use the namespace `mul_char` for the definitions and results.
## Tags
multiplicative character
-/
section definition_and_group
/-!
### Definitions related to multiplicative characters
Even though the intended use is when domain and target of the characters
are commutative rings, we define them in the more general setting when
the domain is a commutative monoid and the target is a commutative monoid
with zero. (We need a zero in the target, since non-units are supposed
to map to zero.)
In this setting, there is an equivalence between multiplicative characters
`R → R'` and group homomorphisms `Rˣ → R'ˣ`, and the multiplicative characters
have a natural structure as a commutative group.
-/
universes u v
section defi
-- The domain of our multiplicative characters
variables (R : Type u) [comm_monoid R]
-- The target
variables (R' : Type v) [comm_monoid_with_zero R']
/-- Define a structure for multiplicative characters.
A multiplicative character from a commutative monoid `R` to a commutative monoid with zero `R'`
is a homomorphism of (multiplicative) monoids that sends non-units to zero. -/
structure mul_char extends monoid_hom R R' :=
(map_nonunit' : ∀ a : R, ¬ is_unit a → to_fun a = 0)
/-- This is the corresponding extension of `monoid_hom_class`. -/
class mul_char_class (F : Type*) (R R' : out_param $ Type*) [comm_monoid R]
[comm_monoid_with_zero R']
extends monoid_hom_class F R R' :=
(map_nonunit : ∀ (χ : F) {a : R} (ha : ¬ is_unit a), χ a = 0)
attribute [simp] mul_char_class.map_nonunit
end defi
section group
namespace mul_char
-- The domain of our multiplicative characters
variables {R : Type u} [comm_monoid R]
-- The target
variables {R' : Type v} [comm_monoid_with_zero R']
instance coe_to_fun : has_coe_to_fun (mul_char R R') (λ _, R → R') :=
⟨λ χ, χ.to_fun⟩
/-- See note [custom simps projection] -/
protected def simps.apply (χ : mul_char R R') : R → R' := χ
initialize_simps_projections mul_char (to_monoid_hom_to_fun → apply, -to_monoid_hom)
section trivial
variables (R R')
/-- The trivial multiplicative character. It takes the value `0` on non-units and
the value `1` on units. -/
@[simps]
noncomputable
def trivial : mul_char R R' :=
{ to_fun := by { classical, exact λ x, if is_unit x then 1 else 0 },
map_nonunit' := by { intros a ha, simp only [ha, if_false], },
map_one' := by simp only [is_unit_one, if_true],
map_mul' := by { intros x y,
simp only [is_unit.mul_iff, boole_mul],
split_ifs; tauto, } }
end trivial
@[simp]
lemma coe_coe (χ : mul_char R R') : (χ.to_monoid_hom : R → R') = χ := rfl
@[simp]
lemma to_fun_eq_coe (χ : mul_char R R') : χ.to_fun = χ := rfl
@[simp]
lemma coe_mk (f : R →* R') (hf) : (mul_char.mk f hf : R → R') = f := rfl
/-- Extensionality. See `ext` below for the version that will actually be used. -/
lemma ext' {χ χ' : mul_char R R'} (h : ∀ a, χ a = χ' a) : χ = χ' :=
begin
cases χ,
cases χ',
congr,
exact monoid_hom.ext h,
end
instance : mul_char_class (mul_char R R') R R' :=
{ coe := λ χ, χ.to_monoid_hom.to_fun,
coe_injective' := λ f g h, ext' (λ a, congr_fun h a),
map_mul := λ χ, χ.map_mul',
map_one := λ χ, χ.map_one',
map_nonunit := λ χ, χ.map_nonunit', }
lemma map_nonunit (χ : mul_char R R') {a : R} (ha : ¬ is_unit a) : χ a = 0 :=
χ.map_nonunit' a ha
/-- Extensionality. Since `mul_char`s always take the value zero on non-units, it is sufficient
to compare the values on units. -/
@[ext]
lemma ext {χ χ' : mul_char R R'} (h : ∀ a : Rˣ, χ a = χ' a) : χ = χ' :=
begin
apply ext',
intro a,
by_cases ha : is_unit a,
{ exact h ha.unit, },
{ rw [map_nonunit χ ha, map_nonunit χ' ha], },
end
lemma ext_iff {χ χ' : mul_char R R'} : χ = χ' ↔ ∀ a : Rˣ, χ a = χ' a :=
⟨by { rintro rfl a, refl }, ext⟩
/-!
### Equivalence of multiplicative characters with homomorphisms on units
We show that restriction / extension by zero gives an equivalence
between `mul_char R R'` and `Rˣ →* R'ˣ`.
-/
/-- Turn a `mul_char` into a homomorphism between the unit groups. -/
def to_unit_hom (χ : mul_char R R') : Rˣ →* R'ˣ := units.map χ
lemma coe_to_unit_hom (χ : mul_char R R') (a : Rˣ) :
↑(χ.to_unit_hom a) = χ a :=
rfl
/-- Turn a homomorphism between unit groups into a `mul_char`. -/
noncomputable
def of_unit_hom (f : Rˣ →* R'ˣ) : mul_char R R' :=
{ to_fun := by { classical, exact λ x, if hx : is_unit x then f hx.unit else 0 },
map_one' := by { have h1 : (is_unit_one.unit : Rˣ) = 1 := units.eq_iff.mp rfl,
simp only [h1, dif_pos, units.coe_eq_one, map_one, is_unit_one], },
map_mul' :=
begin
intros x y,
by_cases hx : is_unit x,
{ simp only [hx, is_unit.mul_iff, true_and, dif_pos],
by_cases hy : is_unit y,
{ simp only [hy, dif_pos],
have hm : (is_unit.mul_iff.mpr ⟨hx, hy⟩).unit = hx.unit * hy.unit := units.eq_iff.mp rfl,
rw [hm, map_mul],
norm_cast, },
{ simp only [hy, not_false_iff, dif_neg, mul_zero], }, },
{ simp only [hx, is_unit.mul_iff, false_and, not_false_iff, dif_neg, zero_mul], },
end ,
map_nonunit' := by { intros a ha, simp only [ha, not_false_iff, dif_neg], }, }
lemma of_unit_hom_coe (f : Rˣ →* R'ˣ) (a : Rˣ) :
of_unit_hom f ↑a = f a :=
by simp [of_unit_hom]
/-- The equivalence between multiplicative characters and homomorphisms of unit groups. -/
noncomputable
def equiv_to_unit_hom : mul_char R R' ≃ (Rˣ →* R'ˣ) :=
{ to_fun := to_unit_hom,
inv_fun := of_unit_hom,
left_inv :=
by { intro χ, ext x, rw [of_unit_hom_coe, coe_to_unit_hom] },
right_inv :=
by { intro f, ext x, rw [coe_to_unit_hom, of_unit_hom_coe], } }
@[simp]
lemma to_unit_hom_eq (χ : mul_char R R') : to_unit_hom χ = equiv_to_unit_hom χ := rfl
@[simp]
lemma of_unit_hom_eq (χ : Rˣ →* R'ˣ) : of_unit_hom χ = equiv_to_unit_hom.symm χ := rfl
@[simp]
lemma coe_equiv_to_unit_hom (χ : mul_char R R') (a : Rˣ) :
↑(equiv_to_unit_hom χ a) = χ a :=
coe_to_unit_hom χ a
@[simp]
lemma equiv_unit_hom_symm_coe (f : Rˣ →* R'ˣ) (a : Rˣ) :
equiv_to_unit_hom.symm f ↑a = f a :=
of_unit_hom_coe f a
/-!
### Commutative group structure on multiplicative characters
The multiplicative characters `R → R'` form a commutative group.
-/
protected
lemma map_one (χ : mul_char R R') : χ (1 : R) = 1 :=
χ.map_one'
/-- If the domain has a zero (and is nontrivial), then `χ 0 = 0`. -/
protected
lemma map_zero {R : Type u} [comm_monoid_with_zero R] [nontrivial R] (χ : mul_char R R') :
χ (0 : R) = 0 :=
by rw [map_nonunit χ not_is_unit_zero]
noncomputable
instance has_one : has_one (mul_char R R') := ⟨trivial R R'⟩
noncomputable
instance inhabited : inhabited (mul_char R R') := ⟨1⟩
/-- Evaluation of the trivial character -/
@[simp]
lemma one_apply_coe (a : Rˣ) : (1 : mul_char R R') a = 1 :=
dif_pos a.is_unit
/-- Multiplication of multiplicative characters. (This needs the target to be commutative.) -/
def mul (χ χ' : mul_char R R') : mul_char R R' :=
{ to_fun := χ * χ',
map_nonunit' := λ a ha, by simp [map_nonunit χ ha],
..χ.to_monoid_hom * χ'.to_monoid_hom }
instance has_mul : has_mul (mul_char R R') := ⟨mul⟩
lemma mul_apply (χ χ' : mul_char R R') (a : R) : (χ * χ') a = χ a * χ' a := rfl
@[simp]
lemma coe_to_fun_mul (χ χ' : mul_char R R') : ⇑(χ * χ') = χ * χ' := rfl
protected
lemma one_mul (χ : mul_char R R') : (1 : mul_char R R') * χ = χ := by { ext, simp }
protected
lemma mul_one (χ : mul_char R R') : χ * 1 = χ := by { ext, simp }
/-- The inverse of a multiplicative character. We define it as `inverse ∘ χ`. -/
noncomputable
def inv (χ : mul_char R R') : mul_char R R' :=
{ to_fun := λ a, monoid_with_zero.inverse (χ a),
map_nonunit' := λ a ha, by simp [map_nonunit _ ha],
..monoid_with_zero.inverse.to_monoid_hom.comp χ.to_monoid_hom }
noncomputable
instance has_inv : has_inv (mul_char R R') := ⟨inv⟩
/-- The inverse of a multiplicative character `χ`, applied to `a`, is the inverse of `χ a`. -/
lemma inv_apply_eq_inv (χ : mul_char R R') (a : R) :
χ⁻¹ a = ring.inverse (χ a) :=
eq.refl $ inv χ a
/-- Variant when the target is a field -/
lemma inv_apply_eq_inv' {R' : Type v} [field R'] (χ : mul_char R R') (a : R) :
χ⁻¹ a = (χ a)⁻¹ :=
(inv_apply_eq_inv χ a).trans $ ring.inverse_eq_inv (χ a)
/-- When the domain has a zero, we can as well take the inverse first. -/
lemma inv_apply {R : Type u} [comm_monoid_with_zero R] (χ : mul_char R R') (a : R) :
χ⁻¹ a = χ (ring.inverse a) :=
begin
by_cases ha : is_unit a,
{ rw [inv_apply_eq_inv],
have h := is_unit.map χ ha,
apply_fun ((*) (χ a)) using is_unit.mul_right_injective h,
rw [ring.mul_inverse_cancel _ h, ← map_mul, ring.mul_inverse_cancel _ ha, mul_char.map_one], },
{ revert ha, nontriviality R, intro ha, -- `nontriviality R` by itself doesn't do it
rw [map_nonunit _ ha, ring.inverse_non_unit a ha, mul_char.map_zero χ], },
end
/-- When the domain is a field, we can use the field inverse instead. -/
lemma inv_apply' {R : Type u} [field R] (χ : mul_char R R') (a : R) : χ⁻¹ a = χ a⁻¹ :=
(inv_apply χ a).trans $ congr_arg _ (ring.inverse_eq_inv a)
/-- The product of a character with its inverse is the trivial character. -/
@[simp]
lemma inv_mul (χ : mul_char R R') : χ⁻¹ * χ = 1 :=
begin
ext x,
rw [coe_to_fun_mul, pi.mul_apply, inv_apply_eq_inv,
ring.inverse_mul_cancel _ (is_unit.map _ x.is_unit), one_apply_coe],
end
/-- Finally, the commutative group structure on `mul_char R R'`. -/
noncomputable
instance comm_group : comm_group (mul_char R R') :=
{ one := 1,
mul := (*),
inv := has_inv.inv,
mul_left_inv := inv_mul,
mul_assoc := by { intros χ₁ χ₂ χ₃, ext a, simp [mul_assoc], },
mul_comm := by { intros χ₁ χ₂, ext a, simp [mul_comm], },
one_mul := one_mul,
mul_one := mul_one, }
/-- If `a` is a unit and `n : ℕ`, then `(χ ^ n) a = (χ a) ^ n`. -/
lemma pow_apply_coe (χ : mul_char R R') (n : ℕ) (a : Rˣ) :
(χ ^ n) a = (χ a) ^ n :=
begin
induction n with n ih,
{ rw [pow_zero, pow_zero, one_apply_coe], },
{ rw [pow_succ, pow_succ, mul_apply, ih], },
end
/-- If `n` is positive, then `(χ ^ n) a = (χ a) ^ n`. -/
lemma pow_apply' (χ : mul_char R R') {n : ℕ} (hn : 0 < n) (a : R) :
(χ ^ n) a = (χ a) ^ n :=
begin
by_cases ha : is_unit a,
{ exact pow_apply_coe χ n ha.unit, },
{ rw [map_nonunit (χ ^ n) ha, map_nonunit χ ha, zero_pow hn], },
end
end mul_char
end group
end definition_and_group
/-!
### Properties of multiplicative characters
We introduce the properties of being nontrivial or quadratic and prove
some basic facts about them.
We now assume that domain and target are commutative rings.
-/
section properties
namespace mul_char
universes u v w
variables {R : Type u} [comm_ring R] {R' : Type v} [comm_ring R'] {R'' : Type w} [comm_ring R'']
/-- A multiplicative character is *nontrivial* if it takes a value `≠ 1` on a unit. -/
def is_nontrivial (χ : mul_char R R') : Prop := ∃ a : Rˣ, χ a ≠ 1
/-- A multiplicative character is nontrivial iff it is not the trivial character. -/
lemma is_nontrivial_iff (χ : mul_char R R') : χ.is_nontrivial ↔ χ ≠ 1 :=
by simp only [is_nontrivial, ne.def, ext_iff, not_forall, one_apply_coe]
/-- A multiplicative character is *quadratic* if it takes only the values `0`, `1`, `-1`. -/
def is_quadratic (χ : mul_char R R') : Prop := ∀ a, χ a = 0 ∨ χ a = 1 ∨ χ a = -1
/-- We can post-compose a multiplicative character with a ring homomorphism. -/
@[simps]
def ring_hom_comp (χ : mul_char R R') (f : R' →+* R'') : mul_char R R'' :=
{ to_fun := λ a, f (χ a),
map_nonunit' := λ a ha, by simp only [map_nonunit χ ha, map_zero],
..f.to_monoid_hom.comp χ.to_monoid_hom }
/-- Composition with an injective ring homomorphism preserves nontriviality. -/
lemma is_nontrivial.comp {χ : mul_char R R'} (hχ : χ.is_nontrivial)
{f : R' →+* R''} (hf : function.injective f) :
(χ.ring_hom_comp f).is_nontrivial :=
begin
obtain ⟨a, ha⟩ := hχ,
use a,
rw [ring_hom_comp_apply, ← ring_hom.map_one f],
exact λ h, ha (hf h),
end
/-- Composition with a ring homomorphism preserves the property of being a quadratic character. -/
lemma is_quadratic.comp {χ : mul_char R R'} (hχ : χ.is_quadratic) (f : R' →+* R'') :
(χ.ring_hom_comp f).is_quadratic :=
begin
intro a,
rcases hχ a with (ha | ha | ha);
simp [ha],
end
/-- The inverse of a quadratic character is itself. → -/
lemma is_quadratic.inv {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ⁻¹ = χ :=
begin
ext x,
rw [inv_apply_eq_inv],
rcases hχ x with h₀ | h₁ | h₂,
{ rw [h₀, ring.inverse_zero], },
{ rw [h₁, ring.inverse_one], },
{ rw [h₂, (by norm_cast : (-1 : R') = (-1 : R'ˣ)), ring.inverse_unit (-1 : R'ˣ)],
refl, },
end
/-- The square of a quadratic character is the trivial character. -/
lemma is_quadratic.sq_eq_one {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ ^ 2 = 1 :=
begin
convert mul_left_inv _,
rw [pow_two, hχ.inv],
end
/-- The `p`th power of a quadratic character is itself, when `p` is the (prime) characteristic
of the target ring. -/
lemma is_quadratic.pow_char {χ : mul_char R R'} (hχ : χ.is_quadratic)
(p : ℕ) [hp : fact p.prime] [char_p R' p] :
χ ^ p = χ :=
begin
ext x,
rw [pow_apply_coe],
rcases hχ x with (hx | hx | hx); rw hx,
{ rw [zero_pow (fact.out p.prime).pos], },
{ rw [one_pow], },
{ exact char_p.neg_one_pow_char R' p, },
end
/-- The `n`th power of a quadratic character is the trivial character, when `n` is even. -/
lemma is_quadratic.pow_even {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : even n) :
χ ^ n = 1 :=
begin
obtain ⟨n, rfl⟩ := even_iff_two_dvd.mp hn,
rw [pow_mul, hχ.sq_eq_one, one_pow]
end
/-- The `n`th power of a quadratic character is itself, when `n` is odd. -/
lemma is_quadratic.pow_odd {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : odd n) :
χ ^ n = χ :=
begin
obtain ⟨n, rfl⟩ := hn,
rw [pow_add, pow_one, hχ.pow_even (even_two_mul _), one_mul]
end
open_locale big_operators
/-- The sum over all values of a nontrivial multiplicative character on a finite ring is zero
(when the target is a domain). -/
lemma is_nontrivial.sum_eq_zero [fintype R] [is_domain R'] {χ : mul_char R R'}
(hχ : χ.is_nontrivial) :
∑ a, χ a = 0 :=
begin
rcases hχ with ⟨b, hb⟩,
refine eq_zero_of_mul_eq_self_left hb _,
simp only [finset.mul_sum, ← map_mul],
exact fintype.sum_bijective _ (units.mul_left_bijective b) _ _ (λ x, rfl)
end
/-- The sum over all values of the trivial multiplicative character on a finite ring is
the cardinality of its unit group. -/
lemma sum_one_eq_card_units [fintype R] [decidable_eq R] :
∑ a, (1 : mul_char R R') a = fintype.card Rˣ :=
begin
calc ∑ a, (1 : mul_char R R') a
= ∑ a : R, if is_unit a then 1 else 0 : finset.sum_congr rfl (λ a _, _)
... = ((finset.univ : finset R).filter is_unit).card : finset.sum_boole
... = (finset.univ.map (⟨(coe : Rˣ → R), units.ext⟩)).card : _
... = fintype.card Rˣ : congr_arg _ (finset.card_map _),
{ split_ifs with h h,
{ exact one_apply_coe h.unit },
{ exact map_nonunit _ h } },
{ congr,
ext a,
simp only [finset.mem_filter, finset.mem_univ, true_and, finset.mem_map,
function.embedding.coe_fn_mk, exists_true_left, is_unit], },
end
end mul_char
end properties
|
c53d0c7b537adc9765ec378c89894cd31474ff3f | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/function/simple_func.lean | 9051f119f2976536646e598ba9f04506a7b2df2e | [
"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 | 46,935 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import measure_theory.constructions.borel_space
import algebra.indicator_function
import algebra.support
/-!
# Simple functions
A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}`
is measurable, and the range is finite. In this file, we define simple functions and establish their
basic properties; and we construct a sequence of simple functions approximating an arbitrary Borel
measurable function `f : α → ℝ≥0∞`.
The theorem `measurable.ennreal_induction` shows that in order to prove something for an arbitrary
measurable function into `ℝ≥0∞`, it is sufficient to show that the property holds for (multiples of)
characteristic functions and is closed under addition and supremum of increasing sequences of
functions.
-/
noncomputable theory
open set (hiding restrict restrict_apply) filter ennreal function (support)
open_locale classical topology big_operators nnreal ennreal measure_theory
namespace measure_theory
variables {α β γ δ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) :=
(to_fun : α → β)
(measurable_set_fiber' : ∀ x, measurable_set (to_fun ⁻¹' {x}))
(finite_range' : (set.range to_fun).finite)
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space α]
instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) (λ _, α → β) := ⟨to_fun⟩
lemma coe_injective ⦃f g : α →ₛ β⦄ (H : (f : α → β) = g) : f = g :=
by cases f; cases g; congr; exact H
@[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g :=
coe_injective $ funext H
lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range'
lemma measurable_set_fiber (f : α →ₛ β) (x : β) : measurable_set (f ⁻¹' {x}) :=
f.measurable_set_fiber' x
@[simp] lemma apply_mk (f : α → β) (h h') (x : α) : simple_func.mk f h h' x = f x := rfl
/-- Simple function defined on the empty type. -/
def of_is_empty [is_empty α] : α →ₛ β :=
{ to_fun := is_empty_elim,
measurable_set_fiber' := λ x, subsingleton.measurable_set,
finite_range' := by simp [range_eq_empty] }
/-- Range of a simple function `α →ₛ β` as a `finset β`. -/
protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset
@[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f :=
finite.mem_to_finset _
theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f :=
f.finite_range.coe_to_finset
theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) :
x ∈ f.range :=
let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in
mem_range.2 ⟨a, ha⟩
lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} :
(∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) :=
by simp only [mem_range, set.forall_range_iff]
lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} :
(∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) :=
by simpa only [mem_range, exists_prop] using set.exists_range_iff
lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range :=
preimage_singleton_eq_empty.trans $ not_congr mem_range.symm
lemma exists_forall_le [nonempty β] [preorder β] [is_directed β (≤)] (f : α →ₛ β) :
∃ C, ∀ x, f x ≤ C :=
f.range.exists_le.imp $ λ C, forall_range_iff.1
/-- Constant function as a `simple_func`. -/
def const (α) {β} [measurable_space α] (b : β) : α →ₛ β :=
⟨λ a, b, λ x, measurable_set.const _, finite_range_const⟩
instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ default⟩
theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl
@[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
@[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) :
(const α b).range = {b} :=
finset.coe_injective $ by simp
lemma range_const_subset (α) [measurable_space α] (b : β) :
(const α b).range ⊆ {b} :=
finset.coe_subset.1 $ by simp
lemma simple_func_bot {α} (f : @simple_func α ⊥ β) [nonempty β] : ∃ c, ∀ x, f x = c :=
begin
have hf_meas := @simple_func.measurable_set_fiber α _ ⊥ f,
simp_rw measurable_space.measurable_set_bot_iff at hf_meas,
casesI is_empty_or_nonempty α,
{ simp only [is_empty.forall_iff, exists_const], },
{ specialize hf_meas (f h.some),
cases hf_meas,
{ exfalso,
refine set.not_mem_empty h.some _,
rw [← hf_meas, set.mem_preimage],
exact set.mem_singleton _, },
{ refine ⟨f h.some, λ x, _⟩,
have : x ∈ f ⁻¹' {f h.some},
{ rw hf_meas, exact set.mem_univ x, },
rwa [set.mem_preimage, set.mem_singleton_iff] at this, }, },
end
lemma simple_func_bot' {α} [nonempty β] (f : @simple_func α ⊥ β) :
∃ c, f = @simple_func.const α _ ⊥ c :=
begin
obtain ⟨c, h_eq⟩ := simple_func_bot f,
refine ⟨c, _⟩,
ext1 x,
rw [h_eq x, simple_func.coe_const],
end
lemma measurable_set_cut (r : α → β → Prop) (f : α →ₛ β)
(h : ∀b, measurable_set {a | r a b}) : measurable_set {a | r a (f a)} :=
begin
have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b},
{ ext a,
suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa,
exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ },
rw this,
exact measurable_set.bUnion f.finite_range.countable
(λ b _, measurable_set.inter (h b) (f.measurable_set_fiber _))
end
@[measurability]
theorem measurable_set_preimage (f : α →ₛ β) (s) : measurable_set (f ⁻¹' s) :=
measurable_set_cut (λ _ b, b ∈ s) f (λ b, measurable_set.const (b ∈ s))
/-- A simple function is measurable -/
@[measurability]
protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f :=
λ s _, measurable_set_preimage f s
@[measurability]
protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) :
ae_measurable f μ :=
f.measurable.ae_measurable
protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) :
∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) :=
sum_measure_preimage_singleton _ (λ _ _, f.measurable_set_fiber _)
lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) :
∑ y in f.range, μ (f ⁻¹' {y}) = μ univ :=
by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range]
/-- If-then-else as a `simple_func`. -/
def piecewise (s : set α) (hs : measurable_set s) (f g : α →ₛ β) : α →ₛ β :=
⟨s.piecewise f g,
λ x, by letI : measurable_space β := ⊤; exact
f.measurable.piecewise hs g.measurable trivial,
(f.finite_range.union g.finite_range).subset range_ite_subset⟩
@[simp] theorem coe_piecewise {s : set α} (hs : measurable_set s) (f g : α →ₛ β) :
⇑(piecewise s hs f g) = s.piecewise f g :=
rfl
theorem piecewise_apply {s : set α} (hs : measurable_set s) (f g : α →ₛ β) (a) :
piecewise s hs f g a = if a ∈ s then f a else g a :=
rfl
@[simp] lemma piecewise_compl {s : set α} (hs : measurable_set sᶜ) (f g : α →ₛ β) :
piecewise sᶜ hs f g = piecewise s hs.of_compl g f :=
coe_injective $ by simp [hs]
@[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ measurable_set.univ f g = f :=
coe_injective $ by simp
@[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ measurable_set.empty f g = g :=
coe_injective $ by simp
lemma support_indicator [has_zero β] {s : set α} (hs : measurable_set s) (f : α →ₛ β) :
function.support (f.piecewise s hs (simple_func.const α 0)) = s ∩ function.support f :=
set.support_indicator
lemma range_indicator {s : set α} (hs : measurable_set s)
(hs_nonempty : s.nonempty) (hs_ne_univ : s ≠ univ) (x y : β) :
(piecewise s hs (const α x) (const α y)).range = {x, y} :=
by simp only [← finset.coe_inj, coe_range, coe_piecewise, range_piecewise, coe_const,
finset.coe_insert, finset.coe_singleton, hs_nonempty.image_const,
(nonempty_compl.2 hs_ne_univ).image_const, singleton_union]
lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ)
(hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) :=
λ s hs, f.measurable_set_cut (λ a b, g b a ∈ s) $ λ b, hg b hs
/-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ :=
⟨λa, g (f a) a,
λ c, f.measurable_set_cut (λ a b, g b a = c) $ λ b, (g b).measurable_set_preimage {c},
(f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $
by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩
@[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) :
f.bind g a = g (f a) a := rfl
/-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple
function `g ∘ f : α →ₛ γ` -/
def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g)
theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl
@[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl
@[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) :
(f.map g).range = f.range.image g :=
finset.coe_injective $ by simp only [coe_range, coe_map, finset.coe_image, range_comp]
@[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl
lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) :
(f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) :=
by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter,
← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp }
lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) :
(f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) :=
map_preimage _ _ _
/-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/
def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ :=
{ to_fun := f ∘ g,
finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _,
measurable_set_fiber' := λ z, hgm (f.measurable_set_fiber z) }
@[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
⇑(f.comp g hgm) = f ∘ g :=
rfl
lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
(f.comp g hgm).range ⊆ f.range :=
finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range]
/-- Extend a `simple_func` along a measurable embedding: `f₁.extend g hg f₂` is the function
`F : β →ₛ γ` such that `F ∘ g = f₁` and `F y = f₂ y` whenever `y ∉ range g`. -/
def extend [measurable_space β] (f₁ : α →ₛ γ) (g : α → β)
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : β →ₛ γ :=
{ to_fun := function.extend g f₁ f₂,
finite_range' := (f₁.finite_range.union $ f₂.finite_range.subset
(image_subset_range _ _)).subset (range_extend_subset _ _ _),
measurable_set_fiber' :=
begin
letI : measurable_space γ := ⊤, haveI : measurable_singleton_class γ := ⟨λ _, trivial⟩,
exact λ x, hg.measurable_extend f₁.measurable f₂.measurable (measurable_set_singleton _)
end }
@[simp] lemma extend_apply [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) (x : α) : (f₁.extend g hg f₂) (g x) = f₁ x :=
hg.injective.extend_apply _ _ _
@[simp] lemma extend_apply' [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) {y : β} (h : ¬∃ x, g x = y) :
(f₁.extend g hg f₂) y = f₂ y :=
function.extend_apply' _ _ _ h
@[simp] lemma extend_comp_eq' [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂) ∘ g = f₁ :=
funext $ λ x, extend_apply _ _ _ _
@[simp] lemma extend_comp_eq [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂).comp g hg.measurable = f₁ :=
coe_injective $ extend_comp_eq' _ _ _
/-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function
with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/
def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f)
@[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β`
into `λ a, (f a, g a)`. -/
def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) :
pair f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) :
(pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) :=
by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp
@[to_additive] instance [has_one β] : has_one (α →ₛ β) := ⟨const α 1⟩
@[to_additive] instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩
@[to_additive] instance [has_div β] : has_div (α →ₛ β) := ⟨λf g, (f.map (/)).seq g⟩
@[to_additive] instance [has_inv β] : has_inv (α →ₛ β) := ⟨λf, f.map (has_inv.inv)⟩
instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩
instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩
instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩
@[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_one [has_one β] : ⇑(1 : α →ₛ β) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl
@[simp, norm_cast, to_additive] lemma coe_inv [has_inv β] (f : α →ₛ β) : ⇑(f⁻¹) = f⁻¹ := rfl
@[simp, norm_cast, to_additive] lemma coe_div [has_div β] (f g : α →ₛ β) : ⇑(f / g) = f / g := rfl
@[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl
@[simp, norm_cast] lemma coe_sup [has_sup β] (f g : α →ₛ β) : ⇑(f ⊔ g) = f ⊔ g := rfl
@[simp, norm_cast] lemma coe_inf [has_inf β] (f g : α →ₛ β) : ⇑(f ⊓ g) = f ⊓ g := rfl
@[to_additive] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl
@[to_additive] lemma div_apply [has_div β] (f g : α →ₛ β) (x : α) : (f / g) x = f x / g x := rfl
@[to_additive] lemma inv_apply [has_inv β] (f : α →ₛ β) (x : α) : f⁻¹ x = (f x)⁻¹ := rfl
lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl
lemma inf_apply [has_inf β] (f g : α →ₛ β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl
@[simp, to_additive] lemma range_one [nonempty α] [has_one β] : (1 : α →ₛ β).range = {1} :=
finset.ext $ λ x, by simp [eq_comm]
@[simp] lemma range_eq_empty_of_is_empty {β} [hα : is_empty α] (f : α →ₛ β) :
f.range = ∅ :=
begin
rw ← finset.not_nonempty_iff_eq_empty,
by_contra,
obtain ⟨y, hy_mem⟩ := h,
rw [simple_func.mem_range, set.mem_range] at hy_mem,
obtain ⟨x, hxy⟩ := hy_mem,
rw is_empty_iff at hα,
exact hα x,
end
lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 :=
forall_range_iff.2 $ λ x, rfl
@[to_additive]
lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl
lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl
@[to_additive]
lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl
@[to_additive]
theorem map_mul [has_mul β] [has_mul γ] {g : β → γ}
(hg : ∀ x y, g (x * y) = g x * g y) (f₁ f₂ : α →ₛ β) : (f₁ * f₂).map g = f₁.map g * f₂.map g :=
ext $ λ x, hg _ _
variables {K : Type*}
instance [has_smul K β] : has_smul K (α →ₛ β) := ⟨λ k f, f.map ((•) k)⟩
@[simp] lemma coe_smul [has_smul K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl
lemma smul_apply [has_smul K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl
instance has_nat_pow [monoid β] : has_pow (α →ₛ β) ℕ := ⟨λ f n, f.map (^ n)⟩
@[simp] lemma coe_pow [monoid β] (f : α →ₛ β) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl
lemma pow_apply [monoid β] (n : ℕ) (f : α →ₛ β) (a : α) : (f ^ n) a = f a ^ n := rfl
instance has_int_pow [div_inv_monoid β] : has_pow (α →ₛ β) ℤ := ⟨λ f n, f.map (^ n)⟩
@[simp] lemma coe_zpow [div_inv_monoid β] (f : α →ₛ β) (z : ℤ) : ⇑(f ^ z) = f ^ z := rfl
lemma zpow_apply [div_inv_monoid β] (z : ℤ) (f : α →ₛ β) (a : α) : (f ^ z) a = f a ^ z := rfl
-- TODO: work out how to generate these instances with `to_additive`, which gets confused by the
-- argument order swap between `coe_smul` and `coe_pow`.
section additive
instance [add_monoid β] : add_monoid (α →ₛ β) :=
function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
(λ _ _, coe_smul _ _)
instance [add_comm_monoid β] : add_comm_monoid (α →ₛ β) :=
function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
(λ _ _, coe_smul _ _)
instance [add_group β] : add_group (α →ₛ β) :=
function.injective.add_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
instance [add_comm_group β] : add_comm_group (α →ₛ β) :=
function.injective.add_comm_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
end additive
@[to_additive] instance [monoid β] : monoid (α →ₛ β) :=
function.injective.monoid (λ f, show α → β, from f) coe_injective coe_one coe_mul coe_pow
@[to_additive] instance [comm_monoid β] : comm_monoid (α →ₛ β) :=
function.injective.comm_monoid (λ f, show α → β, from f) coe_injective coe_one coe_mul coe_pow
@[to_additive] instance [group β] : group (α →ₛ β) :=
function.injective.group (λ f, show α → β, from f) coe_injective
coe_one coe_mul coe_inv coe_div coe_pow coe_zpow
@[to_additive] instance [comm_group β] : comm_group (α →ₛ β) :=
function.injective.comm_group (λ f, show α → β, from f) coe_injective
coe_one coe_mul coe_inv coe_div coe_pow coe_zpow
instance [semiring K] [add_comm_monoid β] [module K β] : module K (α →ₛ β) :=
function.injective.module K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩
coe_injective coe_smul
lemma smul_eq_map [has_smul K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl
instance [preorder β] : preorder (α →ₛ β) :=
{ le_refl := λf a, le_rfl,
le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order β] : partial_order (α →ₛ β) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [has_le β] [order_bot β] : order_bot (α →ₛ β) :=
{ bot := const α ⊥, bot_le := λf a, bot_le }
instance [has_le β] [order_top β] : order_top (α →ₛ β) :=
{ top := const α ⊤, le_top := λf a, le_top }
instance [semilattice_inf β] : semilattice_inf (α →ₛ β) :=
{ inf := (⊓),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup β] : semilattice_sup (α →ₛ β) :=
{ sup := (⊔),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [lattice β] : lattice (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [has_le β] [bounded_order β] : bounded_order (α →ₛ β) :=
{ .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup β] [order_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) :
s.sup f a = s.sup (λc, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section restrict
variables [has_zero β]
/-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/
def restrict (f : α →ₛ β) (s : set α) : α →ₛ β :=
if hs : measurable_set s then piecewise s hs f 0 else 0
theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α}
(hs : ¬measurable_set s) :
restrict f s = 0 :=
dif_neg hs
@[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : measurable_set s) :
⇑(restrict f s) = indicator s f :=
by { rw [restrict, dif_pos hs], refl }
@[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f :=
by simp [restrict]
@[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 :=
by simp [restrict]
theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) :
(f.restrict s).map g = (f.map g).restrict s :=
ext $ λ x,
if hs : measurable_set s then by simp [hs, set.indicator_comp_of_zero hg]
else by simp [restrict_of_not_measurable hs, hg]
theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) :
(f.restrict s).map (coe : ℝ≥0 → ℝ≥0∞) = (f.map coe).restrict s :=
map_restrict_of_zero ennreal.coe_zero _ _
theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) :
(f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s :=
map_restrict_of_zero nnreal.coe_zero _ _
theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : measurable_set s) (a) :
restrict f s a = indicator s f a :=
by simp only [f.coe_restrict hs]
theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : measurable_set s)
{t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t :=
by simp [hs, indicator_preimage_of_not_mem _ _ ht, inter_comm]
theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : measurable_set s)
{r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} :=
f.restrict_preimage hs hr.symm
lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : measurable_set s) :
r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator]
lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β}
(hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) :
r ∈ f '' s :=
if hs : measurable_set s then by simpa [mem_restrict_range hs, h0] using hr
else by { rw [restrict_of_not_measurable hs] at hr,
exact (h0 $ eq_zero_of_mem_range_zero hr).elim }
@[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) :
f.restrict s ≤ g.restrict s :=
if hs : measurable_set s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)]
else by simp only [restrict_of_not_measurable hs, le_refl]
end restrict
section approx
section
variables [semilattice_sup β] [order_bot β] [has_zero β]
/-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation
by simple functions is defined so that in case `β = ℝ≥0∞` it sends each `a` to the supremum
of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β :=
(finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a})
lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) :
(approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf measurable_set_Ici)
end
lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] [measurable_space γ]
{i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α)
(hf : measurable f) (hg : measurable g) :
(approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β]
[has_zero β] [measurable_space β] [opens_measurable_space β]
(i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) :
(⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ℝ≥0∞`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : ℕ) : ℝ≥0∞ :=
ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ))
lemma ennreal_rat_embed_encode (q : ℚ) :
ennreal_rat_embed (encodable.encode q) = real.to_nnreal q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `α → ℝ≥0∞` by a sequence of simple functions. -/
def eapprox : (α → ℝ≥0∞) → ℕ → α →ₛ ℝ≥0∞ :=
approx ennreal_rat_embed
lemma eapprox_lt_top (f : α → ℝ≥0∞) (n : ℕ) (a : α) : eapprox f n a < ∞ :=
begin
simp only [eapprox, approx, finset_sup_apply, finset.sup_lt_iff, with_top.zero_lt_top,
finset.mem_range, ennreal.bot_eq_zero, restrict],
assume b hb,
split_ifs,
{ simp only [coe_zero, coe_piecewise, piecewise_eq_indicator, coe_const],
calc {a : α | ennreal_rat_embed b ≤ f a}.indicator (λ x, ennreal_rat_embed b) a
≤ ennreal_rat_embed b : indicator_le_self _ _ a
... < ⊤ : ennreal.coe_lt_top },
{ exact with_top.zero_lt_top },
end
@[mono] lemma monotone_eapprox (f : α → ℝ≥0∞) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : α → ℝ≥0∞) (hf : measurable f) (a : α) :
(⨆n, (eapprox f n : α →ₛ ℝ≥0∞) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩,
have : (real.to_nnreal q : ℝ≥0∞) ≤
(⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_rfl },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space γ] {f : γ → ℝ≥0∞} {g : α → γ} {n : ℕ}
(hf : measurable f) (hg : measurable g) :
(eapprox (f ∘ g) n : α → ℝ≥0∞) = (eapprox f n : γ →ₛ ℝ≥0∞) ∘ g :=
funext $ assume a, approx_comp a hf hg
/-- Approximate a function `α → ℝ≥0∞` by a series of simple functions taking their values
in `ℝ≥0`. -/
def eapprox_diff (f : α → ℝ≥0∞) : ∀ (n : ℕ), α →ₛ ℝ≥0
| 0 := (eapprox f 0).map ennreal.to_nnreal
| (n+1) := (eapprox f (n+1) - eapprox f n).map ennreal.to_nnreal
lemma sum_eapprox_diff (f : α → ℝ≥0∞) (n : ℕ) (a : α) :
(∑ k in finset.range (n+1), (eapprox_diff f k a : ℝ≥0∞)) = eapprox f n a :=
begin
induction n with n IH,
{ simp only [nat.nat_zero_eq_zero, finset.sum_singleton, finset.range_one], refl },
{ rw [finset.sum_range_succ, nat.succ_eq_add_one, IH, eapprox_diff, coe_map, function.comp_app,
coe_sub, pi.sub_apply, ennreal.coe_to_nnreal,
add_tsub_cancel_of_le (monotone_eapprox f (nat.le_succ _) _)],
apply (lt_of_le_of_lt _ (eapprox_lt_top f (n+1) a)).ne,
rw tsub_le_iff_right,
exact le_self_add },
end
lemma tsum_eapprox_diff (f : α → ℝ≥0∞) (hf : measurable f) (a : α) :
(∑' n, (eapprox_diff f n a : ℝ≥0∞)) = f a :=
by simp_rw [ennreal.tsum_eq_supr_nat' (tendsto_add_at_top_nat 1), sum_eapprox_diff,
supr_eapprox_apply f hf a]
end eapprox
end measurable
section measure
variables {m : measurable_space α} {μ ν : measure α}
/-- Integral of a simple function whose codomain is `ℝ≥0∞`. -/
def lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (μ : measure α) : ℝ≥0∞ :=
∑ x in f.range, x * μ (f ⁻¹' {x})
lemma lintegral_eq_of_subset (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞}
(hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
begin
refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _,
{ simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] },
{ intros, assumption },
{ intros b _ hb,
refine ⟨b, _, hb, rfl⟩,
rw [mem_range, ← preimage_singleton_nonempty],
exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 },
{ intros, refl }
end
lemma lintegral_eq_of_subset' (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞}
(hs : f.range \ {0} ⊆ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
f.lintegral_eq_of_subset $ λ x hfx _, hs $
finset.mem_sdiff.2 ⟨f.mem_range_self x, mt finset.mem_singleton.1 hfx⟩
/-- Calculate the integral of `(g ∘ f)`, where `g : β → ℝ≥0∞` and `f : α →ₛ β`. -/
lemma map_lintegral (g : β → ℝ≥0∞) (f : α →ₛ β) :
(f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) :=
begin
simp only [lintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h },
end
lemma add_lintegral (f g : α →ₛ ℝ≥0∞) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ :=
calc (f + g).lintegral μ =
∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) :
by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) +
∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ :
by rw [map_lintegral, map_lintegral]
... = lintegral f μ + lintegral g μ : rfl
lemma const_mul_lintegral (f : α →ₛ ℝ≥0∞) (x : ℝ≥0∞) :
(const α x * f).lintegral μ = x * f.lintegral μ :=
calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) :
map_lintegral _ _
... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.lintegral μ :
finset.mul_sum.symm
/-- Integral of a simple function `α →ₛ ℝ≥0∞` as a bilinear map. -/
def lintegralₗ {m : measurable_space α} : (α →ₛ ℝ≥0∞) →ₗ[ℝ≥0∞] measure α →ₗ[ℝ≥0∞] ℝ≥0∞ :=
{ to_fun := λ f,
{ to_fun := lintegral f,
map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib],
map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] },
map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g),
map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) }
@[simp] lemma zero_lintegral : (0 : α →ₛ ℝ≥0∞).lintegral μ = 0 :=
linear_map.ext_iff.1 lintegralₗ.map_zero μ
lemma lintegral_add {ν} (f : α →ₛ ℝ≥0∞) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν :=
(lintegralₗ f).map_add μ ν
lemma lintegral_smul (f : α →ₛ ℝ≥0∞) (c : ℝ≥0∞) :
f.lintegral (c • μ) = c • f.lintegral μ :=
(lintegralₗ f).map_smul c μ
@[simp] lemma lintegral_zero [measurable_space α] (f : α →ₛ ℝ≥0∞) :
f.lintegral 0 = 0 :=
(lintegralₗ f).map_zero
lemma lintegral_sum {m : measurable_space α} {ι} (f : α →ₛ ℝ≥0∞) (μ : ι → measure α) :
f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) :=
begin
simp only [lintegral, measure.sum_apply, f.measurable_set_preimage, ← finset.tsum_subtype,
← ennreal.tsum_mul_left],
apply ennreal.tsum_comm
end
lemma restrict_lintegral (f : α →ₛ ℝ≥0∞) {s : set α} (hs : measurable_set s) :
(restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :=
calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) :
lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s
then λ _, by simp only [f.restrict_apply hs, indicator_of_mem hxs, mem_range_self]
else false.elim $ hx $ by simp [*]
... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :
finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul]
else by rw [restrict_preimage_singleton _ hs hb, inter_comm]
lemma lintegral_restrict {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (s : set α) (μ : measure α) :
f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) :=
by simp only [lintegral, measure.restrict_apply, f.measurable_set_preimage]
lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ℝ≥0∞) {s : set α}
(hs : measurable_set s) :
(restrict f s).lintegral μ = f.lintegral (μ.restrict s) :=
by rw [f.restrict_lintegral hs, lintegral_restrict]
lemma const_lintegral (c : ℝ≥0∞) : (const α c).lintegral μ = c * μ univ :=
begin
rw [lintegral],
casesI is_empty_or_nonempty α,
{ simp [μ.eq_zero_of_is_empty] },
{ simp [preimage_const_of_mem] },
end
lemma const_lintegral_restrict (c : ℝ≥0∞) (s : set α) :
(const α c).lintegral (μ.restrict s) = c * μ s :=
by rw [const_lintegral, measure.restrict_apply measurable_set.univ, univ_inter]
lemma restrict_const_lintegral (c : ℝ≥0∞) {s : set α} (hs : measurable_set s) :
((const α c).restrict s).lintegral μ = c * μ s :=
by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict]
lemma le_sup_lintegral (f g : α →ₛ ℝ≥0∞) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ :=
calc f.lintegral μ ⊔ g.lintegral μ =
((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl
... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) :
begin
rw [map_lintegral, map_lintegral],
refine sup_le _ _;
refine finset.sum_le_sum (λ a _, mul_le_mul_right' _ _),
exact le_sup_left,
exact le_sup_right
end
... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral]
/-- `simple_func.lintegral` is monotone both in function and in measure. -/
@[mono] lemma lintegral_mono {f g : α →ₛ ℝ≥0∞} (hfg : f ≤ g) (hμν : μ ≤ ν) :
f.lintegral μ ≤ g.lintegral ν :=
calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left
... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _
... = g.lintegral μ : by rw [sup_of_le_right hfg]
... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $
hμν _ (g.measurable_set_preimage _)
/-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/
lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ℝ≥0∞} {g : β →ₛ ℝ≥0∞}
{ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) :
f.lintegral μ = g.lintegral ν :=
begin
simp only [lintegral, ← H],
apply lintegral_eq_of_subset,
simp only [H],
intros,
exact mem_range_of_measure_ne_zero ‹_›
end
/-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/
lemma lintegral_congr {f g : α →ₛ ℝ≥0∞} (h : f =ᵐ[μ] g) :
f.lintegral μ = g.lintegral μ :=
lintegral_eq_of_measure_preimage $ λ y, measure_congr $
eventually.set_eq $ h.mono $ λ x hx, by simp [hx]
lemma lintegral_map' {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ℝ≥0∞) (g : β →ₛ ℝ≥0∞)
(m' : α → β) (eq : ∀ a, f a = g (m' a)) (h : ∀s, measurable_set s → μ' s = μ (m' ⁻¹' s)) :
f.lintegral μ = g.lintegral μ' :=
lintegral_eq_of_measure_preimage $ λ y,
by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.measurable_set_preimage _)).symm }
lemma lintegral_map {β} [measurable_space β] (g : β →ₛ ℝ≥0∞) {f : α → β} (hf : measurable f) :
g.lintegral (measure.map f μ) = (g.comp f hf).lintegral μ :=
eq.symm $ lintegral_map' _ _ f (λ a, rfl) (λ s hs, measure.map_apply hf hs)
end measure
section fin_meas_supp
open finset function
lemma support_eq [measurable_space α] [has_zero β] (f : α →ₛ β) :
support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} :=
set.ext $ λ x, by simp only [mem_support, set.mem_preimage, mem_filter, mem_range_self, true_and,
exists_prop, mem_Union, set.mem_range, mem_singleton_iff, exists_eq_right']
variables {m : measurable_space α} [has_zero β] [has_zero γ] {μ : measure α} {f : α →ₛ β}
lemma measurable_set_support [measurable_space α] (f : α →ₛ β) : measurable_set (support f) :=
by { rw f.support_eq, exact finset.measurable_set_bUnion _ (λ y hy, measurable_set_fiber _ _), }
/-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite
measure. -/
protected def fin_meas_supp {m : measurable_space α} (f : α →ₛ β) (μ : measure α) : Prop :=
f =ᶠ[μ.cofinite] 0
lemma fin_meas_supp_iff_support : f.fin_meas_supp μ ↔ μ (support f) < ∞ := iff.rfl
lemma fin_meas_supp_iff : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞ :=
begin
split,
{ refine λ h y hy, lt_of_le_of_lt (measure_mono _) h,
exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx },
{ intro H,
rw [fin_meas_supp_iff_support, support_eq],
refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _),
exact λ y hy, (H y (finset.mem_filter.1 hy).2).ne }
end
namespace fin_meas_supp
lemma meas_preimage_singleton_ne_zero (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) :
μ (f ⁻¹' {y}) < ∞ :=
fin_meas_supp_iff.1 h y hy
protected lemma map {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) :
(f.map g).fin_meas_supp μ :=
flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f)
lemma of_map {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) :
f.fin_meas_supp μ :=
flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _
lemma map_iff {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) :
(f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ :=
⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩
protected lemma pair {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) :
(pair f g).fin_meas_supp μ :=
calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g
... ≤ μ (support f) + μ (support g) : measure_union_le _ _
... < _ : add_lt_top.2 ⟨hf, hg⟩
protected lemma map₂ [has_zero δ] (hf : f.fin_meas_supp μ)
{g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) :
((pair f g).map (function.uncurry op)).fin_meas_supp μ :=
(hf.pair hg).map H
protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f + g).fin_meas_supp μ :=
by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) }
protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f * g).fin_meas_supp μ :=
by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) }
lemma lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a ≠ ∞) :
f.lintegral μ < ∞ :=
begin
refine sum_lt_top (λ a ha, _),
rcases eq_or_ne a ∞ with rfl|ha,
{ simp only [ae_iff, ne.def, not_not] at hf,
simp [set.preimage, hf] },
{ by_cases ha0 : a = 0,
{ subst a, rwa [zero_mul] },
{ exact mul_ne_top ha (fin_meas_supp_iff.1 hm _ ha0).ne } }
end
lemma of_lintegral_ne_top {f : α →ₛ ℝ≥0∞} (h : f.lintegral μ ≠ ∞) : f.fin_meas_supp μ :=
begin
refine fin_meas_supp_iff.2 (λ b hb, _),
rw [f.lintegral_eq_of_subset' (finset.subset_insert b _)] at h,
refine ennreal.lt_top_of_mul_ne_top_right _ hb,
exact (lt_top_of_sum_ne_top h (finset.mem_insert_self _ _)).ne
end
lemma iff_lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hf : ∀ᵐ a ∂μ, f a ≠ ∞) :
f.fin_meas_supp μ ↔ f.lintegral μ < ∞ :=
⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_ne_top h.ne⟩
end fin_meas_supp
end fin_meas_supp
/-- To prove something for an arbitrary simple function, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under
addition (of functions with disjoint support).
It is possible to make the hypotheses in `h_add` a bit stronger, and such conditions can be added
once we need them (for example it is only necessary to consider the case where `g` is a multiple
of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/
@[elab_as_eliminator]
protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop}
(h_ind : ∀ c {s} (hs : measurable_set s),
P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0)))
(h_add : ∀ ⦃f g : simple_func α γ⦄, disjoint (support f) (support g) → P f → P g → P (f + g))
(f : simple_func α γ) : P f :=
begin
generalize' h : f.range \ {0} = s,
rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h,
revert s f h, refine finset.induction _ _,
{ intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf,
convert h_ind 0 measurable_set.univ, ext x, simp [hf] },
{ intros x s hxs ih f hf,
have mx := f.measurable_set_preimage {x},
let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f,
have Pg : P g,
{ apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise],
rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert,
insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union],
{ rw [set.image_subset_iff], convert set.subset_univ _,
exact preimage_const_of_mem (mem_singleton _) },
{ rwa [finset.mem_coe] }},
convert h_add _ Pg (h_ind x mx),
{ ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] },
rw disjoint_iff_inf_le,
rintro y, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] }
end
end simple_func
end measure_theory
open measure_theory measure_theory.simple_func
/-- To prove something for an arbitrary measurable function into `ℝ≥0∞`, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under addition
and supremum of increasing sequences of functions.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_add` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`. -/
@[elab_as_eliminator]
theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ℝ≥0∞) → Prop}
(h_ind : ∀ (c : ℝ≥0∞) ⦃s⦄, measurable_set s → P (indicator s (λ _, c)))
(h_add : ∀ ⦃f g : α → ℝ≥0∞⦄, disjoint (support f) (support g) → measurable f → measurable g →
P f → P g → P (f + g))
(h_supr : ∀ ⦃f : ℕ → α → ℝ≥0∞⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f)
(hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x))
⦃f : α → ℝ≥0∞⦄ (hf : measurable f) : P f :=
begin
convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _,
{ ext1 x, rw [supr_eapprox_apply f hf] },
{ exact λ n, simple_func.induction (λ c s hs, h_ind c hs)
(λ f g hfg hf hg, h_add hfg f.measurable g.measurable hf hg) (eapprox f n) }
end
|
255d8a0d8cf223a7dc14966a4ebb2959f0598897 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/pilex.lean | b56c521dafe1f88d2f255ff1c82aa8ad8932967e | [
"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 | 3,760 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.order.pi
import order.well_founded
import order.min_max
/-!
# Lexicographic order on Pi types
This file defines the lexicographic relation for Pi types of partial orders and linear orders. We
also provide a `pilex` analog of `pi.ordered_comm_group` (see `algebra.order.pi`).
-/
variables {ι : Type*} {β : ι → Type*} (r : ι → ι → Prop)
(s : Π {i}, β i → β i → Prop)
/-- The lexicographic relation on `Π i : ι, β i`, where `ι` is ordered by `r`,
and each `β i` is ordered by `s`. -/
def pi.lex (x y : Π i, β i) : Prop :=
∃ i, (∀ j, r j i → x j = y j) ∧ s (x i) (y i)
/-- The cartesian product of an indexed family, equipped with the lexicographic order. -/
def pilex (α : Type*) (β : α → Type*) : Type* := Π a, β a
instance [has_lt ι] [∀ a, has_lt (β a)] : has_lt (pilex ι β) :=
{ lt := pi.lex (<) (λ _, (<)) }
instance [∀ a, inhabited (β a)] : inhabited (pilex ι β) :=
by unfold pilex; apply_instance
instance pilex.is_strict_order [linear_order ι] [∀ a, partial_order (β a)] :
is_strict_order (pilex ι β) (<) :=
{ irrefl := λ a ⟨k, hk₁, hk₂⟩, lt_irrefl (a k) hk₂,
trans :=
begin
rintro a b c ⟨N₁, lt_N₁, a_lt_b⟩ ⟨N₂, lt_N₂, b_lt_c⟩,
rcases lt_trichotomy N₁ N₂ with (H|rfl|H),
exacts [⟨N₁, λ j hj, (lt_N₁ _ hj).trans (lt_N₂ _ $ hj.trans H), lt_N₂ _ H ▸ a_lt_b⟩,
⟨N₁, λ j hj, (lt_N₁ _ hj).trans (lt_N₂ _ hj), a_lt_b.trans b_lt_c⟩,
⟨N₂, λ j hj, (lt_N₁ _ (hj.trans H)).trans (lt_N₂ _ hj), (lt_N₁ _ H).symm ▸ b_lt_c⟩]
end }
instance [linear_order ι] [∀ a, partial_order (β a)] : partial_order (pilex ι β) :=
partial_order_of_SO (<)
protected lemma pilex.is_strict_total_order' [linear_order ι]
(wf : well_founded ((<) : ι → ι → Prop)) [∀ a, linear_order (β a)] :
is_strict_total_order' (pilex ι β) (<) :=
{ trichotomous := λ a b,
begin
by_cases h : ∃ i, a i ≠ b i,
{ let i := wf.min _ h,
have hlt_i : ∀ j < i, a j = b j,
{ intro j, rw ← not_imp_not,
exact λ h', wf.not_lt_min _ _ h' },
have : a i ≠ b i, from wf.min_mem _ h,
exact this.lt_or_lt.imp (λ h, ⟨i, hlt_i, h⟩)
(λ h, or.inr ⟨i, λ j hj, (hlt_i j hj).symm, h⟩) },
{ push_neg at h, exact or.inr (or.inl (funext h)) }
end }
/-- `pilex` is a linear order if the original order is well-founded.
This cannot be an instance, since it depends on the well-foundedness of `<`. -/
protected noncomputable def pilex.linear_order [linear_order ι]
(wf : well_founded ((<) : ι → ι → Prop)) [∀ a, linear_order (β a)] :
linear_order (pilex ι β) :=
@linear_order_of_STO' (pilex ι β) (<) (pilex.is_strict_total_order' wf) (classical.dec_rel _)
lemma pilex.le_of_forall_le [linear_order ι]
(wf : well_founded ((<) : ι → ι → Prop)) [∀ a, linear_order (β a)] {a b : pilex ι β}
(h : ∀ i, a i ≤ b i) : a ≤ b :=
begin
letI : linear_order (pilex ι β) := pilex.linear_order wf,
exact le_of_not_lt (λ ⟨i, hi⟩, (h i).not_lt hi.2)
end
--we might want the analog of `pi.ordered_cancel_comm_monoid` as well in the future
@[to_additive]
instance [linear_order ι] [∀ a, ordered_comm_group (β a)] :
ordered_comm_group (pilex ι β) :=
{ mul_le_mul_left := λ x y hxy z,
hxy.elim
(λ hxyz, hxyz ▸ le_refl _)
(λ ⟨i, hi⟩,
or.inr ⟨i, λ j hji, show z j * x j = z j * y j, by rw hi.1 j hji,
mul_lt_mul_left' hi.2 _⟩),
..pilex.partial_order,
..pi.comm_group }
|
57538d75678eae6446fc14235e06022c1ba699ec | 367134ba5a65885e863bdc4507601606690974c1 | /src/ring_theory/polynomial/homogeneous.lean | cf6c82c759c372e8c0167187aaaf10bb9e0e67a9 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 8,061 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.mv_polynomial
import data.fintype.card
/-!
# Homogeneous polynomials
A multivariate polynomial `φ` is homogeneous of degree `n`
if all monomials occuring in `φ` have degree `n`.
## Main definitions/lemmas
* `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`.
* `homogeneous_component n`: the additive morphism that projects polynomials onto
their summand that is homogeneous of degree `n`.
* `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components
-/
open_locale big_operators
namespace mv_polynomial
variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*}
/-
TODO
* create definition for `∑ i in d.support, d i`
* define graded rings, and show that mv_polynomial is an example
-/
/-- A multivariate polynomial `φ` is homogeneous of degree `n`
if all monomials occuring in `φ` have degree `n`. -/
def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) :=
∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n
section
variables [comm_semiring R]
variables {σ R}
lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) :
is_homogeneous (monomial d r) n :=
begin
intros c hc,
rw coeff_monomial at hc,
split_ifs at hc with h,
{ subst c, exact hn },
{ contradiction }
end
variables (σ) {R}
lemma is_homogeneous_C (r : R) :
is_homogeneous (C r : mv_polynomial σ R) 0 :=
begin
apply is_homogeneous_monomial,
simp only [finsupp.zero_apply, finset.sum_const_zero],
end
variables (σ R)
lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n :=
λ d hd, false.elim (hd $ coeff_zero _)
lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 :=
is_homogeneous_C _ _
variables {σ} (R)
lemma is_homogeneous_X (i : σ) :
is_homogeneous (X i : mv_polynomial σ R) 1 :=
begin
apply is_homogeneous_monomial,
simp only [finsupp.support_single_ne_zero one_ne_zero, finset.sum_singleton],
exact finsupp.single_eq_same
end
end
namespace is_homogeneous
variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ}
lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) :
coeff d φ = 0 :=
by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux }
lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) :
m = n :=
begin
obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ,
rw [← hm hd, ← hn hd]
end
lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) :
is_homogeneous (φ + ψ) n :=
begin
intros c hc,
rw coeff_add at hc,
obtain h|h : coeff c φ ≠ 0 ∨ coeff c ψ ≠ 0,
{ contrapose! hc, simp only [hc, add_zero] },
{ exact hφ h },
{ exact hψ h }
end
lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ)
(h : ∀ i ∈ s, is_homogeneous (φ i) n) :
is_homogeneous (∑ i in s, φ i) n :=
begin
classical,
revert h,
apply finset.induction_on s,
{ intro, simp only [is_homogeneous_zero, finset.sum_empty] },
{ intros i s his IH h,
simp only [his, finset.sum_insert, not_false_iff],
apply (h i (finset.mem_insert_self _ _)).add (IH _),
intros j hjs,
exact h j (finset.mem_insert_of_mem hjs) }
end
lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) :
is_homogeneous (φ * ψ) (m + n) :=
begin
intros c hc,
rw [coeff_mul] at hc,
obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc,
have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0,
{ contrapose! H,
by_cases h : coeff d φ = 0;
simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * },
specialize hφ aux.1, specialize hψ aux.2,
rw finsupp.mem_antidiagonal_support at hde,
classical,
have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _,
have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _,
rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add),
finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib],
{ congr },
all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }
end
lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ)
(h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) :
is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) :=
begin
classical,
revert h,
apply finset.induction_on s,
{ intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] },
{ intros i s his IH h,
simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff],
apply (h i (finset.mem_insert_self _ _)).mul (IH _),
intros j hjs,
exact h j (finset.mem_insert_of_mem hjs) }
end
lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) :
total_degree φ = n :=
begin
rw total_degree,
apply le_antisymm,
{ apply finset.sup_le,
intros d hd,
rw mem_support_iff at hd,
rw [finsupp.sum, hφ hd], },
{ obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h,
simp only [← hφ hd, finsupp.sum],
replace hd := finsupp.mem_support_iff.mpr hd,
exact finset.le_sup hd, }
end
end is_homogeneous
section
noncomputable theory
open_locale classical
open finset
/-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`.
See `sum_homogeneous_component` for the statement that `φ` is equal to the sum
of all its homogeneous components. -/
def homogeneous_component [comm_semiring R] (n : ℕ) :
mv_polynomial σ R →ₗ[R] mv_polynomial σ R :=
(submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n}
section homogeneous_component
open finset
variables [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R)
lemma coeff_homogeneous_component (d : σ →₀ ℕ) :
coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 :=
by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d
lemma homogeneous_component_apply :
homogeneous_component n φ =
∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) :=
by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ
lemma homogeneous_component_is_homogeneous :
(homogeneous_component n φ).is_homogeneous n :=
begin
intros d hd,
contrapose! hd,
rw [coeff_homogeneous_component, if_neg hd]
end
lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) :=
begin
ext1 d,
rcases em (d = 0) with (rfl|hd),
{ simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.coe_zero, if_true, coeff_C,
eq_self_iff_true, forall_true_iff] },
{ rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)],
simp only [finsupp.ext_iff, finsupp.zero_apply] at hd,
simp [hd] }
end
lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) :
homogeneous_component n φ = 0 :=
begin
rw [homogeneous_component_apply, sum_eq_zero],
intros d hd, rw mem_filter at hd,
exfalso, exact h _ hd.1 hd.2
end
lemma homogeneous_component_eq_zero (h : φ.total_degree < n) :
homogeneous_component n φ = 0 :=
begin
apply homogeneous_component_eq_zero',
rw [total_degree, finset.sup_lt_iff] at h,
{ intros d hd, exact ne_of_lt (h d hd), },
{ exact lt_of_le_of_lt (nat.zero_le _) h, }
end
lemma sum_homogeneous_component :
∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ :=
begin
ext1 d,
suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ,
by simpa [coeff_sum, coeff_homogeneous_component],
exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm
end
end homogeneous_component
end
end mv_polynomial
|
a110c23d45d050648deebb7d19a400f2589c4fba | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/filter/partial_auto.lean | 1f48fe69f5be1f42822a85746f45e2cd6ab0845d | [] | 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,718 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Extends `tendsto` to relations and partial functions.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.filter.basic
import Mathlib.PostPort
universes u v w
namespace Mathlib
namespace filter
/-
Relations.
-/
def rmap {α : Type u} {β : Type v} (r : rel α β) (f : filter α) : filter β :=
mk (set_of fun (s : set β) => rel.core r s ∈ f) sorry sorry sorry
theorem rmap_sets {α : Type u} {β : Type v} (r : rel α β) (f : filter α) :
sets (rmap r f) = rel.core r ⁻¹' sets f :=
rfl
@[simp] theorem mem_rmap {α : Type u} {β : Type v} (r : rel α β) (l : filter α) (s : set β) :
s ∈ rmap r l ↔ rel.core r s ∈ l :=
iff.rfl
@[simp] theorem rmap_rmap {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ)
(l : filter α) : rmap s (rmap r l) = rmap (rel.comp r s) l :=
sorry
@[simp] theorem rmap_compose {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ) :
rmap s ∘ rmap r = rmap (rel.comp r s) :=
funext (rmap_rmap r s)
def rtendsto {α : Type u} {β : Type v} (r : rel α β) (l₁ : filter α) (l₂ : filter β) :=
rmap r l₁ ≤ l₂
theorem rtendsto_def {α : Type u} {β : Type v} (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto r l₁ l₂ ↔ ∀ (s : set β), s ∈ l₂ → rel.core r s ∈ l₁ :=
iff.rfl
def rcomap {α : Type u} {β : Type v} (r : rel α β) (f : filter β) : filter α :=
mk (rel.image (fun (s : set β) (t : set α) => rel.core r s ⊆ t) (sets f)) sorry sorry sorry
theorem rcomap_sets {α : Type u} {β : Type v} (r : rel α β) (f : filter β) :
sets (rcomap r f) = rel.image (fun (s : set β) (t : set α) => rel.core r s ⊆ t) (sets f) :=
rfl
@[simp] theorem rcomap_rcomap {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ)
(l : filter γ) : rcomap r (rcomap s l) = rcomap (rel.comp r s) l :=
sorry
@[simp] theorem rcomap_compose {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ) :
rcomap r ∘ rcomap s = rcomap (rel.comp r s) :=
funext (rcomap_rcomap r s)
theorem rtendsto_iff_le_comap {α : Type u} {β : Type v} (r : rel α β) (l₁ : filter α)
(l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ rcomap r l₂ :=
sorry
-- Interestingly, there does not seem to be a way to express this relation using a forward map.
-- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if
-- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty.
def rcomap' {α : Type u} {β : Type v} (r : rel α β) (f : filter β) : filter α :=
mk (rel.image (fun (s : set β) (t : set α) => rel.preimage r s ⊆ t) (sets f)) sorry sorry sorry
@[simp] theorem mem_rcomap' {α : Type u} {β : Type v} (r : rel α β) (l : filter β) (s : set α) :
s ∈ rcomap' r l ↔ ∃ (t : set β), ∃ (H : t ∈ l), rel.preimage r t ⊆ s :=
iff.rfl
theorem rcomap'_sets {α : Type u} {β : Type v} (r : rel α β) (f : filter β) :
sets (rcomap' r f) = rel.image (fun (s : set β) (t : set α) => rel.preimage r s ⊆ t) (sets f) :=
rfl
@[simp] theorem rcomap'_rcomap' {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ)
(l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (rel.comp r s) l :=
sorry
@[simp] theorem rcomap'_compose {α : Type u} {β : Type v} {γ : Type w} (r : rel α β) (s : rel β γ) :
rcomap' r ∘ rcomap' s = rcomap' (rel.comp r s) :=
funext (rcomap'_rcomap' r s)
def rtendsto' {α : Type u} {β : Type v} (r : rel α β) (l₁ : filter α) (l₂ : filter β) :=
l₁ ≤ rcomap' r l₂
theorem rtendsto'_def {α : Type u} {β : Type v} (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto' r l₁ l₂ ↔ ∀ (s : set β), s ∈ l₂ → rel.preimage r s ∈ l₁ :=
sorry
theorem tendsto_iff_rtendsto {α : Type u} {β : Type v} (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ :=
sorry
theorem tendsto_iff_rtendsto' {α : Type u} {β : Type v} (l₁ : filter α) (l₂ : filter β)
(f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ :=
sorry
/-
Partial functions.
-/
def pmap {α : Type u} {β : Type v} (f : α →. β) (l : filter α) : filter β := rmap (pfun.graph' f) l
@[simp] theorem mem_pmap {α : Type u} {β : Type v} (f : α →. β) (l : filter α) (s : set β) :
s ∈ pmap f l ↔ pfun.core f s ∈ l :=
iff.rfl
def ptendsto {α : Type u} {β : Type v} (f : α →. β) (l₁ : filter α) (l₂ : filter β) :=
pmap f l₁ ≤ l₂
theorem ptendsto_def {α : Type u} {β : Type v} (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto f l₁ l₂ ↔ ∀ (s : set β), s ∈ l₂ → pfun.core f s ∈ l₁ :=
iff.rfl
theorem ptendsto_iff_rtendsto {α : Type u} {β : Type v} (l₁ : filter α) (l₂ : filter β)
(f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto (pfun.graph' f) l₁ l₂ :=
iff.rfl
theorem pmap_res {α : Type u} {β : Type v} (l : filter α) (s : set α) (f : α → β) :
pmap (pfun.res f s) l = map f (l ⊓ principal s) :=
sorry
theorem tendsto_iff_ptendsto {α : Type u} {β : Type v} (l₁ : filter α) (l₂ : filter β) (s : set α)
(f : α → β) : tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ :=
sorry
theorem tendsto_iff_ptendsto_univ {α : Type u} {β : Type v} (l₁ : filter α) (l₂ : filter β)
(f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ :=
sorry
def pcomap' {α : Type u} {β : Type v} (f : α →. β) (l : filter β) : filter α :=
rcomap' (pfun.graph' f) l
def ptendsto' {α : Type u} {β : Type v} (f : α →. β) (l₁ : filter α) (l₂ : filter β) :=
l₁ ≤ rcomap' (pfun.graph' f) l₂
theorem ptendsto'_def {α : Type u} {β : Type v} (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto' f l₁ l₂ ↔ ∀ (s : set β), s ∈ l₂ → pfun.preimage f s ∈ l₁ :=
rtendsto'_def (pfun.graph' f) l₁ l₂
theorem ptendsto_of_ptendsto' {α : Type u} {β : Type v} {f : α →. β} {l₁ : filter α}
{l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ :=
sorry
theorem ptendsto'_of_ptendsto {α : Type u} {β : Type v} {f : α →. β} {l₁ : filter α} {l₂ : filter β}
(h : pfun.dom f ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ :=
sorry
end Mathlib |
c734f11ed00ccb1c8026e4130fa84e92646f0e07 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /src/Init/Data/String/Basic.lean | ce463f91e46e217df228d636b4bd0913b3359d7f | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 15,597 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.List.Basic
import Init.Data.Char.Basic
import Init.Data.Option.Basic
universes u
structure String :=
(data : List Char)
abbrev String.Pos := Nat
structure Substring :=
(str : String) (startPos : String.Pos) (stopPos : String.Pos)
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (s₁ s₂ : @& String) : Decidable (s₁ = s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
if h : s₁ = s₂ then isTrue (congrArg _ h)
else isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))
instance : DecidableEq String :=
String.decEq
def List.asString (s : List Char) : String :=
⟨s⟩
namespace String
instance : HasLess String :=
⟨fun s₁ s₂ => s₁.data < s₂.data⟩
@[extern "lean_string_dec_lt"]
instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) :=
List.hasDecidableLt s₁.data s₂.data
@[extern "lean_string_length"]
def length : (@& String) → Nat
| ⟨s⟩ => s.length
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_push"]
def push : String → Char → String
| ⟨s⟩, c => ⟨s ++ [c]⟩
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_append"]
def append : String → (@& String) → String
| ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩
/- O(n) in the runtime, where n is the length of the String -/
def toList (s : String) : List Char :=
s.data
private def csize (c : Char) : Nat :=
c.utf8Size.toNat
private def utf8ByteSizeAux : List Char → Nat → Nat
| [], r => r
| c::cs, r => utf8ByteSizeAux cs (r + csize c)
@[extern "lean_string_utf8_byte_size"]
def utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def toSubstring (s : String) : Substring :=
{str := s, startPos := 0, stopPos := s.bsize}
private def utf8GetAux : List Char → Pos → Pos → Char
| [], i, p => arbitrary Char
| c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p
@[extern "lean_string_utf8_get"]
def get : (@& String) → (@& Pos) → Char
| ⟨s⟩, p => utf8GetAux s 0 p
private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char
| [], i, p => []
| c::cs, i, p =>
if i = p then (c'::cs) else c::(utf8SetAux cs (i + csize c) p)
@[extern "lean_string_utf8_set"]
def set : String → (@& Pos) → Char → String
| ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩
def modify (s : String) (i : Pos) (f : Char → Char) : String :=
s.set i $ f $ s.get i
@[extern "lean_string_utf8_next"]
def next (s : @& String) (p : @& Pos) : Pos :=
let c := get s p;
p + csize c
private def utf8PrevAux : List Char → Pos → Pos → Pos
| [], i, p => 0
| c::cs, i, p =>
let cz := csize c;
let i' := i + cz;
if i' = p then i else utf8PrevAux cs i' p
@[extern "lean_string_utf8_prev"]
def prev : (@& String) → (@& Pos) → Pos
| ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p
def front (s : String) : Char :=
get s 0
def back (s : String) : Char :=
get s (prev s (bsize s))
@[extern "lean_string_utf8_at_end"]
def atEnd : (@& String) → (@& Pos) → Bool
| s, p => p ≥ utf8ByteSize s
/- TODO: remove `partial` keywords after we restore the tactic
framework and wellfounded recursion support -/
partial def posOfAux (s : String) (c : Char) (stopPos : Pos) : Pos → Pos
| pos =>
if pos == stopPos then pos
else if s.get pos == c then pos
else posOfAux (s.next pos)
@[inline] def posOf (s : String) (c : Char) : Pos :=
posOfAux s c s.bsize 0
partial def revPosOfAux (s : String) (c : Char) : Pos → Option Pos
| pos =>
if s.get pos == c then some pos
else if pos == 0 then none
else revPosOfAux (s.prev pos)
def revPosOf (s : String) (c : Char) : Option Pos :=
if s.bsize == 0 then none
else revPosOfAux s c (s.prev s.bsize)
private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char
| [], _, _ => []
| c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e
private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char
| [], _, _, _ => []
| s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e
@[extern "lean_string_utf8_extract"]
def extract : (@& String) → (@& Pos) → (@& Pos) → String
| ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩
@[specialize] partial def splitAux (s : String) (p : Char → Bool) : Pos → Pos → List String → List String
| b, i, r =>
if s.atEnd i then
let r := if p (s.get i) then ""::(s.extract b (i-1))::r else (s.extract b i)::r;
r.reverse
else if p (s.get i) then
let i := s.next i;
splitAux i i (s.extract b (i-1)::r)
else splitAux b (s.next i) r
@[specialize] def split (s : String) (p : Char → Bool) : List String :=
splitAux s p 0 0 []
partial def splitOnAux (s sep : String) : Pos → Pos → Pos → List String → List String
| b, i, j, r =>
if s.atEnd i then
let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 (s.extract b (i-j)::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : String) (sep : String := " ") : List String :=
if sep == "" then [s] else splitOnAux s sep 0 0 0 []
instance : Inhabited String :=
⟨""⟩
instance : HasSizeof String :=
⟨String.length⟩
instance : HasAppend String :=
⟨String.append⟩
def str : String → Char → String := push
def pushn (s : String) (c : Char) (n : Nat) : String :=
n.repeat (fun s => s.push c) s
def isEmpty (s : String) : Bool :=
s.bsize == 0
def join (l : List String) : String :=
l.foldl (fun r s => r ++ s) ""
def singleton (c : Char) : String :=
"".push c
def intercalate (s : String) (ss : List String) : String :=
(List.intercalate s.toList (ss.map toList)).asString
structure Iterator :=
(s : String) (i : Pos)
def mkIterator (s : String) : Iterator :=
⟨s, 0⟩
namespace Iterator
def toString : Iterator → String
| ⟨s, _⟩ => s
def remainingBytes : Iterator → Nat
| ⟨s, i⟩ => s.bsize - i
def pos : Iterator → Pos
| ⟨s, i⟩ => i
def curr : Iterator → Char
| ⟨s, i⟩ => get s i
def next : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.next i⟩
def prev : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.prev i⟩
def hasNext : Iterator → Bool
| ⟨s, i⟩ => i < utf8ByteSize s
def hasPrev : Iterator → Bool
| ⟨s, i⟩ => i > 0
def setCurr : Iterator → Char → Iterator
| ⟨s, i⟩, c => ⟨s.set i c, i⟩
def toEnd : Iterator → Iterator
| ⟨s, _⟩ => ⟨s, s.bsize⟩
def extract : Iterator → Iterator → String
| ⟨s₁, b⟩, ⟨s₂, e⟩ =>
if s₁ ≠ s₂ || b > e then ""
else s₁.extract b e
def forward : Iterator → Nat → Iterator
| it, 0 => it
| it, n+1 => forward it.next n
def remainingToString : Iterator → String
| ⟨s, i⟩ => s.extract i s.bsize
/- (isPrefixOfRemaining it₁ it₂) is `true` Iff `it₁.remainingToString` is a prefix
of `it₂.remainingToString`. -/
def isPrefixOfRemaining : Iterator → Iterator → Bool
| ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁))
def nextn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => nextn it.next i
def prevn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => prevn it.prev i
end Iterator
partial def offsetOfPosAux (s : String) (pos : Pos) : Pos → Nat → Nat
| i, offset =>
if i == pos || s.atEnd i then offset
else offsetOfPosAux (s.next i) (offset+1)
def offsetOfPos (s : String) (pos : Pos) : Nat :=
offsetOfPosAux s pos 0 0
@[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) : Pos → α → α
| i, a =>
if i == stopPos then a
else foldlAux (s.next i) (f a (s.get i))
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α :=
foldlAux f s s.bsize 0 a
@[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) : Pos → α
| i =>
if i == stopPos then a
else f (s.get i) (foldrAux (s.next i))
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α :=
foldrAux f a s s.bsize 0
@[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) : Pos → Bool
| i =>
if i == stopPos then false
else if p (s.get i) then true
else anyAux (s.next i)
@[inline] def any (s : String) (p : Char → Bool) : Bool :=
anyAux s s.bsize p 0
@[inline] def all (s : String) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : String) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def mapAux (f : Char → Char) : Pos → String → String
| i, s =>
if s.atEnd i then s
else
let c := f (s.get i);
let s := s.set i c;
mapAux (s.next i) s
@[inline] def map (f : Char → Char) (s : String) : String :=
mapAux f 0 s
def isNat (s : String) : Bool :=
s.all $ fun c => c.isDigit
def toNat? (s : String) : Option Nat :=
if s.isNat then
some $ s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
else
none
partial def isPrefixOfAux (p s : String) : Pos → Bool
| i =>
if p.atEnd i then true
else
let c₁ := p.get i;
let c₂ := s.get i;
c₁ == c₂ && isPrefixOfAux (s.next i)
/- Return true iff `p` is a prefix of `s` -/
def isPrefixOf (p : String) (s : String) : Bool :=
p.length ≤ s.length && isPrefixOfAux p s 0
end String
namespace Substring
@[inline] def toString : Substring → String
| ⟨s, b, e⟩ => s.extract b e
@[inline] def toIterator : Substring → String.Iterator
| ⟨s, b, _⟩ => ⟨s, b⟩
@[inline] def get : Substring → String.Pos → Char
| ⟨s, b, _⟩, p => s.get (b+p)
@[inline] def next : Substring → String.Pos → String.Pos
| ⟨s, b, e⟩, p =>
let p := s.next (b+p);
if p > e then e - b else p - b
@[inline] def prev : Substring → String.Pos → String.Pos
| ⟨s, b, _⟩, p =>
if p = b then p else s.prev (b+p) - b
@[inline] def front (s : Substring) : Char :=
s.get 0
@[inline] def posOf (s : Substring) (c : Char) : String.Pos :=
match s with
| ⟨s, b, e⟩ => (String.posOfAux s c e b) - b
@[inline] def drop : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if b + n ≥ e then "".toSubstring
else ⟨s, b+n, e⟩
@[inline] def dropRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if e - n ≤ b then "".toSubstring
else ⟨s, b, e - n⟩
@[inline] def take : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let e := if b + n ≥ e then e else b + n;
⟨s, b, e⟩
@[inline] def takeRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let b := if e - n ≤ b then b else e - n;
⟨s, b, e⟩
@[inline] def atEnd : Substring → String.Pos → Bool
| ⟨s, b, e⟩, p => b + p == e
@[inline] def extract : Substring → String.Pos → String.Pos → Substring
| ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩
partial def splitOnAux (s sep : String) (stopPos : String.Pos) : String.Pos → String.Pos → String.Pos → List Substring → List Substring
| b, i, j, r =>
if i == stopPos then
let r := if sep.atEnd j then "".toSubstring::{str := s, startPos := b, stopPos := i-j}::r else {str := s, startPos := b, stopPos := i}::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 ({str := s, startPos := b, stopPos := i-j}::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : Substring) (sep : String := " ") : List Substring :=
if sep == "" then [s] else splitOnAux s.str sep s.stopPos s.startPos s.startPos 0 []
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldlAux f s e b a
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldrAux f a s e b
@[inline] def any (s : Substring) (p : Char → Bool) : Bool :=
match s with
| ⟨s, b, e⟩ => String.anyAux s e p b
@[inline] def all (s : Substring) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : Substring) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == stopPos then i
else if p (s.get i) then takeWhileAux (s.next i)
else i
@[inline] def takeWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeWhileAux s e p b;
⟨s, b, e⟩
@[inline] def dropWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeWhileAux s e p b;
⟨s, b, e⟩
@[specialize] partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == begPos then i
else
let i' := s.prev i;
let c := s.get i';
if !p c then i
else takeRightWhileAux i'
@[inline] def takeRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def dropRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def trimLeft (s : Substring) : Substring :=
s.dropWhile Char.isWhitespace
@[inline] def trimRight (s : Substring) : Substring :=
s.dropRightWhile Char.isWhitespace
@[inline] def trim : Substring → Substring
| ⟨s, b, e⟩ =>
let b := takeWhileAux s e Char.isWhitespace b;
let e := takeRightWhileAux s b Char.isWhitespace e;
⟨s, b, e⟩
def isNat (s : Substring) : Bool :=
s.all $ fun c => c.isDigit
def toNat? (s : Substring) : Option Nat :=
if s.isNat then
some $ s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
else
none
end Substring
namespace String
def drop (s : String) (n : Nat) : String :=
(s.toSubstring.drop n).toString
def dropRight (s : String) (n : Nat) : String :=
(s.toSubstring.dropRight n).toString
def take (s : String) (n : Nat) : String :=
(s.toSubstring.take n).toString
def takeRight (s : String) (n : Nat) : String :=
(s.toSubstring.takeRight n).toString
def takeWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.takeWhile p).toString
def dropWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.dropWhile p).toString
def trimRight (s : String) : String :=
s.toSubstring.trimRight.toString
def trimLeft (s : String) : String :=
s.toSubstring.trimLeft.toString
def trim (s : String) : String :=
s.toSubstring.trim.toString
@[inline] def nextWhile (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos :=
Substring.takeWhileAux s s.bsize p i
@[inline] def nextUntil (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos :=
nextWhile s (fun c => !p c) i
end String
protected def Char.toString (c : Char) : String :=
String.singleton c
|
5a3a06e5ca6d2b7c26d6fcc10a336a7dd5f86aea | 4727251e0cd73359b15b664c3170e5d754078599 | /src/number_theory/lucas_lehmer.lean | cbef60a48fff04d74c25a32e835d4746b2e20dda | [
"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 | 17,261 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison, Ainsley Pahljina
-/
import data.nat.parity
import data.pnat.interval
import data.zmod.basic
import group_theory.order_of_element
import ring_theory.fintype
import tactic.interval_cases
import tactic.ring_exp
/-!
# The Lucas-Lehmer test for Mersenne primes.
We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and
prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`.
We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic
required to calculate the residue, and enables us to prove
```
example : prime (mersenne 127) :=
lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test)
```
## TODO
- Show reverse implication.
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Scott Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ := 2^p - 1
lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p :=
begin
dsimp [mersenne],
calc 0 < 2^1 - 1 : by norm_num
... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h)
end
@[simp]
lemma succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k :=
begin
rw [mersenne, tsub_add_cancel_of_le],
exact one_le_pow_of_one_le (by norm_num) k
end
namespace lucas_lehmer
open nat
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ
| 0 := 4
| (i+1) := (s i)^2 - 2
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/
def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1)
| 0 := 4
| (i+1) := (s_zmod i)^2 - 2
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def s_mod (p : ℕ) : ℕ → ℤ
| 0 := 4 % (2^p - 1)
| (i+1) := ((s_mod i)^2 - 2) % (2^p - 1)
lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 :=
begin
apply ne_of_gt, simp only [gt_iff_lt, sub_pos],
exact_mod_cast nat.one_lt_two_pow p w,
end
lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i :=
begin
cases i; dsimp [s_mod],
{ exact sup_eq_left.mp rfl },
{ apply int.mod_nonneg, exact mersenne_int_ne_zero p w },
end
lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i :=
by cases i; simp [s_mod]
lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 :=
begin
rw ←s_mod_mod,
convert int.mod_lt _ _,
{ refine (abs_of_nonneg _).symm,
simp only [sub_nonneg, ge_iff_le],
exact_mod_cast nat.one_le_two_pow p, },
{ exact mersenne_int_ne_zero p w, },
end
lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):=
begin
induction i with i ih,
{ dsimp [s, s_zmod], norm_num, },
{ push_cast [s, s_zmod, ih] },
end
-- These next two don't make good `norm_cast` lemmas.
lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) :=
begin
have : 1 ≤ b^p := nat.one_le_pow p b w,
push_cast [this],
end
lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) :=
int.coe_nat_pow_pred 2 p dec_trivial
lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) :=
by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *]
/-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/
def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2)
lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) :
lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 :=
begin
dsimp [lucas_lehmer_residue],
rw s_zmod_eq_s_mod p,
split,
{ -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1`
-- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`.
intro h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h,
apply s_mod_nonneg _ (nat.lt_of_succ_lt w),
convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2),
push_cast [nat.one_le_two_pow p],
refl, },
{ intro h, rw h, simp, },
end
/--
A Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
@[derive decidable_pred]
def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩
local attribute [instance]
lemma fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := ⟨q.2⟩
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
@[derive [add_comm_group, decidable_eq, fintype, inhabited]]
def X (q : ℕ+) : Type := (zmod q) × (zmod q)
namespace X
variable {q : ℕ+}
@[ext]
lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y :=
begin
cases x, cases y,
congr; assumption
end
@[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl
@[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl
@[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl
@[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl
instance : has_mul (X q) :=
{ mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) }
@[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl
@[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl
instance : has_one (X q) :=
{ one := ⟨1,0⟩ }
@[simp] lemma one_fst : (1 : X q).1 = 1 := rfl
@[simp] lemma one_snd : (1 : X q).2 = 0 := rfl
@[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl
@[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl
@[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl
@[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, }
instance : monoid (X q) :=
{ mul_assoc := λ x y z, by { ext; { dsimp, ring }, },
one := ⟨1,0⟩,
one_mul := λ x, by { ext; simp, },
mul_one := λ x, by { ext; simp, },
..(infer_instance : has_mul (X q)) }
lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z :=
by { ext; { dsimp, ring }, }
lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z :=
by { ext; { dsimp, ring }, }
instance : ring (X q) :=
{ left_distrib := left_distrib,
right_distrib := right_distrib,
..(infer_instance : add_comm_group (X q)),
..(infer_instance : monoid (X q)) }
instance : comm_ring (X q) :=
{ mul_comm := λ x y, by { ext; { dsimp, ring }, },
..(infer_instance : ring (X q))}
instance [fact (1 < (q : ℕ))] : nontrivial (X q) :=
⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩
@[simp]
lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) :=
begin
induction n,
{ refl, },
{ dsimp, simp only [add_left_inj], exact n_ih, }
end
@[simp]
lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) :=
begin
induction n,
{ refl, },
{ dsimp, simp only [add_zero], exact n_ih, }
end
@[simp]
lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) :=
by { induction n; simp, }
@[simp]
lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) :=
by { induction n; simp, }
@[norm_cast]
lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) :=
by { ext; simp; ring }
@[norm_cast]
lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) :=
by { ext; simp, }
/-- The cardinality of `X` is `q^2`. -/
lemma X_card : fintype.card (X q) = q^2 :=
begin
dsimp [X],
rw [fintype.card_prod, zmod.card q],
ring,
end
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
lemma units_card (w : 1 < q) : fintype.card ((X q)ˣ) < q^2 :=
begin
haveI : fact (1 < (q:ℕ)) := ⟨w⟩,
convert card_units_lt (X q),
rw X_card,
end
/-- We define `ω = 2 + √3`. -/
def ω : X q := (2, 1)
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ωb : X q := (2, -1)
lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
/-- A closed form for the recurrence relation. -/
lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) :=
begin
induction i with i ih,
{ dsimp [s, ω, ωb],
ext; { simp; refl, }, },
{ calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl
... = ((s i : X q)^2 - 2) : by push_cast
... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih
... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring
... = (ω^(2^i))^2 + (ωb^(2^i))^2 :
by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel]
... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] }
end
end X
open X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin
by_contradiction H,
simp at H,
interval_cases q (p'+2); clear H,
{ -- If q = 1, we get a contradiction from 2^p = 2
dsimp [q] at h, injection h with h', clear h,
simp [mersenne] at h',
exact lt_irrefl 2
(calc 2 ≤ p'+2 : nat.le_add_left _ _
... < 2^(p'+2) : nat.lt_two_pow _
... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), },
{ -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1
dsimp [q] at h, injection h with h', clear h,
rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h',
exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', }
end
theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) =
k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 :=
begin
dsimp [lucas_lehmer_residue] at h,
rw s_zmod_eq_s p' at h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
cases h with k h,
use k,
replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q
dsimp at h,
rw closed_form at h,
replace h := congr_arg (λ x, ω^2^p' * x) h,
dsimp at h,
have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp,
rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h,
rw [mul_comm, coe_mul] at h,
rw [mul_comm _ (k : X (q (p'+2)))] at h,
replace h := eq_sub_of_add_eq h,
exact_mod_cast h,
end
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 :=
begin
ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos],
apply nat.min_fac_dvd,
end
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+1)) = -1 :=
begin
cases ω_pow_formula p' h with k w,
rw [mersenne_coe_X] at w,
simpa using w,
end
theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+2)) = 1 :=
calc (ω : X (q (p'+2)))^2^(p'+2)
= (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ']
... = (-1)^2 : by rw ω_pow_eq_neg_one p' h
... = 1 : by simp
/-- `ω` as an element of the group of units. -/
def ω_unit (p : ℕ) : units (X (q p)) :=
{ val := ω,
inv := ωb,
val_inv := by simp [ω_mul_ωb],
inv_val := by simp [ωb_mul_ω], }
@[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
order_of (ω_unit (p'+2)) = 2^(p'+2) :=
begin
apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p
{ norm_num, },
{ intro o,
have ω_pow := order_of_dvd_iff_pow_eq_one.1 o,
replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) :
units (X (q (p'+2))) → X (q (p'+2))) ω_pow,
simp at ω_pow,
have h : (1 : zmod (q (p'+2))) = -1 :=
congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)),
haveI : fact (2 < (q (p'+2) : ℕ)) := ⟨two_lt_q _⟩,
apply zmod.neg_one_ne_one h.symm, },
{ apply order_of_dvd_iff_pow_eq_one.2,
apply units.ext,
push_cast,
exact ω_pow_eq_one p' h, }
end
lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 :=
calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm
... ≤ fintype.card ((X _)ˣ) : order_of_le_card_univ
... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _))
end lucas_lehmer
export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue)
open lucas_lehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime :=
begin
let p' := p - 2,
have z : p = p' + 2 := (tsub_eq_iff_eq_add_of_le w.nat_succ_le).mp rfl,
have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl),
contrapose,
intros a t,
rw z at a,
rw z at t,
have h₁ := order_ineq p' t,
have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a,
have h := lt_of_lt_of_le h₁ h₂,
exact not_lt_of_ge (nat.sub_le _ _) h,
end
-- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better.
example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial
-- Next we use `norm_num` to calculate each `s p i`.
namespace lucas_lehmer
open tactic
meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩
meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩
lemma s_mod_succ {p a i b c}
(h1 : (2^p - 1 : ℤ) = a)
(h2 : s_mod p i = b)
(h3 : (b * b - 2) % a = c) :
s_mod p (i+1) = c :=
by { dsimp [s_mod, mersenne], rw [h1, h2, sq, h3] }
/--
Given a goal of the form `lucas_lehmer_test p`,
attempt to do the calculation using `norm_num` to certify each step.
-/
meta def run_test : tactic unit :=
do `(lucas_lehmer_test %%p) ← target,
`[dsimp [lucas_lehmer_test]],
`[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num],
p ← eval_expr ℕ p,
-- Calculate the candidate Mersenne prime
let M : ℤ := 2^p - 1,
t ← to_expr ``(2^%%p - 1 = %%M),
v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M),
w ← assertv `w t v,
-- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`.
-- We could make a better `has_to_pexpr ℤ` instance, or just:
`[simp only [int.coe_nat_zero, int.coe_nat_succ,
int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w],
-- base case
t ← to_expr ``(s_mod %%p 0 = 4),
v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4),
h ← assertv `h t v,
-- step case, repeated p-2 times
iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })],
-- now close the goal
h ← get_local `h,
exact h
end lucas_lehmer
/-- We verify that the tactic works to prove `127.prime`. -/
example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test).
/-!
This implementation works successfully to prove `(2^127 - 1).prime`,
and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean].
`(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!),
and unfortunately the next Mersenne prime `(2^521 - 1)`,
which was the first "computer era" prime,
is out of reach with the current implementation.
There's still low hanging fruit available to do faster computations
based on the formula
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] :=
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
begin
conv in k { rw ← nat.div_add_mod k (2^n) },
refine nat.modeq.add_right _ _,
conv { congr, skip, skip, rw ← one_mul (k/2^n) },
exact (nat.modeq_sub $ nat.succ_le_of_lt $ pow_pos zero_lt_two _).mul_right _,
end
-- It's hard to know what the limiting factor for large Mersenne primes would be.
-- In the purely computational world, I think it's the squaring operation in `s`.
|
cc0974cb279d3110e82c9ba81db13d436824b335 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/punit.lean | 86c16356489a6c62c6bcdeb81e3743883183227c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,352 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.functor.const
import category_theory.discrete_category
/-!
# The category `discrete punit`
We define `star : C ⥤ discrete punit` sending everything to `punit.star`,
show that any two functors to `discrete punit` are naturally isomorphic,
and construct the equivalence `(discrete punit ⥤ C) ≌ C`.
-/
universes v u -- morphism levels before object levels. See note [category_theory universes].
namespace category_theory
variables (C : Type u) [category.{v} C]
namespace functor
/-- The constant functor sending everything to `punit.star`. -/
@[simps]
def star : C ⥤ discrete punit :=
(functor.const _).obj ⟨⟨⟩⟩
variable {C}
/-- Any two functors to `discrete punit` are isomorphic. -/
@[simps]
def punit_ext (F G : C ⥤ discrete punit) : F ≅ G :=
nat_iso.of_components (λ _, eq_to_iso dec_trivial) (λ _ _ _, dec_trivial)
/--
Any two functors to `discrete punit` are *equal*.
You probably want to use `punit_ext` instead of this.
-/
lemma punit_ext' (F G : C ⥤ discrete punit) : F = G :=
functor.ext (λ _, dec_trivial) (λ _ _ _, dec_trivial)
/-- The functor from `discrete punit` sending everything to the given object. -/
abbreviation from_punit (X : C) : discrete punit.{v+1} ⥤ C :=
(functor.const _).obj X
/-- Functors from `discrete punit` are equivalent to the category itself. -/
@[simps]
def equiv : (discrete punit ⥤ C) ≌ C :=
{ functor :=
{ obj := λ F, F.obj ⟨⟨⟩⟩,
map := λ F G θ, θ.app ⟨⟨⟩⟩ },
inverse := functor.const _,
unit_iso :=
begin
apply nat_iso.of_components _ _,
intro X,
apply discrete.nat_iso,
rintro ⟨⟨⟩⟩,
apply iso.refl _,
intros,
ext ⟨⟨⟩⟩,
simp,
end,
counit_iso :=
begin
refine nat_iso.of_components iso.refl _,
intros X Y f,
dsimp, simp, -- See note [dsimp, simp].
end }
end functor
/-- A category being equivalent to `punit` is equivalent to it having a unique morphism between
any two objects. (In fact, such a category is also a groupoid; see `groupoid.of_hom_unique`) -/
theorem equiv_punit_iff_unique :
nonempty (C ≌ discrete punit) ↔ (nonempty C) ∧ (∀ x y : C, nonempty $ unique (x ⟶ y)) :=
begin
split,
{ rintro ⟨h⟩,
refine ⟨⟨h.inverse.obj ⟨⟨⟩⟩⟩, λ x y, nonempty.intro _⟩,
apply (unique_of_subsingleton _), swap,
{ have hx : x ⟶ h.inverse.obj ⟨⟨⟩⟩ := by convert h.unit.app x,
have hy : h.inverse.obj ⟨⟨⟩⟩ ⟶ y := by convert h.unit_inv.app y,
exact hx ≫ hy, },
have : ∀ z, z = h.unit.app x ≫ (h.functor ⋙ h.inverse).map z ≫ h.unit_inv.app y,
{ intro z, simpa using congr_arg (≫ (h.unit_inv.app y)) (h.unit.naturality z), },
apply subsingleton.intro,
intros a b,
rw [this a, this b],
simp only [functor.comp_map], congr, },
{ rintro ⟨⟨p⟩, h⟩,
haveI := λ x y, (h x y).some,
refine nonempty.intro (category_theory.equivalence.mk
((functor.const _).obj ⟨⟨⟩⟩) ((functor.const _).obj p) _ (by apply functor.punit_ext)),
exact nat_iso.of_components (λ _, { hom := default, inv := default }) (λ _ _ _, by tidy), },
end
end category_theory
|
5301781bfb7ce5014194d647e115fcc68922c075 | 934eae675a9d997202bb021816325184e7d694aa | /_notes/Languages/lean/myproject/pierce3.lean | 046f067d862c3978671c214086e6fb7c5cf06d44 | [] | no_license | philzook58/philzook58.github.io | da78841df4ffd9a19c81e0eab833983d95a64b70 | 76000a5847bd6ee41dff25937ae916835bbcf03f | refs/heads/master | 1,692,951,958,916 | 1,692,631,945,000 | 1,692,631,945,000 | 91,513,884 | 9 | 4 | null | 1,677,330,791,000 | 1,494,977,989,000 | Jupyter Notebook | UTF-8 | Lean | false | false | 2,478 | lean | /-
The thing about lambdas is that binders are complicated and kind of distraction from some of the main points.
It is also interesting to see how a bunch of stuff works and some different angles of definition.
-/
namespace Term0
inductive term where
| true_ : term
| false_ : term
| ITE (x y z: term): term
open term
#check ITE true_ true_ true_
-- value as a subset of terms
def value : term -> Bool
| true_ | false_ => true
| (ITE _ _ _) => false
-- A different presentation of subsets
inductive value' : term -> Prop where
| IsTrue : value' true_
| IsFalse : value' false_
-- An intrinsic definition
inductive value'' where
| trueval
| falseval
-- a step relation
inductive step : term -> term -> Prop where
| eiftrue : forall t1 t2, step (ITE true_ t1 t2) t1
| eiffalse : forall t1 t2, step (ITE false_ t1 t2) t2
| eif : forall t1 t2 t t', step t t' -> step (ITE t t1 t2) (ITE t' t1 t2)
/-
theorem det_step : forall t t' t'', step t t' -> step t t'' -> t' = t'' := by
intros t
induction t <;> intros t' t'' h1 h2
cases h1
cases h1
cases h1 <;> cases h2 <;> simp
cases a
-/
#print Option
def step' : term -> Option term
| ITE true_ t1 _t2 => some t1
| ITE false_ _t1 t2 => some t2
| ITE t t1 t2 => do
let t' <- step' t
return ITE t t1 t2
| _ => none
-- hmm stack based eval of bexpr is even simpler than int
end Term0
namespace Chap8
inductive term where
| true_
| false_
| ite (cond : term) (then_ : term) (else_ : term)
| zero
| succ (x : term)
| pred (x : term)
| iszero (a : term)
inductive type where
| bool_
| nat
open type
open term
inductive has_type : term -> type -> Prop where
| ttrue : has_type true_ bool_
| tfalse : has_type false_ bool_
| tif : forall cond t2 t3 T, has_type cond bool_ -> has_type t2 T -> has_type t3 T -> has_type (ite cond t2 t3) T
| tsucc : forall t, has_type t nat -> has_type (succ t) nat
| tpred : forall t, has_type t nat -> has_type (pred t ) nat
| tzero : has_type zero nat
| tiszero : forall t, has_type t nat -> has_type (iszero t) bool_
theorem inver1 : forall R, has_type true_ R -> R = bool_ := by
intros R hyp
cases hyp
simp
/-
#print Exists
#print Sigma
def infer (x : term) : exists R, has_type x R :=
match x with
| true_ => (bool_, ttrue)
| false_ => (bool_ , tfalse)
| ite (cond : term) (then_ : term) (else_ : term) =>
infer
| zero
| succ (x : term)
| pred (x : term)
| iszero (a : term)
-/
end Chap8
|
3d458c413e39aa309dc7277a75ad74d693a5e4dc | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /library/init/data/default.lean | a2b496e9cd381275dc63e387ed80a7ca3e318edc | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 455 | 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.basic init.data.sigma init.data.nat init.data.char init.data.string
import init.data.list init.data.sum init.data.subtype init.data.int init.data.array
import init.data.bool init.data.fin init.data.unsigned init.data.ordering
import init.data.rbtree init.data.rbmap
|
6b8866a57a67d4472ec0f3ff21322b30648036d1 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/number_theory/padics/ring_homs.lean | 6e7189506bb30a364400761018a0578463f83c88 | [
"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 | 24,480 | lean | /-
Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import number_theory.padics.padic_integers
/-!
# Relating `ℤ_[p]` to `zmod (p ^ n)`
In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$
and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$.
## Main declarations
We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`.
The case for `n = 1` is handled separately, since it is used in the general construction
and we may want to use it without the `^1` getting in the way.
* `padic_int.to_zmod`: ring hom to `zmod p`
* `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)`
* `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals
generated by `p^n`
We also establish the universal property of $\mathbb{Z}_p$ as a projective limit.
Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$,
there is a unique limit $R \to \mathbb{Z}_p$.
* `padic_int.lift`: the limit function
* `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property
## Implementation notes
The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`,
which removes some boilerplate code.
-/
noncomputable theory
open_locale classical
namespace padic_int
open nat local_ring padic
variables {p : ℕ} [hp_prime : fact (p.prime)]
include hp_prime
section ring_homs
/-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/
variables (p) (r : ℚ)
omit hp_prime
/--
`mod_part p r` is an integer that satisfies
`∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`,
see `padic_int.norm_sub_mod_part`.
It is the unique non-negative integer that is `< p` with this property.
(Note that this definition assumes `r : ℚ`.
See `padic_int.zmod_repr` for a version that takes values in `ℕ`
and works for arbitrary `x : ℤ_[p]`.) -/
def mod_part : ℤ :=
(r.num * gcd_a r.denom p) % p
include hp_prime
variable {p}
lemma mod_part_lt_p : mod_part p r < p :=
begin
convert int.mod_lt _ _,
{ simp },
{ exact_mod_cast hp_prime.1.ne_zero }
end
lemma mod_part_nonneg : 0 ≤ mod_part p r :=
int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero
lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) :=
begin
rw is_unit_iff,
apply le_antisymm (r.denom : ℤ_[p]).2,
rw [← not_lt, val_eq_coe, coe_coe],
intro norm_denom_lt,
have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥,
{ rw_mod_cast @rat.mul_denom_eq_num r, refl, },
rw padic_norm_e.mul at hr,
have key : ∥(r.num : ℚ_[p])∥ < 1,
{ calc _ = _ : hr.symm
... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one
... = 1 : mul_one 1 },
have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom,
{ simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int],
norm_cast, exact ⟨key, norm_denom_lt⟩ },
apply hp_prime.1.not_dvd_one,
rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd],
end
lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) :
↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) :=
begin
rw ← zmod.int_coe_zmod_eq_zero_iff_dvd,
simp only [int.cast_coe_nat, zmod.nat_cast_mod p, int.cast_mul, int.cast_sub],
have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p),
simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul]
at this,
push_cast,
rw [mul_right_comm, mul_assoc, ←this],
suffices rdcp : r.denom.coprime p,
{ rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], },
apply coprime.symm,
apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right,
rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt],
apply ge_of_eq,
rw ← is_unit_iff,
exact is_unit_denom r h,
end
lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 :=
begin
let n := mod_part p r,
by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0,
{ rw [aux, norm_zero], exact zero_lt_one, },
rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right],
suffices : ↑p ∣ r.num - n * r.denom,
{ convert (int.cast_ring_hom ℤ_[p]).map_dvd this,
simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul,
sub_left_inj, int.cast_sub],
apply subtype.coe_injective,
simp only [coe_mul, subtype.coe_mk, coe_coe],
rw_mod_cast @rat.mul_denom_eq_num r, refl },
exact norm_sub_mod_part_aux r h
end
lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) :
∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 :=
⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩
lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ)
(ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p]))
(hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) :
(a : zmod (p ^ n)) = b :=
begin
rw [ideal.mem_span_singleton] at ha hb,
rw [← sub_eq_zero, ← int.cast_sub,
zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow],
rw [← dvd_neg, neg_sub] at ha,
have := dvd_add ha hb,
rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left,
← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this,
end
lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ)
(ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p]))
(hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) :
(a : zmod (p ^ n)) = b :=
zmod_congr_of_sub_mem_span_aux n x a b ha hb
lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ)
(hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) :
(m : zmod p) = n :=
begin
rw maximal_ideal_eq_span_p at hm hn,
have := zmod_congr_of_sub_mem_span_aux 1 x m n,
simp only [pow_one] at this,
specialize this hm hn,
apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this,
simpa only [ring_hom.map_int_cast],
end
variable (x : ℤ_[p])
lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) :=
begin
simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd],
obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one,
have H : ∥(r : ℚ_[p])∥ ≤ 1,
{ rw norm_sub_rev at hr,
calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring_nf
... ≤ _ : padic_norm_e.nonarchimedean _ _
... ≤ _ : max_le (le_of_lt hr) x.2 },
obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H,
lift n to ℕ using hzn,
use n,
split, {exact_mod_cast hnp},
simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢,
rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring,
apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _),
apply max_lt hr,
simpa using hn
end
/--
`zmod_repr x` is the unique natural number smaller than `p`
satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`.
-/
def zmod_repr : ℕ :=
classical.some (exists_mem_range x)
lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) :=
classical.some_spec (exists_mem_range x)
lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1
lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2
/--
`to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`.
-/
def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p]))
(f_congr : ∀ (x : ℤ_[p]) (a b : ℕ),
x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) →
(a : zmod v) = b) :
ℤ_[p] →+* zmod v :=
{ to_fun := λ x, f x,
map_zero' :=
begin
rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero],
{ exact f_spec _ },
{ simp only [sub_zero, cast_zero, submodule.zero_mem], }
end,
map_one' :=
begin
rw [f_congr (1 : ℤ_[p]) _ 1, cast_one],
{ exact f_spec _ },
{ simp only [sub_self, cast_one, submodule.zero_mem], }
end,
map_add' :=
begin
intros x y,
rw [f_congr (x + y) _ (f x + f y), cast_add],
{ exact f_spec _ },
{ convert ideal.add_mem _ (f_spec x) (f_spec y),
rw cast_add,
ring, }
end,
map_mul' :=
begin
intros x y,
rw [f_congr (x * y) _ (f x * f y), cast_mul],
{ exact f_spec _ },
{ let I : ideal ℤ_[p] := ideal.span {v},
convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)),
rw cast_mul,
ring, }
end, }
/--
`to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`,
with the equality `to_zmod x = (zmod_repr x : zmod p)`.
-/
def to_zmod : ℤ_[p] →+* zmod p :=
to_zmod_hom p zmod_repr
(by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem })
(by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } )
/--
`z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`.
The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`,
which coerces `zmod p` into artibrary rings.
This is unfortunate, but a consequence of the fact that we allow `zmod p`
to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`.
This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides
`p`. While this is not the case here we can still make use of the coercion.
-/
lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] :=
begin
convert sub_zmod_repr_mem z using 2,
dsimp [to_zmod, to_zmod_hom],
unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ },
change ↑(zmod.val _) = _,
simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add],
apply mod_eq_of_lt,
simpa only [zero_add] using zmod_repr_lt_p z,
end
lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] :=
begin
ext x,
rw ring_hom.mem_ker,
split,
{ intro h,
simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, },
{ intro h,
rw ← sub_zero x at h,
dsimp [to_zmod, to_zmod_hom],
convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h,
apply sub_zmod_repr_mem, }
end
/-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`.
See `appr_spec`. -/
noncomputable def appr : ℤ_[p] → ℕ → ℕ
| x 0 := 0
| x (n+1) :=
let y := x - appr x n in
if hy : y = 0 then
appr x n
else
let u := unit_coeff hy in
appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val
lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n :=
begin
induction n with n ih generalizing x,
{ simp only [appr, succ_pos', pow_zero], },
simp only [appr, ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs,
ring_hom.map_mul],
have hp : p ^ n < p ^ (n + 1),
{ apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) },
split_ifs with h,
{ apply lt_trans (ih _) hp, },
{ calc _ < p ^ n + p ^ n * (p - 1) : _
... = p ^ (n + 1) : _,
{ apply add_lt_add_of_lt_of_le (ih _),
apply nat.mul_le_mul_left,
apply le_pred_of_lt,
apply zmod.val_lt },
{ rw [nat.mul_sub_left_distrib, mul_one, ← pow_succ'],
apply add_sub_cancel_of_le (le_of_lt hp) } }
end
lemma appr_mono (x : ℤ_[p]) : monotone x.appr :=
begin
apply monotone_nat_of_le_succ,
intro n,
dsimp [appr],
split_ifs, { refl, },
apply nat.le_add_right,
end
lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) :
p ^ m ∣ x.appr n - x.appr m :=
begin
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h,
induction k with k ih,
{ simp only [add_zero, nat.sub_self, dvd_zero], },
rw [nat.succ_eq_add_one, ← add_assoc],
dsimp [appr],
split_ifs with h,
{ exact ih },
rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))],
apply dvd_add _ ih,
apply dvd_mul_of_dvd_left,
apply pow_dvd_pow _ (nat.le_add_right m k),
end
lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) :=
begin
simp only [ideal.mem_span_singleton],
induction n with n ih,
{ simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], },
intro x,
dsimp only [appr],
split_ifs with h,
{ rw h, apply dvd_zero },
push_cast, rw sub_add_eq_sub_sub,
obtain ⟨c, hc⟩ := ih x,
simp only [ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul,
zmod.nat_cast_val],
have hc' : c ≠ 0,
{ rintro rfl, simp only [mul_zero] at hc, contradiction },
conv_rhs { congr, simp only [hc], },
rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation,
{ rw hc },
rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub],
apply mul_dvd_mul_left,
obtain hc0 | hc0 := c.valuation.nat_abs.eq_zero_or_pos,
{ simp only [hc0, mul_one, pow_zero],
rw [mul_comm, unit_coeff_spec h] at hc,
suffices : c = unit_coeff h,
{ rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p],
apply to_zmod_spec },
obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units
{ rw int.nat_abs_eq_zero at hc0,
rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, gpow_zero], },
rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc,
exact irreducible_p },
{ rw zero_pow hc0,
simp only [sub_zero, zmod.cast_zero, mul_zero],
rw unit_coeff_spec hc',
exact (dvd_pow_self _ hc0.ne').mul_left _ }
end
attribute [irreducible] appr
/-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/
def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) :=
to_zmod_hom (p^n) (λ x, appr x n)
(by { intros, convert appr_spec n _ using 1, simp })
(by { intros x a b ha hb,
apply zmod_congr_of_sub_mem_span n x a b,
{ simpa using ha },
{ simpa using hb } })
lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} :=
begin
ext x,
rw ring_hom.mem_ker,
split,
{ intro h,
suffices : x.appr n = 0,
{ convert appr_spec n x, simp only [this, sub_zero, cast_zero], },
dsimp [to_zmod_pow, to_zmod_hom] at h,
rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h,
apply eq_zero_of_dvd_of_lt h (appr_lt _ _), },
{ intro h,
rw ← sub_zero x at h,
dsimp [to_zmod_pow, to_zmod_hom],
rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero],
apply appr_spec, }
end
@[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) :
(zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m :=
begin
apply zmod.ring_hom_eq_of_ker_eq,
ext x,
rw [ring_hom.mem_ker, ring_hom.mem_ker],
simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp],
simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk],
rw [zmod.cast_nat_cast (pow_dvd_pow p h),
zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)],
{ rw [sub_self], apply ideal.zero_mem _, },
{ rw ideal.mem_span_singleton,
rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩,
use c,
rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], },
{ apply_instance }
end
@[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) :
↑(to_zmod_pow n x) = to_zmod_pow m x :=
by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl }
lemma dense_range_nat_cast :
dense_range (nat.cast : ℕ → ℤ_[p]) :=
begin
intro x,
rw metric.mem_closure_range_iff,
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε,
use (x.appr n),
rw dist_eq_norm,
apply lt_of_le_of_lt _ hn,
rw norm_le_pow_iff_mem_span_pow,
apply appr_spec,
end
lemma dense_range_int_cast :
dense_range (int.cast : ℤ → ℤ_[p]) :=
begin
intro x,
apply dense_range_nat_cast.induction_on x,
{ exact is_closed_closure, },
{ intro a,
change (a.cast : ℤ_[p]) with (a : ℤ).cast,
apply subset_closure,
exact set.mem_range_self _ }
end
end ring_homs
section lift
/-! ### Universal property as projective limit -/
open cau_seq padic_seq
variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k))
(f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1)
omit hp_prime
/--
Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`,
`nth_hom f r` is an integer-valued sequence
whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n`
and `f n r = (k : zmod (p ^ n))`.
-/
def nth_hom (r : R) : ℕ → ℤ :=
λ n, (f n r : zmod (p^n)).val
@[simp] lemma nth_hom_zero : nth_hom f 0 = 0 :=
by simp [nth_hom]; refl
variable {f}
include hp_prime
include f_compat
lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) :
↑p ^ i ∣ nth_hom f r j - nth_hom f r i :=
begin
specialize f_compat i j h,
rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd,
int.cast_sub],
dsimp [nth_hom],
rw [← f_compat, ring_hom.comp_apply],
have : fact (p ^ i > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], },
end
lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) :=
begin
intros ε hε,
obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε,
use k,
intros j hj,
refine lt_of_le_of_lt _ hk,
norm_cast,
rw ← padic_norm.dvd_iff_norm_le,
exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj
end
/--
`nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r`
as a Cauchy sequence of rationals with respect to the `p`-adic norm.
The `n`th value of the sequence is `((f n r).val : ℚ)`.
-/
def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩
lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 :=
begin
intros ε hε,
change _ < _ at hε,
use 1,
intros j hj,
haveI : fact (1 < p^j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩,
simp [nth_hom_seq, nth_hom, zmod.val_one, hε],
end
lemma nth_hom_seq_add (r s : R) :
nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s :=
begin
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε,
use n,
intros j hj,
dsimp [nth_hom_seq],
apply lt_of_le_of_lt _ hn,
rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le,
← zmod.int_coe_zmod_eq_zero_iff_dvd],
dsimp [nth_hom],
have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
unfreezingI
{ simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] },
rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self],
{ apply_instance },
{ apply pow_dvd_pow, linarith only [hj] },
end
lemma nth_hom_seq_mul (r s : R) :
nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s :=
begin
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε,
use n,
intros j hj,
dsimp [nth_hom_seq],
apply lt_of_le_of_lt _ hn,
rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le,
← zmod.int_coe_zmod_eq_zero_iff_dvd],
dsimp [nth_hom],
have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
unfreezingI
{ simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] },
rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self],
{ apply_instance },
{ apply pow_dvd_pow, linarith only [hj] },
end
/--
`lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`.
This is itself a ring hom: see `padic_int.lift`.
-/
def lim_nth_hom (r : R) : ℤ_[p] :=
of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r)
lemma lim_nth_hom_spec (r : R) :
∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε :=
begin
intros ε hε,
obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε,
norm_cast at hε'0,
obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0,
use N,
intros n hn,
apply lt_trans _ hε',
change ↑(padic_norm_e _) < _,
norm_cast,
convert hN _ hn,
simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq],
end
lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 :=
by simp [lim_nth_hom]; refl
lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 :=
subtype.ext $ quot.sound $ nth_hom_seq_one _
lemma lim_nth_hom_add (r s : R) :
lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s :=
subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _
lemma lim_nth_hom_mul (r s : R) :
lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s :=
subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _
-- TODO: generalize this to arbitrary complete discrete valuation rings
/--
`lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`,
with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`.
-/
def lift : R →+* ℤ_[p] :=
{ to_fun := lim_nth_hom f_compat,
map_one' := lim_nth_hom_one f_compat,
map_mul' := lim_nth_hom_mul f_compat,
map_zero' := lim_nth_hom_zero f_compat,
map_add' := lim_nth_hom_add f_compat }
omit f_compat
lemma lift_sub_val_mem_span (r : R) (n : ℕ) :
(lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) :=
begin
obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _
(show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.1.pos _),
have := le_of_lt (hk (max n k) (le_max_right _ _)),
rw norm_le_pow_iff_mem_span_pow at this,
dsimp [lift],
rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)),
apply ideal.add_mem _ _ this,
rw [ideal.mem_span_singleton],
simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using
(int.cast_ring_hom ℤ_[p]).map_dvd
(pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)),
end
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_unique`.
-/
lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n :=
begin
ext r,
haveI : fact (0 < p ^ n) := ⟨pow_pos hp_prime.1.pos n⟩,
rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← (to_zmod_pow n).map_nat_cast,
← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow],
apply lift_sub_val_mem_span,
end
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_spec`.
-/
lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) :
lift f_compat = g :=
begin
ext1 r,
apply eq_of_forall_dist_le,
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε,
apply le_trans _ (le_of_lt hn),
rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker,
ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self],
end
@[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow
zmod_cast_comp_to_zmod_pow z = z :=
begin
show _ = ring_hom.id _ z,
rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]),
intro, rw ring_hom.comp_id,
end
end lift
lemma ext_of_to_zmod_pow {x y : ℤ_[p]} :
(∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y :=
begin
split,
{ intro h,
rw [← lift_self x, ← lift_self y],
simp [lift, lim_nth_hom, nth_hom, h] },
{ rintro rfl _, refl }
end
lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} :
(∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' :=
begin
split,
{ intro hg,
ext x : 1,
apply ext_of_to_zmod_pow.mp,
intro n,
show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x,
rw hg n },
{ rintro rfl _, refl }
end
end padic_int
|
bcf0c9a471cc134b8a7a00328b48c2f0a1366d64 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Data/Xml/Parser.lean | c5f774485857db0bf88b3fbf37456bbb8d0b822c | [
"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 | 15,241 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Dany Fabian
-/
import Lean.Data.Parsec
import Lean.Data.Xml.Basic
open IO
open System
open Lean
namespace Lean
namespace Xml
namespace Parser
open Lean.Parsec
open Parsec.ParseResult
abbrev LeanChar := Char
/-- consume a newline character sequence pretending, that we read '\n'. As per spec:
https://www.w3.org/TR/xml/#sec-line-ends -/
def endl : Parsec LeanChar := (skipString "\r\n" <|> skipChar '\r' <|> skipChar '\n') *> pure '\n'
def quote (p : Parsec α) : Parsec α :=
skipChar '\'' *> p <* skipChar '\''
<|> skipChar '"' *> p <* skipChar '"'
/-- https://www.w3.org/TR/xml/#NT-Char -/
def Char : Parsec LeanChar :=
(attempt do
let c ← anyChar
let cNat := c.toNat
if (0x20 ≤ cNat ∧ cNat ≤ 0xD7FF)
∨ (0xE000 ≤ cNat ∧ cNat ≤ 0xFFFD)
∨ (0x10000 ≤ cNat ∧ cNat ≤ 0x10FFFF) then pure c else fail "expected xml char")
<|> pchar '\t' <|> endl
/-- https://www.w3.org/TR/xml/#NT-S -/
def S : Parsec String :=
many1Chars (pchar ' ' <|> endl <|> pchar '\t')
/-- https://www.w3.org/TR/xml/#NT-Eq -/
def Eq : Parsec Unit :=
optional S *> skipChar '=' <* optional S
private def nameStartCharRanges : Array (Nat × Nat) :=
#[(0xC0, 0xD6),
(0xD8, 0xF6),
(0xF8, 0x2FF),
(0x370, 0x37D),
(0x37F, 0x1FFF),
(0x200C, 0x200D),
(0x2070, 0x218F),
(0x2C00, 0x2FEF),
(0x3001, 0xD7FF),
(0xF900, 0xFDCF),
(0xFDF0, 0xFFFD),
(0x10000, 0xEFFFF)]
/-- https://www.w3.org/TR/xml/#NT-NameStartChar -/
def NameStartChar : Parsec LeanChar := attempt do
let c ← anyChar
if ('A' ≤ c ∧ c ≤ 'Z') ∨ ('a' ≤ c ∧ c ≤ 'z') then pure c
else if c = ':' ∨ c = '_' then pure c
else
let cNum := c.toNat
if nameStartCharRanges.any (fun (lo, hi) => lo ≤ cNum ∧ cNum ≤ hi) then pure c
else fail "expected a name character"
/-- https://www.w3.org/TR/xml/#NT-NameChar -/
def NameChar : Parsec LeanChar :=
NameStartChar <|> digit <|> pchar '-' <|> pchar '.' <|> pchar '\xB7'
<|> satisfy (λ c => ('\u0300' ≤ c ∧ c ≤ '\u036F') ∨ ('\u203F' ≤ c ∧ c ≤ '\u2040'))
/-- https://www.w3.org/TR/xml/#NT-Name -/
def Name : Parsec String := do
let x ← NameStartChar
manyCharsCore NameChar x.toString
/-- https://www.w3.org/TR/xml/#NT-VersionNum -/
def VersionNum : Parsec Unit :=
skipString "1." <* (many1 digit)
/-- https://www.w3.org/TR/xml/#NT-VersionInfo -/
def VersionInfo : Parsec Unit := do
S *>
skipString "version"
Eq
quote VersionNum
/-- https://www.w3.org/TR/xml/#NT-EncName -/
def EncName : Parsec String := do
let x ← asciiLetter
manyCharsCore (asciiLetter <|> digit <|> pchar '-' <|> pchar '_' <|> pchar '.') x.toString
/-- https://www.w3.org/TR/xml/#NT-EncodingDecl -/
def EncodingDecl : Parsec String := do
S *>
skipString "encoding"
Eq
quote EncName
/-- https://www.w3.org/TR/xml/#NT-SDDecl -/
def SDDecl : Parsec String := do
S *> skipString "standalone" *> Eq *> quote (pstring "yes" <|> pstring "no")
/-- https://www.w3.org/TR/xml/#NT-XMLDecl -/
def XMLdecl : Parsec Unit := do
skipString "<?xml"
VersionInfo
optional EncodingDecl *>
optional SDDecl *>
optional S *>
skipString "?>"
/-- https://www.w3.org/TR/xml/#NT-Comment -/
def Comment : Parsec String :=
let notDash := Char.toString <$> satisfy (λ c => c ≠ '-')
skipString "<!--" *>
Array.foldl String.append "" <$> many (notDash <|> (do
let d ← pchar '-'
let c ← notDash
pure $ d.toString ++ c))
<* skipString "-->"
/-- https://www.w3.org/TR/xml/#NT-PITarget -/
def PITarget : Parsec String :=
Name <* (skipChar 'X' <|> skipChar 'x') <* (skipChar 'M' <|> skipChar 'm') <* (skipChar 'L' <|> skipChar 'l')
/-- https://www.w3.org/TR/xml/#NT-PI -/
def PI : Parsec Unit := do
skipString "<?"
<* PITarget <*
optional (S *> manyChars (notFollowedBy (skipString "?>") *> Char))
skipString "?>"
/-- https://www.w3.org/TR/xml/#NT-Misc -/
def Misc : Parsec Unit :=
Comment *> pure () <|> PI <|> S *> pure ()
/-- https://www.w3.org/TR/xml/#NT-SystemLiteral -/
def SystemLiteral : Parsec String :=
pchar '"' *> manyChars (satisfy λ c => c ≠ '"') <* pchar '"'
<|> pchar '\'' *> manyChars (satisfy λ c => c ≠ '\'') <* pure '\''
/-- https://www.w3.org/TR/xml/#NT-PubidChar -/
def PubidChar : Parsec LeanChar :=
asciiLetter <|> digit <|> endl <|> attempt do
let c ← anyChar
if "-'()+,./:=?;!*#@$_%".contains c then pure c else fail "PublidChar expected"
/-- https://www.w3.org/TR/xml/#NT-PubidLiteral -/
def PubidLiteral : Parsec String :=
pchar '"' *> manyChars PubidChar <* pchar '"'
<|> pchar '\'' *> manyChars (attempt do
let c ← PubidChar
if c = '\'' then fail "'\\'' not expected" else pure c) <* pchar '\''
/-- https://www.w3.org/TR/xml/#NT-ExternalID -/
def ExternalID : Parsec Unit :=
skipString "SYSTEM" *> S *> SystemLiteral *> pure ()
<|> skipString "PUBLIC" *> S *> PubidLiteral *> S *> SystemLiteral *> pure ()
/-- https://www.w3.org/TR/xml/#NT-Mixed -/
def Mixed : Parsec Unit :=
(do
skipChar '('
optional S *>
skipString "#PCDATA" *>
many (optional S *> skipChar '|' *> optional S *> Name) *>
optional S *>
skipString ")*")
<|> skipChar '(' *> (optional S) *> skipString "#PCDATA" <* (optional S) <* skipChar ')'
mutual
/-- https://www.w3.org/TR/xml/#NT-cp -/
partial def cp : Parsec Unit :=
(Name *> pure () <|> choice <|> seq) <* optional (skipChar '?' <|> skipChar '*' <|> skipChar '+')
/-- https://www.w3.org/TR/xml/#NT-choice -/
partial def choice : Parsec Unit := do
skipChar '('
optional S *>
cp
many1 (optional S *> skipChar '|' *> optional S *> cp) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-seq -/
partial def seq : Parsec Unit := do
skipChar '('
optional S *>
cp
many (optional S *> skipChar ',' *> optional S *> cp) *>
optional S *>
skipChar ')'
end
/-- https://www.w3.org/TR/xml/#NT-children -/
def children : Parsec Unit :=
(choice <|> seq) <* optional (skipChar '?' <|> skipChar '*' <|> skipChar '+')
/-- https://www.w3.org/TR/xml/#NT-contentspec -/
def contentspec : Parsec Unit := do
skipString "EMPTY" <|> skipString "ANY" <|> Mixed <|> children
/-- https://www.w3.org/TR/xml/#NT-elementdecl -/
def elementDecl : Parsec Unit := do
skipString "<!ELEMENT"
S *>
Name *>
contentspec *>
optional S *>
skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-StringType -/
def StringType : Parsec Unit :=
skipString "CDATA"
/-- https://www.w3.org/TR/xml/#NT-TokenizedType -/
def TokenizedType : Parsec Unit :=
skipString "ID"
<|> skipString "IDREF"
<|> skipString "IDREFS"
<|> skipString "ENTITY"
<|> skipString "ENTITIES"
<|> skipString "NMTOKEN"
<|> skipString "NMTOKENS"
/-- https://www.w3.org/TR/xml/#NT-NotationType -/
def NotationType : Parsec Unit := do
skipString "NOTATION"
S *>
skipChar '(' <*
optional S
Name *> many (optional S *> skipChar '|' *> optional S *> Name) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-Nmtoken -/
def Nmtoken : Parsec String := do
many1Chars NameChar
/-- https://www.w3.org/TR/xml/#NT-Enumeration -/
def Enumeration : Parsec Unit := do
skipChar '('
optional S *>
Nmtoken *> many (optional S *> skipChar '|' *> optional S *> Nmtoken) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-EnumeratedType -/
def EnumeratedType : Parsec Unit :=
NotationType <|> Enumeration
/-- https://www.w3.org/TR/xml/#NT-AttType -/
def AttType : Parsec Unit :=
StringType <|> TokenizedType <|> EnumeratedType
def predefinedEntityToChar : String → Option LeanChar
| "lt" => some '<'
| "gt" => some '>'
| "amp" => some '&'
| "apos" => some '\''
| "quot" => some '"'
| _ => none
/-- https://www.w3.org/TR/xml/#NT-EntityRef -/
def EntityRef : Parsec $ Option LeanChar := attempt $
skipChar '&' *> predefinedEntityToChar <$> Name <* skipChar ';'
@[inline]
def hexDigitToNat (c : LeanChar) : Nat :=
if '0' ≤ c ∧ c ≤ '9' then c.toNat - '0'.toNat
else if 'a' ≤ c ∧ c ≤ 'f' then c.toNat - 'a'.toNat + 10
else c.toNat - 'A'.toNat + 10
def digitsToNat (base : Nat) (digits : Array Nat) : Nat :=
digits.foldl (λ r d => r * base + d) 0
/-- https://www.w3.org/TR/xml/#NT-CharRef -/
def CharRef : Parsec LeanChar := do
skipString "&#"
let charCode ←
digitsToNat 10 <$> many1 (hexDigitToNat <$> digit)
<|> skipChar 'x' *> digitsToNat 16 <$> many1 (hexDigitToNat <$> hexDigit)
skipChar ';'
return Char.ofNat charCode
/-- https://www.w3.org/TR/xml/#NT-Reference -/
def Reference : Parsec $ Option LeanChar :=
EntityRef <|> some <$> CharRef
/-- https://www.w3.org/TR/xml/#NT-AttValue -/
def AttValue : Parsec String := do
let chars ←
(do
skipChar '"'
many (some <$> satisfy (λ c => c ≠ '<' ∧ c ≠ '&' ∧ c ≠ '"') <|> Reference) <*
skipChar '"')
<|> (do
skipChar '\''
many (some <$> satisfy (λ c => c ≠ '<' ∧ c ≠ '&' ∧ c ≠ '\'') <|> Reference) <*
skipChar '\'')
return chars.foldl (λ s c => if let some c := c then s.push c else s) ""
/-- https://www.w3.org/TR/xml/#NT-DefaultDecl -/
def DefaultDecl : Parsec Unit :=
skipString "#REQUIRED"
<|> skipString "#IMPLIED"
<|> optional (skipString "#FIXED" <* S) *> AttValue *> pure ()
/-- https://www.w3.org/TR/xml/#NT-AttDef -/
def AttDef : Parsec Unit :=
S *> Name *> S *> AttType *> S *> DefaultDecl
/-- https://www.w3.org/TR/xml/#NT-AttlistDecl -/
def AttlistDecl : Parsec Unit :=
skipString "<!ATTLIST" *> S *> Name *> many AttDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-PEReference -/
def PEReference : Parsec Unit :=
skipChar '%' *> Name *> skipChar ';'
/-- https://www.w3.org/TR/xml/#NT-EntityValue -/
def EntityValue : Parsec String := do
let chars ←
(do
skipChar '"'
many (some <$> satisfy (λ c => c ≠ '%' ∧ c ≠ '&' ∧ c ≠ '"') <|> PEReference *> pure none <|> Reference) <*
skipChar '"')
<|> (do
skipChar '\''
many (some <$> satisfy (λ c => c ≠ '%' ∧ c ≠ '&' ∧ c ≠ '\'') <|> PEReference *> pure none <|> Reference) <*
skipChar '\'')
return chars.foldl (λ s c => if let some c := c then s.push c else s) ""
/-- https://www.w3.org/TR/xml/#NT-NDataDecl -/
def NDataDecl : Parsec Unit :=
S *> skipString "NDATA" <* S <* Name
/-- https://www.w3.org/TR/xml/#NT-EntityDef -/
def EntityDef : Parsec Unit :=
EntityValue *> pure () <|> (ExternalID <* optional NDataDecl)
/-- https://www.w3.org/TR/xml/#NT-GEDecl -/
def GEDecl : Parsec Unit :=
skipString "<!ENTITY" *> S *> Name *> S *> EntityDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-PEDef -/
def PEDef : Parsec Unit :=
EntityValue *> pure () <|> ExternalID
/-- https://www.w3.org/TR/xml/#NT-PEDecl -/
def PEDecl : Parsec Unit :=
skipString "<!ENTITY" *> S *> skipChar '%' *> S *> Name *> PEDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-EntityDecl -/
def EntityDecl : Parsec Unit :=
GEDecl <|> PEDecl
/-- https://www.w3.org/TR/xml/#NT-PublicID -/
def PublicID : Parsec Unit :=
skipString "PUBLIC" <* S <* PubidLiteral
/-- https://www.w3.org/TR/xml/#NT-NotationDecl -/
def NotationDecl : Parsec Unit :=
skipString "<!NOTATION" *> S *> Name *> (ExternalID <|> PublicID) *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-markupdecl -/
def markupDecl : Parsec Unit :=
elementDecl <|> AttlistDecl <|> EntityDecl <|> NotationDecl <|> PI <|> (Comment *> pure ())
/-- https://www.w3.org/TR/xml/#NT-DeclSep -/
def DeclSep : Parsec Unit :=
PEReference <|> S *> pure ()
/-- https://www.w3.org/TR/xml/#NT-intSubset -/
def intSubset : Parsec Unit :=
many (markupDecl <|> DeclSep) *> pure ()
/-- https://www.w3.org/TR/xml/#NT-doctypedecl -/
def doctypedecl : Parsec Unit := do
skipString "<!DOCTYPE"
S *>
Name *>
optional (S *> ExternalID) *> pure ()
<* optional S
optional (skipChar '[' *> intSubset <* skipChar ']' <* optional S) *>
skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-prolog -/
def prolog : Parsec Unit :=
optional XMLdecl *>
many Misc *>
optional (doctypedecl <* many Misc) *> pure ()
/-- https://www.w3.org/TR/xml/#NT-Attribute -/
def Attribute : Parsec (String × String) := do
let name ← Name
Eq
let value ← AttValue
return (name, value)
protected def elementPrefix : Parsec (Array Content → Element) := do
skipChar '<'
let name ← Name
let attributes ← many (S *> Attribute)
optional S *> pure ()
return Element.Element name (Std.RBMap.fromList attributes.toList compare)
/-- https://www.w3.org/TR/xml/#NT-EmptyElemTag -/
def EmptyElemTag (elem : Array Content → Element) : Parsec Element := do
skipString "/>" *> pure (elem #[])
/-- https://www.w3.org/TR/xml/#NT-STag -/
def STag (elem : Array Content → Element) : Parsec (Array Content → Element) := do
skipChar '>' *> pure elem
/-- https://www.w3.org/TR/xml/#NT-ETag -/
def ETag : Parsec Unit :=
skipString "</" *> Name *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-CDStart -/
def CDStart : Parsec Unit :=
skipString "<![CDATA["
/-- https://www.w3.org/TR/xml/#NT-CDEnd -/
def CDEnd : Parsec Unit :=
skipString "]]>"
/-- https://www.w3.org/TR/xml/#NT-CData -/
def CData : Parsec String :=
manyChars (notFollowedBy (skipString "]]>") *> anyChar)
/-- https://www.w3.org/TR/xml/#NT-CDSect -/
def CDSect : Parsec String :=
CDStart *> CData <* CDEnd
/-- https://www.w3.org/TR/xml/#NT-CharData -/
def CharData : Parsec String :=
notFollowedBy (skipString "]]>") *> manyChars (satisfy λ c => c ≠ '<' ∧ c ≠ '&')
mutual
/-- https://www.w3.org/TR/xml/#NT-content -/
partial def content : Parsec (Array Content) := do
let x ← optional (Content.Character <$> CharData)
let xs ← many do
let y ←
attempt (some <$> Content.Element <$> element)
<|> (do let c ← Reference; pure <| c.map (Content.Character ∘ Char.toString))
<|> some <$> Content.Character <$> CDSect
<|> PI *> pure none
<|> some <$> Content.Comment <$> Comment
let z ← optional (Content.Character <$> CharData)
pure #[y, z]
let xs := #[x] ++ xs.concatMap id |>.filterMap id
let mut res := #[]
for x in xs do
if res.size > 0 then
match res.back, x with
| Content.Character x, Content.Character y => res := res.set! (res.size - 1) (Content.Character $ x ++ y)
| _, x => res := res.push x
else res := res.push x
return res
/-- https://www.w3.org/TR/xml/#NT-element -/
partial def element : Parsec Element := do
let elem ← Parser.elementPrefix
EmptyElemTag elem <|> STag elem <*> content <* ETag
end
/-- https://www.w3.org/TR/xml/#NT-document -/
def document : Parsec Element := prolog *> element <* many Misc <* eof
end Parser
def parse (s : String) : Except String Element :=
match Xml.Parser.document s.mkIterator with
| Parsec.ParseResult.success _ res => Except.ok res
| Parsec.ParseResult.error it err => Except.error s!"offset {it.i.byteIdx.repr}: {err}\n{(it.prevn 10).extract it}"
end Xml
|
0192298d95201e55d89fb99b11e205a64fadd225 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/box_integral/box/basic.lean | 71807a3aa84a418f50476ce81f95071b93c69088 | [
"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 | 18,009 | 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 data.set.intervals.monotone
import topology.algebra.order.monotone_convergence
import topology.metric_space.basic
/-!
# Rectangular boxes in `ℝⁿ`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define rectangular boxes in `ℝⁿ`. As usual, we represent `ℝⁿ` as the type of
functions `ι → ℝ` (usually `ι = fin n` for some `n`). When we need to interpret a box `[l, u]` as a
set, we use the product `{x | ∀ i, l i < x i ∧ x i ≤ u i}` of half-open intervals `(l i, u i]`. We
exclude `l i` because this way boxes of a partition are disjoint as sets in `ℝⁿ`.
Currently, the only use cases for these constructions are the definitions of Riemann-style integrals
(Riemann, Henstock-Kurzweil, McShane).
## Main definitions
We use the same structure `box_integral.box` both for ambient boxes and for elements of a partition.
Each box is stored as two points `lower upper : ι → ℝ` and a proof of `∀ i, lower i < upper i`. We
define instances `has_mem (ι → ℝ) (box ι)` and `has_coe_t (box ι) (set $ ι → ℝ)` so that each box is
interpreted as the set `{x | ∀ i, x i ∈ set.Ioc (I.lower i) (I.upper i)}`. This way boxes of a
partition are pairwise disjoint and their union is exactly the original box.
We require boxes to be nonempty, because this way coercion to sets is injective. The empty box can
be represented as `⊥ : with_bot (box_integral.box ι)`.
We define the following operations on boxes:
* coercion to `set (ι → ℝ)` and `has_mem (ι → ℝ) (box_integral.box ι)` as described above;
* `partial_order` and `semilattice_sup` instances such that `I ≤ J` is equivalent to
`(I : set (ι → ℝ)) ⊆ J`;
* `lattice` instances on `with_bot (box_integral.box ι)`;
* `box_integral.box.Icc`: the closed box `set.Icc I.lower I.upper`; defined as a bundled monotone
map from `box ι` to `set (ι → ℝ)`;
* `box_integral.box.face I i : box (fin n)`: a hyperface of `I : box_integral.box (fin (n + 1))`;
* `box_integral.box.distortion`: the maximal ratio of two lengths of edges of a box; defined as the
supremum of `nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`.
We also provide a convenience constructor `box_integral.box.mk' (l u : ι → ℝ) : with_bot (box ι)`
that returns the box `⟨l, u, _⟩` if it is nonempty and `⊥` otherwise.
## Tags
rectangular box
-/
open set function metric filter
noncomputable theory
open_locale nnreal classical topology
namespace box_integral
variables {ι : Type*}
/-!
### Rectangular box: definition and partial order
-/
/-- A nontrivial rectangular box in `ι → ℝ` with corners `lower` and `upper`. Repesents the product
of half-open intervals `(lower i, upper i]`. -/
structure box (ι : Type*) :=
(lower upper : ι → ℝ)
(lower_lt_upper : ∀ i, lower i < upper i)
attribute [simp] box.lower_lt_upper
namespace box
variables (I J : box ι) {x y : ι → ℝ}
instance : inhabited (box ι) := ⟨⟨0, 1, λ i, zero_lt_one⟩⟩
lemma lower_le_upper : I.lower ≤ I.upper := λ i, (I.lower_lt_upper i).le
lemma lower_ne_upper (i) : I.lower i ≠ I.upper i := (I.lower_lt_upper i).ne
instance : has_mem (ι → ℝ) (box ι) := ⟨λ x I, ∀ i, x i ∈ Ioc (I.lower i) (I.upper i)⟩
instance : has_coe_t (box ι) (set $ ι → ℝ) := ⟨λ I, {x | x ∈ I}⟩
@[simp] lemma mem_mk {l u x : ι → ℝ} {H} : x ∈ mk l u H ↔ ∀ i, x i ∈ Ioc (l i) (u i) := iff.rfl
@[simp, norm_cast] lemma mem_coe : x ∈ (I : set (ι → ℝ)) ↔ x ∈ I := iff.rfl
lemma mem_def : x ∈ I ↔ ∀ i, x i ∈ Ioc (I.lower i) (I.upper i) := iff.rfl
lemma mem_univ_Ioc {I : box ι} : x ∈ pi univ (λ i, Ioc (I.lower i) (I.upper i)) ↔ x ∈ I :=
mem_univ_pi
lemma coe_eq_pi : (I : set (ι → ℝ)) = pi univ (λ i, Ioc (I.lower i) (I.upper i)) :=
set.ext $ λ x, mem_univ_Ioc.symm
@[simp] lemma upper_mem : I.upper ∈ I := λ i, right_mem_Ioc.2 $ I.lower_lt_upper i
lemma exists_mem : ∃ x, x ∈ I := ⟨_, I.upper_mem⟩
lemma nonempty_coe : set.nonempty (I : set (ι → ℝ)) := I.exists_mem
@[simp] lemma coe_ne_empty : (I : set (ι → ℝ)) ≠ ∅ := I.nonempty_coe.ne_empty
@[simp] lemma empty_ne_coe : ∅ ≠ (I : set (ι → ℝ)) := I.coe_ne_empty.symm
instance : has_le (box ι) := ⟨λ I J, ∀ ⦃x⦄, x ∈ I → x ∈ J⟩
lemma le_def : I ≤ J ↔ ∀ x ∈ I, x ∈ J := iff.rfl
lemma le_tfae :
tfae [I ≤ J,
(I : set (ι → ℝ)) ⊆ J,
Icc I.lower I.upper ⊆ Icc J.lower J.upper,
J.lower ≤ I.lower ∧ I.upper ≤ J.upper] :=
begin
tfae_have : 1 ↔ 2, from iff.rfl,
tfae_have : 2 → 3,
{ intro h,
simpa [coe_eq_pi, closure_pi_set, lower_ne_upper] using closure_mono h },
tfae_have : 3 ↔ 4, from Icc_subset_Icc_iff I.lower_le_upper,
tfae_have : 4 → 2, from λ h x hx i, Ioc_subset_Ioc (h.1 i) (h.2 i) (hx i),
tfae_finish
end
variables {I J}
@[simp, norm_cast] lemma coe_subset_coe : (I : set (ι → ℝ)) ⊆ J ↔ I ≤ J := iff.rfl
lemma le_iff_bounds : I ≤ J ↔ J.lower ≤ I.lower ∧ I.upper ≤ J.upper := (le_tfae I J).out 0 3
lemma injective_coe : injective (coe : box ι → set (ι → ℝ)) :=
begin
rintros ⟨l₁, u₁, h₁⟩ ⟨l₂, u₂, h₂⟩ h,
simp only [subset.antisymm_iff, coe_subset_coe, le_iff_bounds] at h,
congr,
exacts [le_antisymm h.2.1 h.1.1, le_antisymm h.1.2 h.2.2]
end
@[simp, norm_cast] lemma coe_inj : (I : set (ι → ℝ)) = J ↔ I = J :=
injective_coe.eq_iff
@[ext] lemma ext (H : ∀ x, x ∈ I ↔ x ∈ J) : I = J :=
injective_coe $ set.ext H
lemma ne_of_disjoint_coe (h : disjoint (I : set (ι → ℝ)) J) : I ≠ J :=
mt coe_inj.2 $ h.ne I.coe_ne_empty
instance : partial_order (box ι) :=
{ le := (≤),
.. partial_order.lift (coe : box ι → set (ι → ℝ)) injective_coe }
/-- Closed box corresponding to `I : box_integral.box ι`. -/
protected def Icc : box ι ↪o set (ι → ℝ) :=
order_embedding.of_map_le_iff (λ I : box ι, Icc I.lower I.upper) (λ I J, (le_tfae I J).out 2 0)
lemma Icc_def : I.Icc = Icc I.lower I.upper := rfl
@[simp] lemma upper_mem_Icc (I : box ι) : I.upper ∈ I.Icc := right_mem_Icc.2 I.lower_le_upper
@[simp] lemma lower_mem_Icc (I : box ι) : I.lower ∈ I.Icc := left_mem_Icc.2 I.lower_le_upper
protected lemma is_compact_Icc (I : box ι) : is_compact I.Icc := is_compact_Icc
lemma Icc_eq_pi : I.Icc = pi univ (λ i, Icc (I.lower i) (I.upper i)) := (pi_univ_Icc _ _).symm
lemma le_iff_Icc : I ≤ J ↔ I.Icc ⊆ J.Icc := (le_tfae I J).out 0 2
lemma antitone_lower : antitone (λ I : box ι, I.lower) :=
λ I J H, (le_iff_bounds.1 H).1
lemma monotone_upper : monotone (λ I : box ι, I.upper) :=
λ I J H, (le_iff_bounds.1 H).2
lemma coe_subset_Icc : ↑I ⊆ I.Icc := λ x hx, ⟨λ i, (hx i).1.le, λ i, (hx i).2⟩
/-!
### Supremum of two boxes
-/
/-- `I ⊔ J` is the least box that includes both `I` and `J`. Since `↑I ∪ ↑J` is usually not a box,
`↑(I ⊔ J)` is larger than `↑I ∪ ↑J`. -/
instance : has_sup (box ι) :=
⟨λ I J, ⟨I.lower ⊓ J.lower, I.upper ⊔ J.upper,
λ i, (min_le_left _ _).trans_lt $ (I.lower_lt_upper i).trans_le (le_max_left _ _)⟩⟩
instance : semilattice_sup (box ι) :=
{ le_sup_left := λ I J, le_iff_bounds.2 ⟨inf_le_left, le_sup_left⟩,
le_sup_right := λ I J, le_iff_bounds.2 ⟨inf_le_right, le_sup_right⟩,
sup_le := λ I₁ I₂ J h₁ h₂, le_iff_bounds.2 ⟨le_inf (antitone_lower h₁) (antitone_lower h₂),
sup_le (monotone_upper h₁) (monotone_upper h₂)⟩,
.. box.partial_order, .. box.has_sup }
/-!
### `with_bot (box ι)`
In this section we define coercion from `with_bot (box ι)` to `set (ι → ℝ)` by sending `⊥` to `∅`.
-/
instance with_bot_coe : has_coe_t (with_bot (box ι)) (set (ι → ℝ)) := ⟨λ o, o.elim ∅ coe⟩
@[simp, norm_cast] lemma coe_bot : ((⊥ : with_bot (box ι)) : set (ι → ℝ)) = ∅ := rfl
@[simp, norm_cast] lemma coe_coe : ((I : with_bot (box ι)) : set (ι → ℝ)) = I := rfl
lemma is_some_iff : ∀ {I : with_bot (box ι)}, I.is_some ↔ (I : set (ι → ℝ)).nonempty
| ⊥ := by { erw option.is_some, simp }
| (I : box ι) := by { erw option.is_some, simp [I.nonempty_coe] }
lemma bUnion_coe_eq_coe (I : with_bot (box ι)) :
(⋃ (J : box ι) (hJ : ↑J = I), (J : set (ι → ℝ))) = I :=
by induction I using with_bot.rec_bot_coe; simp [with_bot.coe_eq_coe]
@[simp, norm_cast] lemma with_bot_coe_subset_iff {I J : with_bot (box ι)} :
(I : set (ι → ℝ)) ⊆ J ↔ I ≤ J :=
begin
induction I using with_bot.rec_bot_coe, { simp },
induction J using with_bot.rec_bot_coe, { simp [subset_empty_iff] },
simp
end
@[simp, norm_cast] lemma with_bot_coe_inj {I J : with_bot (box ι)} :
(I : set (ι → ℝ)) = J ↔ I = J :=
by simp only [subset.antisymm_iff, ← le_antisymm_iff, with_bot_coe_subset_iff]
/-- Make a `with_bot (box ι)` from a pair of corners `l u : ι → ℝ`. If `l i < u i` for all `i`,
then the result is `⟨l, u, _⟩ : box ι`, otherwise it is `⊥`. In any case, the result interpreted
as a set in `ι → ℝ` is the set `{x : ι → ℝ | ∀ i, x i ∈ Ioc (l i) (u i)}`. -/
def mk' (l u : ι → ℝ) : with_bot (box ι) :=
if h : ∀ i, l i < u i then ↑(⟨l, u, h⟩ : box ι) else ⊥
@[simp] lemma mk'_eq_bot {l u : ι → ℝ} : mk' l u = ⊥ ↔ ∃ i, u i ≤ l i :=
by { rw mk', split_ifs; simpa using h }
@[simp] lemma mk'_eq_coe {l u : ι → ℝ} : mk' l u = I ↔ l = I.lower ∧ u = I.upper :=
begin
cases I with lI uI hI, rw mk', split_ifs,
{ simp [with_bot.coe_eq_coe] },
{ suffices : l = lI → u ≠ uI, by simpa,
rintro rfl rfl, exact h hI }
end
@[simp] lemma coe_mk' (l u : ι → ℝ) : (mk' l u : set (ι → ℝ)) = pi univ (λ i, Ioc (l i) (u i)) :=
begin
rw mk', split_ifs,
{ exact coe_eq_pi _ },
{ rcases not_forall.mp h with ⟨i, hi⟩,
rw [coe_bot, univ_pi_eq_empty], exact Ioc_eq_empty hi }
end
instance : has_inf (with_bot (box ι)) :=
⟨λ I, with_bot.rec_bot_coe (λ J, ⊥) (λ I J, with_bot.rec_bot_coe ⊥
(λ J, mk' (I.lower ⊔ J.lower) (I.upper ⊓ J.upper)) J) I⟩
@[simp] lemma coe_inf (I J : with_bot (box ι)) : (↑(I ⊓ J) : set (ι → ℝ)) = I ∩ J :=
begin
induction I using with_bot.rec_bot_coe, { change ∅ = _, simp },
induction J using with_bot.rec_bot_coe, { change ∅ = _, simp },
change ↑(mk' _ _) = _,
simp only [coe_eq_pi, ← pi_inter_distrib, Ioc_inter_Ioc, pi.sup_apply, pi.inf_apply, coe_mk',
coe_coe]
end
instance : lattice (with_bot (box ι)) :=
{ inf_le_left := λ I J,
begin
rw [← with_bot_coe_subset_iff, coe_inf],
exact inter_subset_left _ _
end,
inf_le_right := λ I J,
begin
rw [← with_bot_coe_subset_iff, coe_inf],
exact inter_subset_right _ _
end,
le_inf := λ I J₁ J₂ h₁ h₂,
begin
simp only [← with_bot_coe_subset_iff, coe_inf] at *,
exact subset_inter h₁ h₂
end,
.. with_bot.semilattice_sup, .. box.with_bot.has_inf }
@[simp, norm_cast] lemma disjoint_with_bot_coe {I J : with_bot (box ι)} :
disjoint (I : set (ι → ℝ)) J ↔ disjoint I J :=
by { simp only [disjoint_iff_inf_le, ← with_bot_coe_subset_iff, coe_inf], refl }
lemma disjoint_coe : disjoint (I : with_bot (box ι)) J ↔ disjoint (I : set (ι → ℝ)) J :=
disjoint_with_bot_coe.symm
lemma not_disjoint_coe_iff_nonempty_inter :
¬disjoint (I : with_bot (box ι)) J ↔ (I ∩ J : set (ι → ℝ)).nonempty :=
by rw [disjoint_coe, set.not_disjoint_iff_nonempty_inter]
/-!
### Hyperface of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`
-/
/-- Face of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`: the box in `ℝⁿ = fin n → ℝ` with corners at
`I.lower ∘ fin.succ_above i` and `I.upper ∘ fin.succ_above i`. -/
@[simps { simp_rhs := tt }] def face {n} (I : box (fin (n + 1))) (i : fin (n + 1)) : box (fin n) :=
⟨I.lower ∘ fin.succ_above i, I.upper ∘ fin.succ_above i, λ j, I.lower_lt_upper _⟩
@[simp] lemma face_mk {n} (l u : fin (n + 1) → ℝ) (h : ∀ i, l i < u i) (i : fin (n + 1)) :
face ⟨l, u, h⟩ i = ⟨l ∘ fin.succ_above i, u ∘ fin.succ_above i, λ j, h _⟩ :=
rfl
@[mono] lemma face_mono {n} {I J : box (fin (n + 1))} (h : I ≤ J) (i : fin (n + 1)) :
face I i ≤ face J i :=
λ x hx i, Ioc_subset_Ioc ((le_iff_bounds.1 h).1 _) ((le_iff_bounds.1 h).2 _) (hx _)
lemma monotone_face {n} (i : fin (n + 1)) : monotone (λ I, face I i) := λ I J h, face_mono h i
lemma maps_to_insert_nth_face_Icc {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Icc (I.lower i) (I.upper i)) :
maps_to (i.insert_nth x) (I.face i).Icc I.Icc :=
λ y hy, fin.insert_nth_mem_Icc.2 ⟨hx, hy⟩
lemma maps_to_insert_nth_face {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Ioc (I.lower i) (I.upper i)) :
maps_to (i.insert_nth x) (I.face i) I :=
λ y hy, by simpa only [mem_coe, mem_def, i.forall_iff_succ_above, hx, fin.insert_nth_apply_same,
fin.insert_nth_apply_succ_above, true_and]
lemma continuous_on_face_Icc {X} [topological_space X] {n} {f : (fin (n + 1) → ℝ) → X}
{I : box (fin (n + 1))} (h : continuous_on f I.Icc) {i : fin (n + 1)} {x : ℝ}
(hx : x ∈ Icc (I.lower i) (I.upper i)) :
continuous_on (f ∘ i.insert_nth x) (I.face i).Icc :=
h.comp (continuous_on_const.fin_insert_nth i continuous_on_id) (I.maps_to_insert_nth_face_Icc hx)
/-!
### Covering of the interior of a box by a monotone sequence of smaller boxes
-/
/-- The interior of a box. -/
protected def Ioo : box ι →o set (ι → ℝ) :=
{ to_fun := λ I, pi univ (λ i, Ioo (I.lower i) (I.upper i)),
monotone' := λ I J h, pi_mono $ λ i hi, Ioo_subset_Ioo ((le_iff_bounds.1 h).1 i)
((le_iff_bounds.1 h).2 i) }
lemma Ioo_subset_coe (I : box ι) : I.Ioo ⊆ I := λ x hx i, Ioo_subset_Ioc_self (hx i trivial)
protected lemma Ioo_subset_Icc (I : box ι) : I.Ioo ⊆ I.Icc := I.Ioo_subset_coe.trans coe_subset_Icc
lemma Union_Ioo_of_tendsto [finite ι] {I : box ι} {J : ℕ → box ι} (hJ : monotone J)
(hl : tendsto (lower ∘ J) at_top (𝓝 I.lower)) (hu : tendsto (upper ∘ J) at_top (𝓝 I.upper)) :
(⋃ n, (J n).Ioo) = I.Ioo :=
have hl' : ∀ i, antitone (λ n, (J n).lower i),
from λ i, (monotone_eval i).comp_antitone (antitone_lower.comp_monotone hJ),
have hu' : ∀ i, monotone (λ n, (J n).upper i),
from λ i, (monotone_eval i).comp (monotone_upper.comp hJ),
calc (⋃ n, (J n).Ioo) = pi univ (λ i, ⋃ n, Ioo ((J n).lower i) ((J n).upper i)) :
Union_univ_pi_of_monotone (λ i, (hl' i).Ioo (hu' i))
... = I.Ioo :
pi_congr rfl (λ i hi, Union_Ioo_of_mono_of_is_glb_of_is_lub (hl' i) (hu' i)
(is_glb_of_tendsto_at_top (hl' i) (tendsto_pi_nhds.1 hl _))
(is_lub_of_tendsto_at_top (hu' i) (tendsto_pi_nhds.1 hu _)))
lemma exists_seq_mono_tendsto (I : box ι) : ∃ J : ℕ →o box ι, (∀ n, (J n).Icc ⊆ I.Ioo) ∧
tendsto (lower ∘ J) at_top (𝓝 I.lower) ∧ tendsto (upper ∘ J) at_top (𝓝 I.upper) :=
begin
choose a b ha_anti hb_mono ha_mem hb_mem hab ha_tendsto hb_tendsto
using λ i, exists_seq_strict_anti_strict_mono_tendsto (I.lower_lt_upper i),
exact ⟨⟨λ k, ⟨flip a k, flip b k, λ i, hab _ _ _⟩,
λ k l hkl, le_iff_bounds.2 ⟨λ i, (ha_anti i).antitone hkl, λ i, (hb_mono i).monotone hkl⟩⟩,
λ n x hx i hi, ⟨(ha_mem _ _).1.trans_le (hx.1 _), (hx.2 _).trans_lt (hb_mem _ _).2⟩,
tendsto_pi_nhds.2 ha_tendsto, tendsto_pi_nhds.2 hb_tendsto⟩
end
section distortion
variable [fintype ι]
/-- The distortion of a box `I` is the maximum of the ratios of the lengths of its edges.
It is defined as the maximum of the ratios
`nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`. -/
def distortion (I : box ι) : ℝ≥0 :=
finset.univ.sup $ λ i : ι, nndist I.lower I.upper / nndist (I.lower i) (I.upper i)
lemma distortion_eq_of_sub_eq_div {I J : box ι} {r : ℝ}
(h : ∀ i, I.upper i - I.lower i = (J.upper i - J.lower i) / r) :
distortion I = distortion J :=
begin
simp only [distortion, nndist_pi_def, real.nndist_eq', h, map_div₀],
congr' 1 with i,
have : 0 < r,
{ by_contra hr,
have := div_nonpos_of_nonneg_of_nonpos (sub_nonneg.2 $ J.lower_le_upper i) (not_lt.1 hr),
rw ← h at this,
exact this.not_lt (sub_pos.2 $ I.lower_lt_upper i) },
simp_rw [nnreal.finset_sup_div, div_div_div_cancel_right _ ((map_ne_zero real.nnabs).2 this.ne')],
end
lemma nndist_le_distortion_mul (I : box ι) (i : ι) :
nndist I.lower I.upper ≤ I.distortion * nndist (I.lower i) (I.upper i) :=
calc nndist I.lower I.upper =
(nndist I.lower I.upper / nndist (I.lower i) (I.upper i)) * nndist (I.lower i) (I.upper i) :
(div_mul_cancel _ $ mt nndist_eq_zero.1 (I.lower_lt_upper i).ne).symm
... ≤ I.distortion * nndist (I.lower i) (I.upper i) :
mul_le_mul_right' (finset.le_sup $ finset.mem_univ i) _
lemma dist_le_distortion_mul (I : box ι) (i : ι) :
dist I.lower I.upper ≤ I.distortion * (I.upper i - I.lower i) :=
have A : I.lower i - I.upper i < 0, from sub_neg.2 (I.lower_lt_upper i),
by simpa only [← nnreal.coe_le_coe, ← dist_nndist, nnreal.coe_mul, real.dist_eq,
abs_of_neg A, neg_sub] using I.nndist_le_distortion_mul i
lemma diam_Icc_le_of_distortion_le (I : box ι) (i : ι) {c : ℝ≥0} (h : I.distortion ≤ c) :
diam I.Icc ≤ c * (I.upper i - I.lower i) :=
have (0 : ℝ) ≤ c * (I.upper i - I.lower i),
from mul_nonneg c.coe_nonneg (sub_nonneg.2 $ I.lower_le_upper _),
diam_le_of_forall_dist_le this $ λ x hx y hy,
calc dist x y ≤ dist I.lower I.upper : real.dist_le_of_mem_pi_Icc hx hy
... ≤ I.distortion * (I.upper i - I.lower i) : I.dist_le_distortion_mul i
... ≤ c * (I.upper i - I.lower i) :
mul_le_mul_of_nonneg_right h (sub_nonneg.2 (I.lower_le_upper i))
end distortion
end box
end box_integral
|
460bf39465b5b3cbbda2e952a5109c28af1842b4 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/xrewrite1.lean | abb7858300334e15b7939d93e9d5b0abec4931be | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 306 | lean | open nat tactic
constant zeroadd (a : nat) : 0 + a = a
meta definition xrewrite (th_name : name) : tactic unit :=
do th ← mk_const th_name,
rewrite_core semireducible tt tt occurrences.all ff th,
try reflexivity
example (a : nat) : (0 + a) + (0 + a) + (0 + a) = a + a + a :=
by xrewrite `zeroadd
|
55bf4952760efc8f8099de836075cf396f8ffc0c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/335.lean | 396f55ab8fc6f8fd4aecc75e6f50e2ec9b073a5b | [
"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 | 613 | lean | opaque foo : {x : Nat} → Type
opaque bar : {T : Type} → ({x : T} → Type) → Type
structure Baz where
baz : {x : Nat} → Type
#check bar foo
#check fun (b : Baz) => bar b.baz
structure Ty where
ctx : Type
ty : ctx → Type
structure Tm where
ty : Ty
tm : ∀ {Γ}, ty.ty Γ
#check fun (Γ : Type)
(A : Ty)
(Actx : Γ = A.ctx)
(x : Tm)
(xTy : x.ty = A)
=> Eq.rec (motive := fun ty _ => ∀ {Γ:ty.ctx}, ty.ty Γ) (fun {Γ} => x.tm (Γ:=Γ)) xTy
#check fun (Γ : Type)
(A : Ty)
(Actx : Γ = A.ctx)
(x : Tm)
(xTy : x.ty = A)
=> Eq.rec (motive := fun ty _ => ∀ {Γ:ty.ctx}, ty.ty Γ) x.tm xTy
|
e8cc4627a27beac529965ab245f7c672d67fe686 | 367134ba5a65885e863bdc4507601606690974c1 | /src/deprecated/submonoid.lean | ea136e56d84bb947f1ff3ff4ffdf7f47cfcb7ab9 | [
"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 | 20,246 | 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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard
-/
import group_theory.submonoid.basic
import algebra.big_operators.basic
/-!
# Submonoids
This file defines unbundled multiplicative and additive submonoids (deprecated). For bundled form
see `group_theory/submonoid`.
We some results about images and preimages of submonoids under monoid homomorphisms. These theorems
use unbundled monoid homomorphisms (also deprecated).
There are also theorems about the submonoids generated by an element or a subset of a monoid,
defined inductively.
## Implementation notes
Unbundled submonoids will slowly be removed from mathlib.
## Tags
submonoid, submonoids, is_submonoid
-/
open_locale big_operators
variables {M : Type*} [monoid M] {s : set M}
variables {A : Type*} [add_monoid A] {t : set A}
/-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/
class is_add_submonoid (s : set A) : Prop :=
(zero_mem : (0:A) ∈ s)
(add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s)
/-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/
@[to_additive]
class is_submonoid (s : set M) : Prop :=
(one_mem : (1:M) ∈ s)
(mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s)
lemma additive.is_add_submonoid
(s : set M) : ∀ [is_submonoid s], @is_add_submonoid (additive M) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem additive.is_add_submonoid_iff
{s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI additive.is_add_submonoid _⟩
lemma multiplicative.is_submonoid
(s : set A) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative A) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem multiplicative.is_submonoid_iff
{s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI multiplicative.is_submonoid _⟩
/-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is
an `add_submonoid` of M."]
instance is_submonoid.inter (s₁ s₂ : set M) [is_submonoid s₁] [is_submonoid s₂] :
is_submonoid (s₁ ∩ s₂) :=
{ one_mem := ⟨is_submonoid.one_mem, is_submonoid.one_mem⟩,
mul_mem := λ x y hx hy,
⟨is_submonoid.mul_mem hx.1 hy.1, is_submonoid.mul_mem hx.2 hy.2⟩ }
/-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is
an `add_submonoid` of `M`."]
instance is_submonoid.Inter {ι : Sort*} (s : ι → set M) [h : ∀ y : ι, is_submonoid (s y)] :
is_submonoid (set.Inter s) :=
{ one_mem := set.mem_Inter.2 $ λ y, is_submonoid.one_mem,
mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $
λ y, is_submonoid.mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) }
/-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid
of `M`. -/
@[to_additive "The union of an indexed, directed, nonempty set
of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "]
lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set M) [∀ i, is_submonoid (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_submonoid (⋃i, s i) :=
{ one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem⟩,
mul_mem := λ a b ha hb,
let ⟨i, hi⟩ := set.mem_Union.1 ha in
let ⟨j, hj⟩ := set.mem_Union.1 hb in
let ⟨k, hk⟩ := directed i j in
set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ }
section powers
/-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/
def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y}
/-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/
def multiples (x : A) : set A := {y | ∃ n:ℕ, n •ℕ x = y}
attribute [to_additive multiples] powers
/-- 1 is in the set of natural number powers of an element of a monoid. -/
lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩
/-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/
lemma multiples.zero_mem {x : A} : (0 : A) ∈ multiples x := ⟨0, zero_nsmul _⟩
attribute [to_additive] powers.one_mem
/-- An element of a monoid is in the set of that element's natural number powers. -/
lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩
/-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/
lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, one_nsmul _⟩
attribute [to_additive] powers.self_mem
/-- The set of natural number powers of an element of a monoid is closed under multiplication. -/
lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) :=
λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩
/-- The set of natural number multiples of an element of an `add_monoid` is closed under
addition. -/
lemma multiples.add_mem {x y z : A} :
(y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) :=
@powers.mul_mem (multiplicative A) _ _ _ _
attribute [to_additive] powers.mul_mem
/-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The set of natural number multiples of an element of
an `add_monoid` `M` is an `add_submonoid` of `M`."]
instance powers.is_submonoid (x : M) : is_submonoid (powers x) :=
{ one_mem := powers.one_mem,
mul_mem := λ y z, powers.mul_mem }
/-- A monoid is a submonoid of itself. -/
@[to_additive "An `add_monoid` is an `add_submonoid` of itself."]
instance univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp
/-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/
@[to_additive "The preimage of an `add_submonoid` under an `add_monoid` hom is
an `add_submonoid` of the domain."]
instance preimage.is_submonoid {N : Type*} [monoid N] (f : M → N) [is_monoid_hom f]
(s : set N) [is_submonoid s] : is_submonoid (f ⁻¹' s) :=
{ one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem,
mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s),
show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb }
/-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/
@[instance, to_additive "The image of an `add_submonoid` under an `add_monoid`
hom is an `add_submonoid` of the codomain."]
lemma image.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f]
(s : set M) [is_submonoid s] : is_submonoid (f '' s) :=
{ one_mem := ⟨1, is_submonoid.one_mem, is_monoid_hom.map_one f⟩,
mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1,
by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ }
/-- The image of a monoid hom is a submonoid of the codomain. -/
@[to_additive "The image of an `add_monoid` hom is an `add_submonoid`
of the codomain."]
instance range.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] :
is_submonoid (set.range f) :=
by rw ← set.image_univ; apply_instance
/-- Submonoids are closed under natural powers. -/
lemma is_submonoid.pow_mem {a : M} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s
| 0 := is_submonoid.one_mem
| (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem
/-- An `add_submonoid` is closed under multiplication by naturals. -/
lemma is_add_submonoid.smul_mem {a : A} [is_add_submonoid t] :
∀ (h : a ∈ t) {n : ℕ}, n •ℕ a ∈ t :=
@is_submonoid.pow_mem (multiplicative A) _ _ _ (multiplicative.is_submonoid _)
attribute [to_additive smul_mem] is_submonoid.pow_mem
/-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/
lemma is_submonoid.power_subset {a : M} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s :=
assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h
/-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the
`add_submonoid`. -/
lemma is_add_submonoid.multiple_subset {a : A} [is_add_submonoid t] :
a ∈ t → multiples a ⊆ t :=
@is_submonoid.power_subset (multiplicative A) _ _ _ (multiplicative.is_submonoid _)
attribute [to_additive multiple_subset] is_submonoid.power_subset
end powers
namespace is_submonoid
/-- The product of a list of elements of a submonoid is an element of the submonoid. -/
@[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the
`add_submonoid`."]
lemma list_prod_mem [is_submonoid s] : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s
| [] h := one_mem
| (a::l) h :=
suffices a * l.prod ∈ s, by simpa,
have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h,
is_submonoid.mul_mem this.1 (list_prod_mem this.2)
/-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of
the submonoid. -/
@[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid`
is an element of the `add_submonoid`. "]
lemma multiset_prod_mem {M} [comm_monoid M] (s : set M) [is_submonoid s] (m : multiset M) :
(∀a∈m, a ∈ s) → m.prod ∈ s :=
begin
refine quotient.induction_on m (assume l hl, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod],
exact list_prod_mem hl
end
/-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element
of the submonoid. -/
@[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by
a `finset` is an element of the `add_submonoid`."]
lemma finset_prod_mem {M A} [comm_monoid M] (s : set M) [is_submonoid s] (f : A → M) :
∀(t : finset A), (∀b∈t, f b ∈ s) → ∏ b in t, f b ∈ s
| ⟨m, hm⟩ hs := multiset_prod_mem s _ (by simpa)
end is_submonoid
-- TODO: modify `subtype_instance` to produce this definition, then use it here
-- and for `subtype.group`
/-- Submonoids are themselves monoids. -/
@[to_additive "An `add_submonoid` is itself an `add_monoid`."]
def subtype.monoid {s : set M} [is_submonoid s] : monoid s :=
{ one := ⟨1, is_submonoid.one_mem⟩,
mul := λ x y, ⟨x * y, is_submonoid.mul_mem x.2 y.2⟩,
mul_one := λ x, subtype.eq $ mul_one x.1,
one_mul := λ x, subtype.eq $ one_mul x.1,
mul_assoc := λ x y z, subtype.eq $ mul_assoc x.1 y.1 z.1 }
/-- Submonoids of commutative monoids are themselves commutative monoids. -/
@[to_additive "An `add_submonoid` of a commutative `add_monoid` is itself
a commutative `add_monoid`. "]
def subtype.comm_monoid {M} [comm_monoid M] {s : set M} [is_submonoid s] : comm_monoid s :=
{ mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1,
.. subtype.monoid }
section
local attribute [instance] subtype.monoid subtype.add_monoid
/-- Submonoids inherit the 1 of the monoid. -/
@[simp, norm_cast, to_additive "An `add_submonoid` inherits the 0 of the `add_monoid`. "]
lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : M) = 1 := rfl
attribute [norm_cast] is_add_submonoid.coe_zero
/-- Submonoids inherit the multiplication of the monoid. -/
@[simp, norm_cast, to_additive "An `add_submonoid` inherits the addition of the `add_monoid`. "]
lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : M) = a * b := rfl
attribute [norm_cast] is_add_submonoid.coe_add
/-- Submonoids inherit the exponentiation by naturals of the monoid. -/
@[simp, norm_cast] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) :
((a ^ n : s) : M) = a ^ n :=
by induction n; simp [*, pow_succ]
/-- An `add_submonoid` inherits the multiplication by naturals of the `add_monoid`. -/
@[simp, norm_cast] lemma is_add_submonoid.smul_coe {A : Type*} [add_monoid A] {s : set A}
[is_add_submonoid s] (a : s) (n : ℕ) : ((n •ℕ a : s) : A) = n •ℕ a :=
by {induction n, refl, simp [*, succ_nsmul]}
attribute [to_additive smul_coe] is_submonoid.coe_pow
/-- The natural injection from a submonoid into the monoid is a monoid hom. -/
@[to_additive "The natural injection from an `add_submonoid` into
the `add_monoid` is an `add_monoid` hom. "]
instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → M) :=
{ map_one := rfl, map_mul := λ _ _, rfl }
/-- The natural injection from a submonoid into the monoid is a monoid hom. -/
@[to_additive "The natural injection from an `add_submonoid` into
the `add_monoid` is an `add_monoid` hom. "]
instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → M) :=
subtype_val.is_monoid_hom
/-- Given a monoid hom `f : γ → M` whose image is contained in a submonoid `s`, the induced map
from `γ` to `s` is a monoid hom. -/
@[to_additive "Given an `add_monoid` hom `f : γ → M` whose image is contained in
an `add_submonoid` s, the induced map from `γ` to `s` is an `add_monoid` hom."]
instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → M)
[is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) :=
{ map_one := subtype.eq (is_monoid_hom.map_one f),
map_mul := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) }
/-- Given two submonoids `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is
a monoid hom. -/
@[to_additive "Given two `add_submonoid`s `s` and `t` such that `s ⊆ t`, the
natural injection from `s` into `t` is an `add_monoid` hom."]
instance set_inclusion.is_monoid_hom (t : set M) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) :
is_monoid_hom (set.inclusion h) :=
subtype_mk.is_monoid_hom _ _
end
namespace add_monoid
/-- The inductively defined membership predicate for the submonoid generated by a subset of a
monoid. -/
inductive in_closure (s : set A) : A → Prop
| basic {a : A} : a ∈ s → in_closure a
| zero : in_closure 0
| add {a b : A} : in_closure a → in_closure b → in_closure (a + b)
end add_monoid
namespace monoid
/-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an
add_monoid. -/
inductive in_closure (s : set M) : M → Prop
| basic {a : M} : a ∈ s → in_closure a
| one : in_closure 1
| mul {a b : M} : in_closure a → in_closure b → in_closure (a * b)
attribute [to_additive] monoid.in_closure
attribute [to_additive] monoid.in_closure.one
attribute [to_additive] monoid.in_closure.mul
/-- The inductively defined submonoid generated by a subset of a monoid. -/
@[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."]
def closure (s : set M) : set M := {a | in_closure s a }
@[to_additive]
instance closure.is_submonoid (s : set M) : is_submonoid (closure s) :=
{ one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul }
/-- A subset of a monoid is contained in the submonoid it generates. -/
@[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."]
theorem subset_closure {s : set M} : s ⊆ closure s :=
assume a, in_closure.basic
/-- The submonoid generated by a set is contained in any submonoid that contains the set. -/
@[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that
contains the set."]
theorem closure_subset {s t : set M} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t :=
assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem]
/-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is
contained in the submonoid generated by `t`. -/
@[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid`
of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."]
theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
/-- The submonoid generated by an element of a monoid equals the set of natural number powers of
the element. -/
@[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of
natural number multiples of the element."]
theorem closure_singleton {x : M} : closure ({x} : set M) = powers x :=
set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $
is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure
/-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated
by the image of the set under the monoid hom. -/
@[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals
the `add_submonoid` generated by the image of the set under the `add_monoid` hom."]
lemma image_closure {A : Type*} [monoid A] (f : M → A) [is_monoid_hom f] (s : set M) :
f '' closure s = closure (f '' s) :=
le_antisymm
begin
rintros _ ⟨x, hx, rfl⟩,
apply in_closure.rec_on hx; intros,
{ solve_by_elim [subset_closure, set.mem_image_of_mem] },
{ rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem },
{ rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] }
end
(closure_subset $ set.image_subset _ subset_closure)
/-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists
a list of elements of `s` whose product is `a`. -/
@[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by
a set `s`, there exists a list of elements of `s` whose sum is `a`."]
theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) :
(∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) :=
begin
induction h,
case in_closure.basic : a ha { existsi ([a]), simp [ha] },
case in_closure.one { existsi ([]), simp },
case in_closure.mul : a b _ _ ha hb {
rcases ha with ⟨la, ha, eqa⟩,
rcases hb with ⟨lb, hb, eqb⟩,
existsi (la ++ lb),
simp [eqa.symm, eqb.symm, or_imp_distrib],
exact assume a, ⟨ha a, hb a⟩
}
end
/-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by
`s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the
submonoid generated by `t` whose product is `x`. -/
@[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid`
of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s`
and an element of the `add_submonoid` generated by `t` whose sum is `x`."]
theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x :=
⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸
list.rec_on L (λ _, ⟨1, is_submonoid.one_mem, 1, is_submonoid.one_mem, mul_one _⟩)
(λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in
or.cases_on (HL1 hd $ list.mem_cons_self _ _)
(λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz,
by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩)
(λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht),
by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1,
λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy)
(closure_mono (set.subset_union_right _ _) hz)⟩
end monoid
/-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/
@[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."]
def submonoid.of (s : set M) [h : is_submonoid s] : submonoid M := ⟨s, h.1, h.2⟩
@[to_additive]
instance submonoid.is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.2, S.3⟩
|
8a2f45b8b5cb44f46d9989c1f448c0d552c6a3a3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/order/floor.lean | 2d23ea9abdb7acabb846dbdcd48c981c491732e3 | [
"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,570 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import algebra.order.floor
import topology.algebra.order.basic
/-!
# Topological facts about `int.floor`, `int.ceil` and `int.fract`
This file proves statements about limits and continuity of functions involving `floor`, `ceil` and
`fract`.
## Main declarations
* `tendsto_floor_at_top`, `tendsto_floor_at_bot`, `tendsto_ceil_at_top`, `tendsto_ceil_at_bot`:
`int.floor` and `int.ceil` tend to +-∞ in +-∞.
* `continuous_on_floor`: `int.floor` is continuous on `Ico n (n + 1)`, because constant.
* `continuous_on_ceil`: `int.ceil` is continuous on `Ioc n (n + 1)`, because constant.
* `continuous_on_fract`: `int.fract` is continuous on `Ico n (n + 1)`.
* `continuous_on.comp_fract`: Precomposing a continuous function satisfying `f 0 = f 1` with
`int.fract` yields another continuous function.
-/
open filter function int set
open_locale topological_space
variables {α β γ : Type*} [linear_ordered_ring α] [floor_ring α]
lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top :=
floor_mono.tendsto_at_top_at_top $ λ b, ⟨(b + 1 : ℤ), by { rw floor_coe, exact (lt_add_one _).le }⟩
lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot :=
floor_mono.tendsto_at_bot_at_bot $ λ b, ⟨b, (floor_coe _).le⟩
lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top :=
ceil_mono.tendsto_at_top_at_top $ λ b, ⟨b, (ceil_coe _).ge⟩
lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot :=
ceil_mono.tendsto_at_bot_at_bot $ λ b, ⟨(b - 1 : ℤ), by { rw ceil_coe, exact (sub_one_lt _).le }⟩
variables [topological_space α]
lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) :=
(continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const
lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) :=
(continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const
lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) :
tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝 n) :=
begin
rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)),
simpa only [floor_coe] using
(continuous_on_floor n _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto
end
lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) :
tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝 n) :=
begin
rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)),
simpa only [ceil_coe] using
(continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto
end
lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) :
tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝[≥] n) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _)
begin
refine (eventually_nhds_within_of_forall $ λ x (hx : (n : α) ≤ x), _),
change _ ≤ _,
norm_cast,
convert ← floor_mono hx,
rw floor_eq_iff,
exact ⟨le_rfl, lt_add_one _⟩
end
lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) :
tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝[≤] n) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _)
begin
refine (eventually_nhds_within_of_forall $ λ x (hx : x ≤ (n : α)), _),
change _ ≤ _,
norm_cast,
convert ← ceil_mono hx,
rw ceil_eq_iff,
exact ⟨sub_one_lt _, le_rfl⟩
end
lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) :
tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝[≤] (n-1)) :=
begin
rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)),
convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm))
(tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds
(eventually_of_forall (λ _, mem_Iic.mpr $ le_rfl)));
norm_cast <|> apply_instance,
ring
end
lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) :
tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝[≥] (n+1)) :=
begin
rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)),
convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm))
(tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds
(eventually_of_forall (λ _, mem_Ici.mpr $ le_rfl)));
norm_cast <|> apply_instance,
ring
end
lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) :
tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝 (n-1)) :=
begin
rw ← nhds_within_univ,
exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n),
end
lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) :
tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝 (n+1)) :=
begin
rw ← nhds_within_univ,
exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n),
end
lemma continuous_on_fract [topological_add_group α] (n : ℤ) :
continuous_on (fract : α → α) (Ico n (n+1) : set α) :=
continuous_on_id.sub (continuous_on_floor n)
lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α]
(n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝 1) :=
begin
convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n);
[{norm_cast, ring}, apply_instance, apply_instance]
end
lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α]
(n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝[<] 1) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
(tendsto_fract_left' _) (eventually_of_forall fract_lt_one)
lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α]
(n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝 0) :=
begin
convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n);
[exact (sub_self _).symm, apply_instance, apply_instance]
end
lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α]
(n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝[≥] 0) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
(tendsto_fract_right' _) (eventually_of_forall fract_nonneg)
local notation `I` := (Icc 0 1 : set α)
variables [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ]
/-- Do not use this, use `continuous_on.comp_fract` instead. -/
lemma continuous_on.comp_fract' {f : β → α → γ}
(h : continuous_on (uncurry f) $ (univ : set β) ×ˢ I) (hf : ∀ s, f s 0 = f s 1) :
continuous (λ st : β × α, f st.1 $ fract st.2) :=
begin
change continuous ((uncurry f) ∘ (prod.map id (fract))),
rw continuous_iff_continuous_at,
rintro ⟨s, t⟩,
by_cases ht : t = floor t,
{ rw ht,
rw ← continuous_within_at_univ,
have : (univ : set (β × α)) ⊆ ((univ : set β) ×ˢ Iio ↑⌊t⌋) ∪ ((univ : set β) ×ˢ Ici ↑⌊t⌋),
{ rintros p -,
rw ← prod_union,
exact ⟨trivial, lt_or_le p.2 _⟩ },
refine continuous_within_at.mono _ this,
refine continuous_within_at.union _ _,
{ simp only [continuous_within_at, fract_coe, nhds_within_prod_eq,
nhds_within_univ, id.def, comp_app, prod.map_mk],
have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)),
by simp [uncurry, hf],
rw this,
refine (h _ ⟨true.intro, by exact_mod_cast right_mem_Icc.mpr zero_le_one⟩).tendsto.comp _,
rw [nhds_within_prod_eq, nhds_within_univ],
rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _ _),
exact tendsto_id.prod_map
(tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) },
{ simp only [continuous_within_at, fract_coe, nhds_within_prod_eq,
nhds_within_univ, id.def, comp_app, prod.map_mk],
refine (h _ ⟨true.intro, by exact_mod_cast left_mem_Icc.mpr zero_le_one⟩).tendsto.comp _,
rw [nhds_within_prod_eq, nhds_within_univ,
nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _ _)],
exact tendsto_id.prod_map (tendsto_fract_right _) } },
{ have : t ∈ Ioo (floor t : α) ((floor t : α) + 1),
from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩,
apply (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp,
simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk],
exact continuous_at_id.tendsto.prod_map
(tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
(((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono
Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2))
(eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) }
end
lemma continuous_on.comp_fract
{s : β → α}
{f : β → α → γ}
(h : continuous_on (uncurry f) $ (univ : set β) ×ˢ (Icc 0 1 : set α))
(hs : continuous s)
(hf : ∀ s, f s 0 = f s 1) :
continuous (λ x : β, f x $ int.fract (s x)) :=
(h.comp_fract' hf).comp (continuous_id.prod_mk hs)
/-- A special case of `continuous_on.comp_fract`. -/
lemma continuous_on.comp_fract'' {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) :
continuous (f ∘ fract) :=
continuous_on.comp_fract (h.comp continuous_on_snd $ λ x hx, (mem_prod.mp hx).2)
continuous_id (λ _, hf)
|
93605298e5fd1e3d89c137862c44c7aa43d447e5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Coe.lean | 1b83ca4198cfc7d9a74e55b007e0116e7c23daa4 | [
"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 | 13,312 | 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.Prelude
set_option linter.missingDocs true -- keep it documented
/-!
# Coercion
Lean uses a somewhat elaborate system of typeclasses to drive the coercion system.
Here a *coercion* means an invisible function that is automatically inserted
to fix what would otherwise be a type error. For example, if we have:
```
def f (x : Nat) : Int := x
```
then this is clearly not type correct as is, because `x` has type `Nat` but
type `Int` is expected, and normally you will get an error message saying exactly that.
But before it shows that message, it will attempt to synthesize an instance of
`CoeT Nat x Int`, which will end up going through all the other typeclasses defined
below, to discover that there is an instance of `Coe Nat Int` defined.
This instance is defined as:
```
instance : Coe Nat Int := ⟨Int.ofNat⟩
```
so Lean will elaborate the original function `f` as if it said:
```
def f (x : Nat) : Int := Int.ofNat x
```
which is not a type error anymore.
You can also use the `↑` operator to explicitly indicate a coercion. Using `↑x`
instead of `x` in the example will result in the same output.
Because there are many polymorphic functions in Lean, it is often ambiguous where
the coercion can go. For example:
```
def f (x y : Nat) : Int := x + y
```
This could be either `↑x + ↑y` where `+` is the addition on `Int`, or `↑(x + y)`
where `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition
with the type `Nat → Nat → Int`. You can use the `↑` operator to disambiguate
between these possibilities, but generally Lean will elaborate working from the
"outside in", meaning that it will first look at the expression `_ + _ : Int`
and assign the `+` to be the one for `Int`, and then need to insert coercions
for the subterms `↑x : Int` and `↑y : Int`, resulting in the `↑x + ↑y` version.
Note that unlike most operators like `+`, `↑` is always eagerly unfolded at
parse time into its definition. So if we look at the definition of `f` from
before, we see no trace of the `CoeT.coe` function:
```
def f (x : Nat) : Int := x
#print f
-- def f : Nat → Int :=
-- fun (x : Nat) => Int.ofNat x
```
## Important typeclasses
Lean resolves a coercion by either inserting a `CoeDep` instance
or chaining `CoeHead? CoeOut* Coe* CoeTail?` instances.
(That is, zero or one `CoeHead` instances, an arbitrary number of `CoeOut`
instances, etc.)
The `CoeHead? CoeOut*` instances are chained from the "left" side.
So if Lean looks for a coercion from `Nat` to `Int`, it starts by trying coerce
`Nat` using `CoeHead` by looking for a `CoeHead Nat ?α` instance, and then
continuing with `CoeOut`. Similarly `Coe* CoeTail?` are chained from the "right".
These classes should be implemented for coercions:
* `Coe α β` is the most basic class, and the usual one you will want to use
when implementing a coercion for your own types.
The variables in the type `α` must be a subset of the variables in `β`
(or out-params of type class parameters),
because `Coe` is chained right-to-left.
* `CoeOut α β` is like `Coe α β` but chained left-to-right.
Use this if the variables in the type `α` are a superset of the variables in `β`.
* `CoeTail α β` is like `Coe α β`, but only applied once.
Use this for coercions that would cause loops, like `[Ring R] → CoeTail Nat R`.
* `CoeHead α β` is similar to `CoeOut α β`, but only applied once.
Use this for coercions that would cause loops, like `[SetLike S α] → CoeHead S (Set α)`.
* `CoeDep α (x : α) β` allows `β` to depend not only on `α` but on the value
`x : α` itself. This is useful when the coercion function is dependent.
An example of a dependent coercion is the instance for `Prop → Bool`, because
it only holds for `Decidable` propositions. It is defined as:
```
instance (p : Prop) [Decidable p] : CoeDep Prop p Bool := ...
```
* `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a
(coercion-to-)function type, and this is triggered whenever an element
`f : α` appears in an application like `f x` which would not make sense since
`f` does not have a function type.
`CoeFun` instances apply to `CoeOut` as well.
* `CoeSort α β` is a coercion to a sort. `β` must be a universe, and this is
triggered when `a : α` appears in a place where a type is expected, like
`(x : a)` or `a → a`.
`CoeSort` instances apply to `CoeOut` as well.
On top of these instances this file defines several auxiliary type classes:
* `CoeTC := Coe*`
* `CoeOTC := CoeOut* Coe*`
* `CoeHTC := CoeHead? CoeOut* Coe*`
* `CoeHTCT := CoeHead? CoeOut* Coe* CoeTail?`
* `CoeDep := CoeHead? CoeOut* Coe* CoeTail? | CoeDep`
-/
universe u v w w'
/--
`Coe α β` is the typeclass for coercions from `α` to `β`. It can be transitively
chained with other `Coe` instances, and coercion is automatically used when
`x` has type `α` but it is used in a context where `β` is expected.
You can use the `↑x` operator to explicitly trigger coercion.
-/
class Coe (α : semiOutParam (Sort u)) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] Coe.coe
/--
Auxiliary class implementing `Coe*`.
Users should generally not implement this directly.
-/
class CoeTC (α : Sort u) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeTC.coe
instance [Coe β γ] [CoeTC α β] : CoeTC α γ where coe a := Coe.coe (CoeTC.coe a : β)
instance [Coe α β] : CoeTC α β where coe a := Coe.coe a
instance : CoeTC α α where coe a := a
/--
`CoeOut α β` is for coercions that are applied from left-to-right.
-/
class CoeOut (α : Sort u) (β : semiOutParam (Sort v)) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeOut.coe
/--
Auxiliary class implementing `CoeOut* Coe*`.
Users should generally not implement this directly.
-/
class CoeOTC (α : Sort u) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeOTC.coe
instance [CoeOut α β] [CoeOTC β γ] : CoeOTC α γ where coe a := CoeOTC.coe (CoeOut.coe a : β)
instance [CoeTC α β] : CoeOTC α β where coe a := CoeTC.coe a
instance : CoeOTC α α where coe a := a
-- Note: ^^ We add reflexivity instances for CoeOTC/etc. so that we avoid going
-- through a user-defined CoeTC/etc. instance. (Instances like
-- `CoeTC F (A →+ B)` apply even when the two sides are defeq.)
/--
`CoeHead α β` is for coercions that are applied from left-to-right at most once
at beginning of the coercion chain.
-/
class CoeHead (α : Sort u) (β : semiOutParam (Sort v)) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeHead.coe
/--
Auxiliary class implementing `CoeHead CoeOut* Coe*`.
Users should generally not implement this directly.
-/
class CoeHTC (α : Sort u) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeHTC.coe
instance [CoeHead α β] [CoeOTC β γ] : CoeHTC α γ where coe a := CoeOTC.coe (CoeHead.coe a : β)
instance [CoeOTC α β] : CoeHTC α β where coe a := CoeOTC.coe a
instance : CoeHTC α α where coe a := a
/--
`CoeTail α β` is for coercions that can only appear at the end of a
sequence of coercions. That is, `α` can be further coerced via `Coe σ α` and
`CoeHead τ σ` instances but `β` will only be the expected type of the expression.
-/
class CoeTail (α : semiOutParam (Sort u)) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeTail.coe
/--
Auxiliary class implementing `CoeHead* Coe* CoeTail?`.
Users should generally not implement this directly.
-/
class CoeHTCT (α : Sort u) (β : Sort v) where
/-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,
or by double type ascription `((x : α) : β)`. -/
coe : α → β
attribute [coe_decl] CoeHTCT.coe
instance [CoeTail β γ] [CoeHTC α β] : CoeHTCT α γ where coe a := CoeTail.coe (CoeHTC.coe a : β)
instance [CoeHTC α β] : CoeHTCT α β where coe a := CoeHTC.coe a
instance : CoeHTCT α α where coe a := a
/--
`CoeDep α (x : α) β` is a typeclass for dependent coercions, that is, the type `β`
can depend on `x` (or rather, the value of `x` is available to typeclass search
so an instance that relates `β` to `x` is allowed).
Dependent coercions do not participate in the transitive chaining process of
regular coercions: they must exactly match the type mismatch on both sides.
-/
class CoeDep (α : Sort u) (_ : α) (β : Sort v) where
/-- The resulting value of type `β`. The input `x : α` is a parameter to
the type class, so the value of type `β` may possibly depend on additional
typeclasses on `x`. -/
coe : β
attribute [coe_decl] CoeDep.coe
/--
`CoeT` is the core typeclass which is invoked by Lean to resolve a type error.
It can also be triggered explicitly with the notation `↑x` or by double type
ascription `((x : α) : β)`.
A `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`.
-/
class CoeT (α : Sort u) (_ : α) (β : Sort v) where
/-- The resulting value of type `β`. The input `x : α` is a parameter to
the type class, so the value of type `β` may possibly depend on additional
typeclasses on `x`. -/
coe : β
attribute [coe_decl] CoeT.coe
instance [CoeHTCT α β] : CoeT α a β where coe := CoeHTCT.coe a
instance [CoeDep α a β] : CoeT α a β where coe := CoeDep.coe a
instance : CoeT α a α where coe := a
/--
`CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a
(coercion-to-)function type, and this is triggered whenever an element
`f : α` appears in an application like `f x`, which would not make sense since
`f` does not have a function type.
`CoeFun` instances apply to `CoeOut` as well.
-/
class CoeFun (α : Sort u) (γ : outParam (α → Sort v)) where
/-- Coerces a value `f : α` to type `γ f`, which should be either be a
function type or another `CoeFun` type, in order to resolve a mistyped
application `f x`. -/
coe : (f : α) → γ f
attribute [coe_decl] CoeFun.coe
instance [CoeFun α fun _ => β] : CoeOut α β where coe a := CoeFun.coe a
/--
`CoeSort α β` is a coercion to a sort. `β` must be a universe, and this is
triggered when `a : α` appears in a place where a type is expected, like
`(x : a)` or `a → a`.
`CoeSort` instances apply to `CoeOut` as well.
-/
class CoeSort (α : Sort u) (β : outParam (Sort v)) where
/-- Coerces a value of type `α` to `β`, which must be a universe. -/
coe : α → β
attribute [coe_decl] CoeSort.coe
instance [CoeSort α β] : CoeOut α β where coe a := CoeSort.coe a
/--
`↑x` represents a coercion, which converts `x` of type `α` to type `β`, using
typeclasses to resolve a suitable conversion function. You can often leave the
`↑` off entirely, since coercion is triggered implicitly whenever there is a
type error, but in ambiguous cases it can be useful to use `↑` to disambiguate
between e.g. `↑x + ↑y` and `↑(x + y)`.
-/
syntax:1024 (name := coeNotation) "↑" term:1024 : term
/-! # Basic instances -/
instance boolToProp : Coe Bool Prop where
coe b := Eq b true
instance boolToSort : CoeSort Bool Prop where
coe b := b
instance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where
coe := decide p
instance optionCoe {α : Type u} : Coe α (Option α) where
coe := some
instance subtypeCoe {α : Sort u} {p : α → Prop} : CoeOut (Subtype p) α where
coe v := v.val
/-! # Coe bridge -/
/--
Helper definition used by the elaborator. It is not meant to be used directly by users.
This is used for coercions between monads, in the case where we want to apply
a monad lift and a coercion on the result type at the same time.
-/
@[inline, coe_decl] def Lean.Internal.liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u}
[MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do
let a ← liftM x
pure (CoeT.coe a)
/--
Helper definition used by the elaborator. It is not meant to be used directly by users.
This is used for coercing the result type under a monad.
-/
@[inline, coe_decl] def Lean.Internal.coeM {m : Type u → Type v} {α β : Type u}
[∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do
let a ← x
pure (CoeT.coe a)
|
70b92ca04a8f54bd1b317b94324e6116437f9117 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/holor.lean | ead3071a3de04eacb2b017dd9ee5260ef3f35c64 | [
"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 | 14,793 | lean | /-
Copyright (c) 2018 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import algebra.module.pi
import algebra.big_operators.basic
/-!
# Basic properties of holors
Holors are indexed collections of tensor coefficients. Confusingly,
they are often called tensors in physics and in the neural network
community.
A holor is simply a multidimensional array of values. The size of a
holor is specified by a `list ℕ`, whose length is called the dimension
of the holor.
The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the
holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of
rank at most 1" if it is a tensor product of one-dimensional holors.
The CP rank of a holor `x` is the smallest N such that `x` is the sum
of N holors of rank at most 1.
Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html>
## References
* <https://en.wikipedia.org/wiki/Tensor_rank_decomposition>
-/
universes u
open list
open_locale big_operators
/-- `holor_index ds` is the type of valid index tuples used to identify an entry of a holor
of dimensions `ds`. -/
def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds}
namespace holor_index
variables {ds₁ ds₂ ds₃ : list ℕ}
def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁
| ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩
def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂
| ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩
lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) :
(cast (congr_arg holor_index eq) ⟨is, h⟩).val = is :=
by subst eq; refl
def assoc_right :
holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm)
lemma take_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.take = t.take.take
| ⟨ is , h ⟩ := subtype.eq $ by simp [assoc_right,take, cast_type, list.take_take,
nat.le_add_right, min_eq_left]
lemma drop_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.take = t.take.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take])
lemma drop_drop :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.drop = t.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop])
end holor_index
/-- Holor (indexed collections of tensor coefficients) -/
def holor (α : Type u) (ds:list ℕ) := holor_index ds → α
namespace holor
variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ}
instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩
instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩
instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩
instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩
instance [add_semigroup α] : add_semigroup (holor α ds) :=
by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field
instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) :=
by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field
instance [add_monoid α] : add_monoid (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, nsmul n (x i) };
tactic.pi_instance_derive_field
instance [add_comm_monoid α] : add_comm_monoid (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, nsmul n (x i) };
tactic.pi_instance_derive_field
instance [add_group α] : add_group (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, nsmul n (x i),
gsmul := λ n x i, gsmul n (x i) };
tactic.pi_instance_derive_field
instance [add_comm_group α] : add_comm_group (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, nsmul n (x i),
gsmul := λ n x i, gsmul n (x i) };
tactic.pi_instance_derive_field
/- scalar product -/
instance [has_mul α] : has_scalar α (holor α ds) :=
⟨λ a x, λ t, a * x t⟩
instance [semiring α] : module α (holor α ds) := pi.module _ _ _
/-- The tensor product of two holors. -/
def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) :=
λ t, x (t.take) * y (t.drop)
local infix ` ⊗ ` : 70 := mul
lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) :
cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) :=
by subst eq; refl
def assoc_right :
holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm)
lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left :=
funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃),
begin
rw assoc_left,
unfold mul,
rw mul_assoc,
rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop],
rw cast_type,
refl,
rw append_assoc
end)
lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
mul (mul x y) z == (mul x (mul y z)) :=
by simp [cast_heq, mul_assoc0, assoc_left].
lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) :
x ⊗ (y + z) = x ⊗ y + x ⊗ z :=
funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)))
lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) :
(x + y) ⊗ z = x ⊗ z + y ⊗ z :=
funext $ λt, add_mul (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))
@[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) :
(0 : holor α ds₁) ⊗ x = 0 :=
funext (λ t, zero_mul (x (holor_index.drop t)))
@[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) :
x ⊗ (0 :holor α ds₂) = 0 :=
funext (λ t, mul_zero (x (holor_index.take t)))
lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) :
x ⊗ y = x ⟨[], forall₂.nil⟩ • y :=
by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop]
/- holor slices -/
/-- A slice is a subholor consisting of all entries with initial index i. -/
def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds :=
(λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩)
/-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/
def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] :=
λ ti, if ti.1 = [j] then 1 else 0
lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) :
Π (t : holor_index (d :: ds)),
(∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t
| ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds)
| ⟨(i :: is), hforall₂⟩ hp := hp i is rfl
/-- Two holors are equal if all their slices are equal. -/
lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds))
(h : slice x = slice y) : x = y :=
funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis,
have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end,
have hid: i<d, from (forall₂_cons.1 hiisdds).1,
have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2,
calc
x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl)
... = slice y i hid ⟨is, hisds⟩ : by rw h
... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl)
lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ}
(hid : i < d) (x : holor α ds) :
slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 :=
funext $ λ t : holor_index ds, if h : i = j
then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]
else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl
lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) :
slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)])
lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) :
slice (0 : holor α (d :: ds)) i hid = 0 := rfl
lemma slice_sum [add_comm_monoid α] {β : Type}
(i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) :
∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid :=
begin
letI := classical.dec_eq β,
refine finset.induction_on s _ _,
{ simp [slice_zero] },
{ intros _ _ h_not_in ih,
rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] }
end
/-- The original holor can be recovered from its slices by multiplying with unit vectors and
summing up. -/
@[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) :
∑ i in (finset.range d).attach,
unit_vec d i ⊗ slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x :=
begin
apply slice_eq _ _ _,
ext i hid,
rw [←slice_sum],
simp only [slice_unit_vec_mul hid],
rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid),
{ simp },
{ assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩),
have hbi' : i ≠ b,
{ simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm },
simp [hbi'] },
{ assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d),
exfalso,
exact absurd (finset.mem_attach _ _) hid' }
end
/- CP rank -/
/-- `cprank_max1 x` means `x` has CP rank at most 1, that is,
it is the tensor product of 1-dimensional holors. -/
inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop
| nil (x : holor α []) :
cprank_max1 x
| cons {d} {ds} (x : holor α [d]) (y : holor α ds) :
cprank_max1 y → cprank_max1 (x ⊗ y)
/-- `cprank_max N x` means `x` has CP rank at most `N`, that is,
it can be written as the sum of N holors of rank at most 1. -/
inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop
| zero {ds} :
cprank_max 0 (0 : holor α ds)
| succ n {ds} (x : holor α ds) (y : holor α ds) :
cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y)
lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x :=
have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero),
by rwa [add_zero x, zero_add] at h
lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds}
(h : cprank_max1 x) : cprank_max 1 x :=
have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero,
by rwa [zero_add, add_zero] at h'
lemma cprank_max_add [monoid α] [add_monoid α]:
∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds},
cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y)
| 0 n x y (cprank_max.zero) hy := by simp [hy]
| (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy :=
begin
simp only [add_comm, add_assoc],
apply cprank_max.succ,
{ assumption },
{ exact cprank_max_add hx₂ hy }
end
lemma cprank_max_mul [ring α] :
∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y)
| 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero]
| (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) :=
begin
rw mul_left_distrib,
rw nat.add_comm,
apply cprank_max_add,
{ exact cprank_max_1 (cprank_max1.cons _ _ hy₁) },
{ exact cprank_max_mul k x y₂ hy₂ }
end
lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) :
(∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) :=
by letI := classical.dec_eq β;
exact finset.induction_on s
(by simp [cprank_max.zero])
(begin
assume x s (h_x_notin_s : x ∉ s) ih h_cprank,
simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s],
rw nat.right_distrib,
simp only [nat.one_mul, nat.add_comm],
have ih' : cprank_max (finset.card s * n) (∑ x in s, f x),
{ apply ih,
assume (x : β) (h_x_in_s: x ∈ s),
simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] },
exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih')
end)
lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x
| [] x := cprank_max_nil x
| (d :: ds) x :=
have h_summands : Π (i : {x // x ∈ finset.range d}),
cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)),
from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))),
have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds,
by simp [finset.card_range],
have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i),
have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
by rwa [finset.card_attach] at this,
begin
rw [←sum_unit_vec_mul_slice x],
rw [h_dds_prod],
exact h_cprank_max_sum,
end
/-- The CP rank of a holor `x`: the smallest N such that
`x` can be written as the sum of N holors of rank at most 1. -/
noncomputable def cprank [ring α] (x : holor α ds) : nat :=
@nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩
lemma cprank_upper_bound [ring α] :
Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod :=
λ ds (x : holor α ds),
by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x);
exact nat.find_min'
⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩
(cprank_max_upper_bound x)
end holor
|
8cf865dc3bdb9a4cd3a6deea0c93154aa99a3b36 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/group2.lean | 7a6509c3faeba2aecd59fa852272783f65f05116 | [
"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 | 1,698 | lean | import logic
section
variable {A : Type}
variable f : A → A → A
variable one : A
variable inv : A → A
local infixl `*` := f
local postfix `^-1`:100 := inv
definition is_assoc := ∀ a b c, (a*b)*c = a*b*c
definition is_id := ∀ a, a*one = a
definition is_inv := ∀ a, a*a^-1 = one
end
inductive group_struct [class] (A : Type) : Type :=
mk : Π (mul : A → A → A) (one : A) (inv : A → A), is_assoc mul → is_id mul one → is_inv mul one inv → group_struct A
inductive group : Type :=
mk : Π (A : Type), group_struct A → group
definition carrier (g : group) : Type
:= group.rec (λ c s, c) g
attribute carrier [coercion]
definition group_to_struct [instance] (g : group) : group_struct (carrier g)
:= group.rec (λ (A : Type) (s : group_struct A), s) g
check group_struct
definition mul1 {A : Type} [s : group_struct A] (a b : A) : A
:= group_struct.rec (λ mul one inv h1 h2 h3, mul) s a b
infixl `*` := mul1
section
variable G1 : group
variable G2 : group
variables a b c : G2
variables d e : G1
check a * b * b
check d * e
end
constant G : group.{1}
constants a b : G
definition val : G := a*b
check val
constant pos_real : Type.{1}
constant rmul : pos_real → pos_real → pos_real
constant rone : pos_real
constant rinv : pos_real → pos_real
axiom H1 : is_assoc rmul
axiom H2 : is_id rmul rone
axiom H3 : is_inv rmul rone rinv
definition real_group_struct [instance] : group_struct pos_real
:= group_struct.mk rmul rone rinv H1 H2 H3
constants x y : pos_real
check x * y
set_option pp.implicit true
print "---------------"
theorem T (a b : pos_real): (rmul a b) = a*b
:= eq.refl (rmul a b)
|
0df31f64431b75234cdac4a9756d39e966e49ee7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/metric_space/hausdorff_dimension.lean | fbad19511cd6d049c87e64f5e96ee2e155fa898e | [
"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 | 22,966 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.cont_diff
import measure_theory.measure.hausdorff
/-!
# Hausdorff dimension
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The Hausdorff dimension of a set `X` in an (extended) metric space is the unique number
`dimH s : ℝ≥0∞` such that for any `d : ℝ≥0` we have
- `μH[d] s = 0` if `dimH s < d`, and
- `μH[d] s = ∞` if `d < dimH s`.
In this file we define `dimH s` to be the Hausdorff dimension of `s`, then prove some basic
properties of Hausdorff dimension.
## Main definitions
* `measure_theory.dimH`: the Hausdorff dimension of a set. For the Hausdorff dimension of the whole
space we use `measure_theory.dimH (set.univ : set X)`.
## Main results
### Basic properties of Hausdorff dimension
* `hausdorff_measure_of_lt_dimH`, `dimH_le_of_hausdorff_measure_ne_top`,
`le_dimH_of_hausdorff_measure_eq_top`, `hausdorff_measure_of_dimH_lt`, `measure_zero_of_dimH_lt`,
`le_dimH_of_hausdorff_measure_ne_zero`, `dimH_of_hausdorff_measure_ne_zero_ne_top`: various forms
of the characteristic property of the Hausdorff dimension;
* `dimH_union`: the Hausdorff dimension of the union of two sets is the maximum of their Hausdorff
dimensions.
* `dimH_Union`, `dimH_bUnion`, `dimH_sUnion`: the Hausdorff dimension of a countable union of sets
is the supremum of their Hausdorff dimensions;
* `dimH_empty`, `dimH_singleton`, `set.subsingleton.dimH_zero`, `set.countable.dimH_zero` : `dimH s
= 0` whenever `s` is countable;
### (Pre)images under (anti)lipschitz and Hölder continuous maps
* `holder_with.dimH_image_le` etc: if `f : X → Y` is Hölder continuous with exponent `r > 0`, then
for any `s`, `dimH (f '' s) ≤ dimH s / r`. We prove versions of this statement for `holder_with`,
`holder_on_with`, and locally Hölder maps, as well as for `set.image` and `set.range`.
* `lipschitz_with.dimH_image_le` etc: Lipschitz continuous maps do not increase the Hausdorff
dimension of sets.
* for a map that is known to be both Lipschitz and antilipschitz (e.g., for an `isometry` or
a `continuous_linear_equiv`) we also prove `dimH (f '' s) = dimH s`.
### Hausdorff measure in `ℝⁿ`
* `real.dimH_of_nonempty_interior`: if `s` is a set in a finite dimensional real vector space `E`
with nonempty interior, then the Hausdorff dimension of `s` is equal to the dimension of `E`.
* `dense_compl_of_dimH_lt_finrank`: if `s` is a set in a finite dimensional real vector space `E`
with Hausdorff dimension strictly less than the dimension of `E`, the `s` has a dense complement.
* `cont_diff.dense_compl_range_of_finrank_lt_finrank`: the complement to the range of a `C¹`
smooth map is dense provided that the dimension of the domain is strictly less than the dimension
of the codomain.
## Notations
We use the following notation localized in `measure_theory`. It is defined in
`measure_theory.measure.hausdorff`.
- `μH[d]` : `measure_theory.measure.hausdorff_measure d`
## Implementation notes
* The definition of `dimH` explicitly uses `borel X` as a measurable space structure. This way we
can formulate lemmas about Hausdorff dimension without assuming that the environment has a
`[measurable_space X]` instance that is equal but possibly not defeq to `borel X`.
Lemma `dimH_def` unfolds this definition using whatever `[measurable_space X]` instance we have in
the environment (as long as it is equal to `borel X`).
* The definition `dimH` is irreducible; use API lemmas or `dimH_def` instead.
## Tags
Hausdorff measure, Hausdorff dimension, dimension
-/
open_locale measure_theory ennreal nnreal topology
open measure_theory measure_theory.measure set topological_space finite_dimensional filter
variables {ι X Y : Type*} [emetric_space X] [emetric_space Y]
/-- Hausdorff dimension of a set in an (e)metric space. -/
@[irreducible] noncomputable def dimH (s : set X) : ℝ≥0∞ :=
by { borelize X, exact ⨆ (d : ℝ≥0) (hd : @hausdorff_measure X _ _ ⟨rfl⟩ d s = ∞), d }
/-!
### Basic properties
-/
section measurable
variables [measurable_space X] [borel_space X]
/-- Unfold the definition of `dimH` using `[measurable_space X] [borel_space X]` from the
environment. -/
lemma dimH_def (s : set X) : dimH s = ⨆ (d : ℝ≥0) (hd : μH[d] s = ∞), d :=
by { borelize X, rw dimH }
lemma hausdorff_measure_of_lt_dimH {s : set X} {d : ℝ≥0} (h : ↑d < dimH s) : μH[d] s = ∞ :=
begin
simp only [dimH_def, lt_supr_iff] at h,
rcases h with ⟨d', hsd', hdd'⟩,
rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hdd',
exact top_unique (hsd' ▸ hausdorff_measure_mono hdd'.le _)
end
lemma dimH_le {s : set X} {d : ℝ≥0∞} (H : ∀ d' : ℝ≥0, μH[d'] s = ∞ → ↑d' ≤ d) : dimH s ≤ d :=
(dimH_def s).trans_le $ supr₂_le H
lemma dimH_le_of_hausdorff_measure_ne_top {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ ∞) :
dimH s ≤ d :=
le_of_not_lt $ mt hausdorff_measure_of_lt_dimH h
lemma le_dimH_of_hausdorff_measure_eq_top {s : set X} {d : ℝ≥0} (h : μH[d] s = ∞) :
↑d ≤ dimH s :=
by { rw dimH_def, exact le_supr₂ d h }
lemma hausdorff_measure_of_dimH_lt {s : set X} {d : ℝ≥0}
(h : dimH s < d) : μH[d] s = 0 :=
begin
rw dimH_def at h,
rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨d', hsd', hd'd⟩,
rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hd'd,
exact (hausdorff_measure_zero_or_top hd'd s).resolve_right (λ h, hsd'.not_le $ le_supr₂ d' h)
end
lemma measure_zero_of_dimH_lt {μ : measure X} {d : ℝ≥0}
(h : μ ≪ μH[d]) {s : set X} (hd : dimH s < d) :
μ s = 0 :=
h $ hausdorff_measure_of_dimH_lt hd
lemma le_dimH_of_hausdorff_measure_ne_zero {s : set X} {d : ℝ≥0} (h : μH[d] s ≠ 0) :
↑d ≤ dimH s :=
le_of_not_lt $ mt hausdorff_measure_of_dimH_lt h
lemma dimH_of_hausdorff_measure_ne_zero_ne_top {d : ℝ≥0} {s : set X} (h : μH[d] s ≠ 0)
(h' : μH[d] s ≠ ∞) : dimH s = d :=
le_antisymm (dimH_le_of_hausdorff_measure_ne_top h') (le_dimH_of_hausdorff_measure_ne_zero h)
end measurable
@[mono] lemma dimH_mono {s t : set X} (h : s ⊆ t) : dimH s ≤ dimH t :=
begin
borelize X,
exact dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top $
top_unique $ hd ▸ measure_mono h)
end
lemma dimH_subsingleton {s : set X} (h : s.subsingleton) : dimH s = 0 :=
begin
borelize X,
apply le_antisymm _ (zero_le _),
refine dimH_le_of_hausdorff_measure_ne_top _,
exact ((hausdorff_measure_le_one_of_subsingleton h le_rfl).trans_lt ennreal.one_lt_top).ne,
end
alias dimH_subsingleton ← set.subsingleton.dimH_zero
@[simp] lemma dimH_empty : dimH (∅ : set X) = 0 := subsingleton_empty.dimH_zero
@[simp] lemma dimH_singleton (x : X) : dimH ({x} : set X) = 0 := subsingleton_singleton.dimH_zero
@[simp] lemma dimH_Union [encodable ι] (s : ι → set X) :
dimH (⋃ i, s i) = ⨆ i, dimH (s i) :=
begin
borelize X,
refine le_antisymm (dimH_le $ λ d hd, _) (supr_le $ λ i, dimH_mono $ subset_Union _ _),
contrapose! hd,
have : ∀ i, μH[d] (s i) = 0,
from λ i, hausdorff_measure_of_dimH_lt ((le_supr (λ i, dimH (s i)) i).trans_lt hd),
rw measure_Union_null this,
exact ennreal.zero_ne_top
end
@[simp] lemma dimH_bUnion {s : set ι} (hs : s.countable) (t : ι → set X) :
dimH (⋃ i ∈ s, t i) = ⨆ i ∈ s, dimH (t i) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union, dimH_Union, ← supr_subtype'']
end
@[simp] lemma dimH_sUnion {S : set (set X)} (hS : S.countable) : dimH (⋃₀ S) = ⨆ s ∈ S, dimH s :=
by rw [sUnion_eq_bUnion, dimH_bUnion hS]
@[simp] lemma dimH_union (s t : set X) : dimH (s ∪ t) = max (dimH s) (dimH t) :=
by rw [union_eq_Union, dimH_Union, supr_bool_eq, cond, cond, ennreal.sup_eq_max]
lemma dimH_countable {s : set X} (hs : s.countable) : dimH s = 0 :=
bUnion_of_singleton s ▸ by simp only [dimH_bUnion hs, dimH_singleton, ennreal.supr_zero_eq_zero]
alias dimH_countable ← set.countable.dimH_zero
lemma dimH_finite {s : set X} (hs : s.finite) : dimH s = 0 := hs.countable.dimH_zero
alias dimH_finite ← set.finite.dimH_zero
@[simp] lemma dimH_coe_finset (s : finset X) : dimH (s : set X) = 0 := s.finite_to_set.dimH_zero
alias dimH_coe_finset ← finset.dimH_zero
/-!
### Hausdorff dimension as the supremum of local Hausdorff dimensions
-/
section
variables [second_countable_topology X]
/-- If `r` is less than the Hausdorff dimension of a set `s` in an (extended) metric space with
second countable topology, then there exists a point `x ∈ s` such that every neighborhood
`t` of `x` within `s` has Hausdorff dimension greater than `r`. -/
lemma exists_mem_nhds_within_lt_dimH_of_lt_dimH {s : set X} {r : ℝ≥0∞} (h : r < dimH s) :
∃ x ∈ s, ∀ t ∈ 𝓝[s] x, r < dimH t :=
begin
contrapose! h, choose! t htx htr using h,
rcases countable_cover_nhds_within htx with ⟨S, hSs, hSc, hSU⟩,
calc dimH s ≤ dimH (⋃ x ∈ S, t x) : dimH_mono hSU
... = ⨆ x ∈ S, dimH (t x) : dimH_bUnion hSc _
... ≤ r : supr₂_le (λ x hx, htr x $ hSs hx)
end
/-- In an (extended) metric space with second countable topology, the Hausdorff dimension
of a set `s` is the supremum over `x ∈ s` of the limit superiors of `dimH t` along
`(𝓝[s] x).small_sets`. -/
lemma bsupr_limsup_dimH (s : set X) : (⨆ x ∈ s, limsup dimH (𝓝[s] x).small_sets) = dimH s :=
begin
refine le_antisymm (supr₂_le $ λ x hx, _) _,
{ refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _),
exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ },
{ refine le_of_forall_ge_of_dense (λ r hr, _),
rcases exists_mem_nhds_within_lt_dimH_of_lt_dimH hr with ⟨x, hxs, hxr⟩,
refine le_supr₂_of_le x hxs _, rw limsup_eq, refine le_Inf (λ b hb, _),
rcases eventually_small_sets.1 hb with ⟨t, htx, ht⟩,
exact (hxr t htx).le.trans (ht t subset.rfl) }
end
/-- In an (extended) metric space with second countable topology, the Hausdorff dimension
of a set `s` is the supremum over all `x` of the limit superiors of `dimH t` along
`(𝓝[s] x).small_sets`. -/
lemma supr_limsup_dimH (s : set X) : (⨆ x, limsup dimH (𝓝[s] x).small_sets) = dimH s :=
begin
refine le_antisymm (supr_le $ λ x, _) _,
{ refine Limsup_le_of_le (by apply_auto_param) (eventually_map.2 _),
exact eventually_small_sets.2 ⟨s, self_mem_nhds_within, λ t, dimH_mono⟩ },
{ rw ← bsupr_limsup_dimH, exact supr₂_le_supr _ _ }
end
end
/-!
### Hausdorff dimension and Hölder continuity
-/
variables {C K r : ℝ≥0} {f : X → Y} {s t : set X}
/-- If `f` is a Hölder continuous map with exponent `r > 0`, then `dimH (f '' s) ≤ dimH s / r`. -/
lemma holder_on_with.dimH_image_le (h : holder_on_with C r f s) (hr : 0 < r) :
dimH (f '' s) ≤ dimH s / r :=
begin
borelize [X, Y],
refine dimH_le (λ d hd, _),
have := h.hausdorff_measure_image_le hr d.coe_nonneg,
rw [hd, ennreal.coe_rpow_of_nonneg _ d.coe_nonneg, top_le_iff] at this,
have Hrd : μH[(r * d : ℝ≥0)] s = ⊤,
{ contrapose this, exact ennreal.mul_ne_top ennreal.coe_ne_top this },
rw [ennreal.le_div_iff_mul_le, mul_comm, ← ennreal.coe_mul],
exacts [le_dimH_of_hausdorff_measure_eq_top Hrd, or.inl (mt ennreal.coe_eq_zero.1 hr.ne'),
or.inl ennreal.coe_ne_top]
end
namespace holder_with
/-- If `f : X → Y` is Hölder continuous with a positive exponent `r`, then the Hausdorff dimension
of the image of a set `s` is at most `dimH s / r`. -/
lemma dimH_image_le (h : holder_with C r f) (hr : 0 < r) (s : set X) :
dimH (f '' s) ≤ dimH s / r :=
(h.holder_on_with s).dimH_image_le hr
/-- If `f` is a Hölder continuous map with exponent `r > 0`, then the Hausdorff dimension of its
range is at most the Hausdorff dimension of its domain divided by `r`. -/
lemma dimH_range_le (h : holder_with C r f) (hr : 0 < r) :
dimH (range f) ≤ dimH (univ : set X) / r :=
@image_univ _ _ f ▸ h.dimH_image_le hr univ
end holder_with
/-- If `s` is a set in a space `X` with second countable topology and `f : X → Y` is Hölder
continuous in a neighborhood within `s` of every point `x ∈ s` with the same positive exponent `r`
but possibly different coefficients, then the Hausdorff dimension of the image `f '' s` is at most
the Hausdorff dimension of `s` divided by `r`. -/
lemma dimH_image_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y}
(hr : 0 < r) {s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C r f t) :
dimH (f '' s) ≤ dimH s / r :=
begin
choose! C t htn hC using hf,
rcases countable_cover_nhds_within htn with ⟨u, hus, huc, huU⟩,
replace huU := inter_eq_self_of_subset_left huU, rw inter_Union₂ at huU,
rw [← huU, image_Union₂, dimH_bUnion huc, dimH_bUnion huc], simp only [ennreal.supr_div],
exact supr₂_mono (λ x hx, ((hC x (hus hx)).mono (inter_subset_right _ _)).dimH_image_le hr)
end
/-- If `f : X → Y` is Hölder continuous in a neighborhood of every point `x : X` with the same
positive exponent `r` but possibly different coefficients, then the Hausdorff dimension of the range
of `f` is at most the Hausdorff dimension of `X` divided by `r`. -/
lemma dimH_range_le_of_locally_holder_on [second_countable_topology X] {r : ℝ≥0} {f : X → Y}
(hr : 0 < r) (hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), holder_on_with C r f s) :
dimH (range f) ≤ dimH (univ : set X) / r :=
begin
rw ← image_univ,
refine dimH_image_le_of_locally_holder_on hr (λ x _, _),
simpa only [exists_prop, nhds_within_univ] using hf x
end
/-!
### Hausdorff dimension and Lipschitz continuity
-/
/-- If `f : X → Y` is Lipschitz continuous on `s`, then `dimH (f '' s) ≤ dimH s`. -/
lemma lipschitz_on_with.dimH_image_le (h : lipschitz_on_with K f s) : dimH (f '' s) ≤ dimH s :=
by simpa using h.holder_on_with.dimH_image_le zero_lt_one
namespace lipschitz_with
/-- If `f` is a Lipschitz continuous map, then `dimH (f '' s) ≤ dimH s`. -/
lemma dimH_image_le (h : lipschitz_with K f) (s : set X) : dimH (f '' s) ≤ dimH s :=
(h.lipschitz_on_with s).dimH_image_le
/-- If `f` is a Lipschitz continuous map, then the Hausdorff dimension of its range is at most the
Hausdorff dimension of its domain. -/
lemma dimH_range_le (h : lipschitz_with K f) : dimH (range f) ≤ dimH (univ : set X) :=
@image_univ _ _ f ▸ h.dimH_image_le univ
end lipschitz_with
/-- If `s` is a set in an extended metric space `X` with second countable topology and `f : X → Y`
is Lipschitz in a neighborhood within `s` of every point `x ∈ s`, then the Hausdorff dimension of
the image `f '' s` is at most the Hausdorff dimension of `s`. -/
lemma dimH_image_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y}
{s : set X} (hf : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with C f t) :
dimH (f '' s) ≤ dimH s :=
begin
have : ∀ x ∈ s, ∃ (C : ℝ≥0) (t ∈ 𝓝[s] x), holder_on_with C 1 f t,
by simpa only [holder_on_with_one] using hf,
simpa only [ennreal.coe_one, div_one]
using dimH_image_le_of_locally_holder_on zero_lt_one this
end
/-- If `f : X → Y` is Lipschitz in a neighborhood of each point `x : X`, then the Hausdorff
dimension of `range f` is at most the Hausdorff dimension of `X`. -/
lemma dimH_range_le_of_locally_lipschitz_on [second_countable_topology X] {f : X → Y}
(hf : ∀ x : X, ∃ (C : ℝ≥0) (s ∈ 𝓝 x), lipschitz_on_with C f s) :
dimH (range f) ≤ dimH (univ : set X) :=
begin
rw ← image_univ,
refine dimH_image_le_of_locally_lipschitz_on (λ x _, _),
simpa only [exists_prop, nhds_within_univ] using hf x
end
namespace antilipschitz_with
lemma dimH_preimage_le (hf : antilipschitz_with K f) (s : set Y) :
dimH (f ⁻¹' s) ≤ dimH s :=
begin
borelize [X, Y],
refine dimH_le (λ d hd, le_dimH_of_hausdorff_measure_eq_top _),
have := hf.hausdorff_measure_preimage_le d.coe_nonneg s,
rw [hd, top_le_iff] at this,
contrapose! this,
exact ennreal.mul_ne_top (by simp) this
end
lemma le_dimH_image (hf : antilipschitz_with K f) (s : set X) :
dimH s ≤ dimH (f '' s) :=
calc dimH s ≤ dimH (f ⁻¹' (f '' s)) : dimH_mono (subset_preimage_image _ _)
... ≤ dimH (f '' s) : hf.dimH_preimage_le _
end antilipschitz_with
/-!
### Isometries preserve Hausdorff dimension
-/
lemma isometry.dimH_image (hf : isometry f) (s : set X) : dimH (f '' s) = dimH s :=
le_antisymm (hf.lipschitz.dimH_image_le _) (hf.antilipschitz.le_dimH_image _)
namespace isometry_equiv
@[simp] lemma dimH_image (e : X ≃ᵢ Y) (s : set X) : dimH (e '' s) = dimH s :=
e.isometry.dimH_image s
@[simp] lemma dimH_preimage (e : X ≃ᵢ Y) (s : set Y) : dimH (e ⁻¹' s) = dimH s :=
by rw [← e.image_symm, e.symm.dimH_image]
lemma dimH_univ (e : X ≃ᵢ Y) : dimH (univ : set X) = dimH (univ : set Y) :=
by rw [← e.dimH_preimage univ, preimage_univ]
end isometry_equiv
namespace continuous_linear_equiv
variables {𝕜 E F : Type*} [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F]
@[simp] lemma dimH_image (e : E ≃L[𝕜] F) (s : set E) : dimH (e '' s) = dimH s :=
le_antisymm (e.lipschitz.dimH_image_le s) $
by simpa only [e.symm_image_image] using e.symm.lipschitz.dimH_image_le (e '' s)
@[simp] lemma dimH_preimage (e : E ≃L[𝕜] F) (s : set F) : dimH (e ⁻¹' s) = dimH s :=
by rw [← e.image_symm_eq_preimage, e.symm.dimH_image]
lemma dimH_univ (e : E ≃L[𝕜] F) : dimH (univ : set E) = dimH (univ : set F) :=
by rw [← e.dimH_preimage, preimage_univ]
end continuous_linear_equiv
/-!
### Hausdorff dimension in a real vector space
-/
namespace real
variables {E : Type*} [fintype ι] [normed_add_comm_group E] [normed_space ℝ E]
[finite_dimensional ℝ E]
theorem dimH_ball_pi (x : ι → ℝ) {r : ℝ} (hr : 0 < r) :
dimH (metric.ball x r) = fintype.card ι :=
begin
casesI is_empty_or_nonempty ι,
{ rwa [dimH_subsingleton, eq_comm, nat.cast_eq_zero, fintype.card_eq_zero_iff],
exact λ x _ y _, subsingleton.elim x y },
{ rw ← ennreal.coe_nat,
have : μH[fintype.card ι] (metric.ball x r) = ennreal.of_real ((2 * r) ^ fintype.card ι),
by rw [hausdorff_measure_pi_real, real.volume_pi_ball _ hr],
refine dimH_of_hausdorff_measure_ne_zero_ne_top _ _; rw [nnreal.coe_nat_cast, this],
{ simp [pow_pos (mul_pos (zero_lt_two' ℝ) hr)] },
{ exact ennreal.of_real_ne_top } }
end
theorem dimH_ball_pi_fin {n : ℕ} (x : fin n → ℝ) {r : ℝ} (hr : 0 < r) :
dimH (metric.ball x r) = n :=
by rw [dimH_ball_pi x hr, fintype.card_fin]
theorem dimH_univ_pi (ι : Type*) [fintype ι] : dimH (univ : set (ι → ℝ)) = fintype.card ι :=
by simp only [← metric.Union_ball_nat_succ (0 : ι → ℝ), dimH_Union,
dimH_ball_pi _ (nat.cast_add_one_pos _), supr_const]
theorem dimH_univ_pi_fin (n : ℕ) : dimH (univ : set (fin n → ℝ)) = n :=
by rw [dimH_univ_pi, fintype.card_fin]
theorem dimH_of_mem_nhds {x : E} {s : set E} (h : s ∈ 𝓝 x) :
dimH s = finrank ℝ E :=
begin
have e : E ≃L[ℝ] (fin (finrank ℝ E) → ℝ),
from continuous_linear_equiv.of_finrank_eq (finite_dimensional.finrank_fin_fun ℝ).symm,
rw ← e.dimH_image,
refine le_antisymm _ _,
{ exact (dimH_mono (subset_univ _)).trans_eq (dimH_univ_pi_fin _) },
{ have : e '' s ∈ 𝓝 (e x), by { rw ← e.map_nhds_eq, exact image_mem_map h },
rcases metric.nhds_basis_ball.mem_iff.1 this with ⟨r, hr0, hr⟩,
simpa only [dimH_ball_pi_fin (e x) hr0] using dimH_mono hr }
end
theorem dimH_of_nonempty_interior {s : set E} (h : (interior s).nonempty) :
dimH s = finrank ℝ E :=
let ⟨x, hx⟩ := h in dimH_of_mem_nhds (mem_interior_iff_mem_nhds.1 hx)
variable (E)
theorem dimH_univ_eq_finrank : dimH (univ : set E) = finrank ℝ E :=
dimH_of_mem_nhds (@univ_mem _ (𝓝 0))
theorem dimH_univ : dimH (univ : set ℝ) = 1 :=
by rw [dimH_univ_eq_finrank ℝ, finite_dimensional.finrank_self, nat.cast_one]
end real
variables {E F : Type*}
[normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
[normed_add_comm_group F] [normed_space ℝ F]
theorem dense_compl_of_dimH_lt_finrank {s : set E} (hs : dimH s < finrank ℝ E) : dense sᶜ :=
begin
refine λ x, mem_closure_iff_nhds.2 (λ t ht, nonempty_iff_ne_empty.2 $ λ he, hs.not_le _),
rw [← diff_eq, diff_eq_empty] at he,
rw [← real.dimH_of_mem_nhds ht],
exact dimH_mono he
end
/-!
### Hausdorff dimension and `C¹`-smooth maps
`C¹`-smooth maps are locally Lipschitz continuous, hence they do not increase the Hausdorff
dimension of sets.
-/
/-- Let `f` be a function defined on a finite dimensional real normed space. If `f` is `C¹`-smooth
on a convex set `s`, then the Hausdorff dimension of `f '' s` is less than or equal to the Hausdorff
dimension of `s`.
TODO: do we actually need `convex ℝ s`? -/
lemma cont_diff_on.dimH_image_le {f : E → F} {s t : set E} (hf : cont_diff_on ℝ 1 f s)
(hc : convex ℝ s) (ht : t ⊆ s) :
dimH (f '' t) ≤ dimH t :=
dimH_image_le_of_locally_lipschitz_on $ λ x hx,
let ⟨C, u, hu, hf⟩ := (hf x (ht hx)).exists_lipschitz_on_with hc
in ⟨C, u, nhds_within_mono _ ht hu, hf⟩
/-- The Hausdorff dimension of the range of a `C¹`-smooth function defined on a finite dimensional
real normed space is at most the dimension of its domain as a vector space over `ℝ`. -/
lemma cont_diff.dimH_range_le {f : E → F} (h : cont_diff ℝ 1 f) :
dimH (range f) ≤ finrank ℝ E :=
calc dimH (range f) = dimH (f '' univ) : by rw image_univ
... ≤ dimH (univ : set E) : h.cont_diff_on.dimH_image_le convex_univ subset.rfl
... = finrank ℝ E : real.dimH_univ_eq_finrank E
/-- A particular case of Sard's Theorem. Let `f : E → F` be a map between finite dimensional real
vector spaces. Suppose that `f` is `C¹` smooth on a convex set `s` of Hausdorff dimension strictly
less than the dimension of `F`. Then the complement of the image `f '' s` is dense in `F`. -/
lemma cont_diff_on.dense_compl_image_of_dimH_lt_finrank [finite_dimensional ℝ F] {f : E → F}
{s t : set E} (h : cont_diff_on ℝ 1 f s) (hc : convex ℝ s) (ht : t ⊆ s)
(htF : dimH t < finrank ℝ F) :
dense (f '' t)ᶜ :=
dense_compl_of_dimH_lt_finrank $ (h.dimH_image_le hc ht).trans_lt htF
/-- A particular case of Sard's Theorem. If `f` is a `C¹` smooth map from a real vector space to a
real vector space `F` of strictly larger dimension, then the complement of the range of `f` is dense
in `F`. -/
lemma cont_diff.dense_compl_range_of_finrank_lt_finrank [finite_dimensional ℝ F] {f : E → F}
(h : cont_diff ℝ 1 f) (hEF : finrank ℝ E < finrank ℝ F) :
dense (range f)ᶜ :=
dense_compl_of_dimH_lt_finrank $ h.dimH_range_le.trans_lt $ nat.cast_lt.2 hEF
|
205418cb6f055d75af2a7b4b8a62bc99d61c9a8d | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/order/level01.lean | b7b9d93a66910f02fdb9068e0cd6a50d4a8e3602 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 628 | lean | import game.sets.sets_level10
import data.real.basic
namespace xena -- hide
/-
# Chapter 2 : Order
## Level 1
This level aims to familiarize you with the use of the trichotomy property in
Lean, as it will come in handy in later levels.
This property is stated in Lean's mathlib is:
`lt_trichotomy : ∀ (a b : ?M_1), a < b ∨ a = b ∨ b < a`
and you can just use it to finish the proof below.
-/
/- Lemma
For any two real numbers $a$ and $b$, we have that
$$ a < b \lor a = b \lor b < a$$.
-/
theorem trichotomy' (a b : ℝ) : a < b ∨ a = b ∨ b < a :=
begin
exact lt_trichotomy a b, done
end
end xena --hide
|
add90246249cec8c1cdc70a286b04a7a073362c3 | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/topology/metric_space/gluing.lean | e652282b6123c84efccceccc22769286c7180b73 | [
"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 | 23,502 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Gluing metric spaces
Authors: Sébastien Gouëzel
Gluing two metric spaces along a common subset. Formally, we are given
Φ
γ ---> α
|
|Ψ
v
β
where hΦ : isometry Φ and hΨ : isometry Ψ
We want to complete the square by a space `glue_space hΦ hΨ` and two isometries
`to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute.
We start by defining a predistance on the disjoint union α ⊕ β, for which
points Φ p and Ψ p are at distance 0. The (quotient) metric space associated
to this predistance is the desired space.
This is an instance of a more general construction, where Φ and Ψ do not have to be isometries,
but the distances in the image almost coincide, up to 2ε say. Then one can almost glue the two
spaces so that the images of a point under Φ and Ψ are ε-close. If ε > 0, this yields a
metric space structure on α ⊕ β, without the need to take a quotient. In particular, when
α and β are inhabited, this gives a natural metric space structure on α ⊕ β, where the basepoints
are at distance 1, say, and the distances between other points are obtained by going through the
two basepoints.
We also define the inductive limit of metric spaces. Given
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings, we define the inductive
limit of the X n, also known as the increasing union of the X n in this context, if we
identify X n and X (n+1) through f n. This is a metric space in which all X n embed
isometrically and in a way compatible with f n.
-/
import topology.metric_space.isometry topology.metric_space.premetric_space
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open function set premetric lattice
namespace metric
section approx_gluing
variables [metric_space α] [metric_space β]
{Φ : γ → α} {Ψ : γ → β} {ε : ℝ}
open lattice
open sum (inl inr)
/-- Define a predistance on α ⊕ β, for which Φ p and Ψ p are at distance ε -/
def glue_dist (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : α ⊕ β → α ⊕ β → ℝ
| (inl x) (inl y) := dist x y
| (inr x) (inr y) := dist x y
| (inl x) (inr y) := infi (λp, dist x (Φ p) + dist y (Ψ p)) + ε
| (inr x) (inl y) := infi (λp, dist y (Φ p) + dist x (Ψ p)) + ε
private lemma glue_dist_self (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) : ∀x, glue_dist Φ Ψ ε x x = 0
| (inl x) := dist_self _
| (inr x) := dist_self _
lemma glue_dist_glued_points [nonempty γ] (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (p : γ) :
glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε :=
begin
have : infi (λq, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0,
{ have A : ∀q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) :=
λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg,
refine le_antisymm _ (le_cinfi A),
have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp,
rw this,
exact cinfi_le ⟨0, forall_range_iff.2 A⟩ },
rw [glue_dist, this, zero_add]
end
private lemma glue_dist_comm (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) :
∀x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x
| (inl x) (inl y) := dist_comm _ _
| (inr x) (inr y) := dist_comm _ _
| (inl x) (inr y) := rfl
| (inr x) (inl y) := rfl
variable [nonempty γ]
private lemma glue_dist_triangle (Φ : γ → α) (Ψ : γ → β) (ε : ℝ)
(H : ∀p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) :
∀x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z
| (inl x) (inl y) (inl z) := dist_triangle _ _ _
| (inr x) (inr y) (inr z) := dist_triangle _ _ _
| (inr x) (inl y) (inl z) := begin
have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : infi (λp, dist z (Φ p) + dist x (Ψ p)) ≤ infi (λp, dist y (Φ p) + dist x (Ψ p)) + dist y z,
{ have : infi (λp, dist y (Φ p) + dist x (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))),
{ refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λt, t + dist y z)) _ (B _ _),
exact continuous_add continuous_id continuous_const,
exact λx y hx, by simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) :
add_le_add (dist_triangle_left _ _ _) (le_refl _)
... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring },
linarith
end
| (inr x) (inr y) (inl z) := begin
have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : infi (λp, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + infi (λp, dist z (Φ p) + dist y (Ψ p)),
{ have : dist x y + infi (λp, dist z (Φ p) + dist y (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))),
{ refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λt, dist x y + t)) _ (B _ _),
exact continuous_add continuous_const continuous_id,
exact λx y hx, by simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) :
add_le_add (le_refl _) (dist_triangle _ _ _)
... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring },
linarith
end
| (inl x) (inl y) (inr z) := begin
have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : infi (λp, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + infi (λp, dist y (Φ p) + dist z (Ψ p)),
{ have : dist x y + infi (λp, dist y (Φ p) + dist z (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))),
{ refine cinfi_of_cinfi_of_monotone_of_continuous ( _ : continuous (λt, dist x y + t)) _ (B _ _),
exact continuous_add continuous_const continuous_id,
exact λx y hx, by simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) :
add_le_add (dist_triangle _ _ _) (le_refl _)
... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring },
linarith
end
| (inl x) (inr y) (inr z) := begin
have B : ∀a b, bdd_below (range (λ (p : γ), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : infi (λp, dist x (Φ p) + dist z (Ψ p)) ≤ infi (λp, dist x (Φ p) + dist y (Ψ p)) + dist y z,
{ have : infi (λp, dist x (Φ p) + dist y (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))),
{ refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λt, t + dist y z)) _ (B _ _),
exact continuous_add continuous_id continuous_const,
exact λx y hx, by simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) :
add_le_add (le_refl _) (dist_triangle_left _ _ _)
... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring },
linarith
end
| (inl x) (inr y) (inl z) := real.le_of_forall_epsilon_le $ λδ δpos, begin
have : ∃a ∈ range (λp, dist x (Φ p) + dist y (Ψ p)), a < infi (λp, dist x (Φ p) + dist y (Ψ p)) + δ/2 :=
exists_lt_of_cInf_lt (by simp [‹nonempty γ›]) (by rw [infi]; linarith),
rcases this with ⟨a, arange, ha⟩,
rcases mem_range.1 arange with ⟨p, pa⟩,
rw ← pa at ha,
have : ∃b ∈ range (λp, dist z (Φ p) + dist y (Ψ p)), b < infi (λp, dist z (Φ p) + dist y (Ψ p)) + δ/2 :=
exists_lt_of_cInf_lt (by simp [‹nonempty γ›]) (by rw [infi]; linarith),
rcases this with ⟨b, brange, hb⟩,
rcases mem_range.1 brange with ⟨q, qb⟩,
rw ← qb at hb,
have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε,
{ have := le_trans (le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε :
add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) (le_refl _)) (le_refl _)
... ≤ (infi (λp, dist x (Φ p) + dist y (Ψ p)) + ε) + (infi (λp, dist z (Φ p) + dist y (Ψ p)) + ε) + δ :
by linarith
end
| (inr x) (inl y) (inr z) := real.le_of_forall_epsilon_le $ λδ δpos, begin
have : ∃a ∈ range (λp, dist y (Φ p) + dist x (Ψ p)), a < infi (λp, dist y (Φ p) + dist x (Ψ p)) + δ/2 :=
exists_lt_of_cInf_lt (by simp [‹nonempty γ›]) (by rw [infi]; linarith),
rcases this with ⟨a, arange, ha⟩,
rcases mem_range.1 arange with ⟨p, pa⟩,
rw ← pa at ha,
have : ∃b ∈ range (λp, dist y (Φ p) + dist z (Ψ p)), b < infi (λp, dist y (Φ p) + dist z (Ψ p)) + δ/2 :=
exists_lt_of_cInf_lt (by simp [‹nonempty γ›]) (by rw [infi]; linarith),
rcases this with ⟨b, brange, hb⟩,
rcases mem_range.1 brange with ⟨q, qb⟩,
rw ← qb at hb,
have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε,
{ have := le_trans (neg_le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε :
add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) (le_refl _)) (le_refl _)
... ≤ (infi (λp, dist y (Φ p) + dist x (Ψ p)) + ε) + (infi (λp, dist y (Φ p) + dist z (Ψ p)) + ε) + δ :
by linarith
end
private lemma glue_eq_of_dist_eq_zero (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (ε0 : 0 < ε) :
∀p q : α ⊕ β, glue_dist Φ Ψ ε p q = 0 → p = q
| (inl x) (inl y) h := by rw eq_of_dist_eq_zero h
| (inl x) (inr y) h := begin
have : 0 ≤ infi (λp, dist x (Φ p) + dist y (Ψ p)) :=
le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inl y) h := begin
have : 0 ≤ infi (λp, dist y (Φ p) + dist x (Ψ p)) :=
le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inr y) h := by rw eq_of_dist_eq_zero h
/-- Given two maps Φ and Ψ intro metric spaces α and β such that the distances between Φ p and Φ q,
and between Ψ p and Ψ q, coincide up to 2 ε where ε > 0, one can almost glue the two spaces α
and β along the images of Φ and Ψ, so that Φ p and Ψ p are at distance ε. -/
def glue_metric_approx (Φ : γ → α) (Ψ : γ → β) (ε : ℝ) (ε0 : 0 < ε)
(H : ∀p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) : metric_space (α ⊕ β) :=
{ dist := glue_dist Φ Ψ ε,
dist_self := glue_dist_self Φ Ψ ε,
dist_comm := glue_dist_comm Φ Ψ ε,
dist_triangle := glue_dist_triangle Φ Ψ ε H,
eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 }
end approx_gluing
section sum
/- A particular case of the previous construction is when one uses basepoints in α and β and one
glues only along the basepoints, putting them at distance 1. We give a direct definition of
the distance, without infi, as it is easier to use in applications, and show that it is equal to
the gluing distance defined above to take advantage of the lemmas we have already proved. -/
variables [metric_space α] [metric_space β] [inhabited α] [inhabited β]
open sum (inl inr)
/- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible
with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam α + diam β + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default. -/
def sum.dist : α ⊕ β → α ⊕ β → ℝ
| (inl a) (inl a') := dist a a'
| (inr b) (inr b') := dist b b'
| (inl a) (inr b) := dist a (default α) + 1 + dist (default β) b
| (inr b) (inl a) := dist b (default β) + 1 + dist (default α) a
lemma sum.dist_eq_glue_dist {p q : α ⊕ β} :
sum.dist p q = glue_dist (λ_ : unit, default α) (λ_ : unit, default β) 1 p q :=
by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm]
private lemma sum.dist_comm (x y : α ⊕ β) : sum.dist x y = sum.dist y x :=
by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm]
lemma sum.one_dist_le {x : α} {y : β} : 1 ≤ sum.dist (inl x) (inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg) $
add_le_add_right (le_add_of_nonneg_left dist_nonneg) _
lemma sum.one_dist_le' {x : α} {y : β} : 1 ≤ sum.dist (inr y) (inl x) :=
by rw sum.dist_comm; exact sum.one_dist_le
private lemma sum.mem_uniformity (s : set ((α ⊕ β) × (α ⊕ β))) :
s ∈ (@uniformity (α ⊕ β) _).sets ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s :=
begin
split,
{ rintro ⟨hsα, hsβ⟩,
rcases mem_uniformity_dist.1 hsα with ⟨εα, εα0, hα⟩,
rcases mem_uniformity_dist.1 hsβ with ⟨εβ, εβ0, hβ⟩,
refine ⟨min (min εα εβ) 1, lt_min (lt_min εα0 εβ0) zero_lt_one, _⟩,
rintro (a|a) (b|b) h,
{ exact hα (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' },
{ exact hβ (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } },
{ rintro ⟨ε, ε0, H⟩,
split; rw [filter.mem_map, mem_uniformity_dist];
exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ }
end
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties follow from our
choice of the distance. The harder work is to show that the uniform structure defined by the distance coincides
with the disjoint union uniform structure. -/
def metric_space_sum : metric_space (α ⊕ β) :=
{ dist := sum.dist,
dist_self := λx, by cases x; simp only [sum.dist, dist_self],
dist_comm := sum.dist_comm,
dist_triangle := λp q r,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_dist_triangle _ _ _ (by simp; norm_num) _ _ _,
eq_of_dist_eq_zero := λp q,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _,
to_uniform_space := sum.uniform_space,
uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity }
local attribute [instance] metric_space_sum
lemma sum.dist_eq {x y : α ⊕ β} : dist x y = sum.dist x y := rfl
/-- The left injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inl : isometry (sum.inl : α → (α ⊕ β)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
/-- The right injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inr : isometry (sum.inr : β → (α ⊕ β)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
end sum
section gluing
/- Exact gluing of two metric spaces along isometric subsets. -/
variables [nonempty γ] [metric_space γ] [metric_space α] [metric_space β]
{Φ : γ → α} {Ψ : γ → β} {ε : ℝ}
open sum (inl inr)
local attribute [instance] premetric.dist_setoid
def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : premetric_space (α ⊕ β) :=
{ dist := glue_dist Φ Ψ 0,
dist_self := glue_dist_self Φ Ψ 0,
dist_comm := glue_dist_comm Φ Ψ 0,
dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp }
def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* :=
@metric_quot _ (glue_premetric hΦ hΨ)
instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) :
metric_space (glue_space hΦ hΨ) :=
@premetric.metric_space_quot _ (glue_premetric hΦ hΨ)
def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : α) : glue_space hΦ hΨ :=
by letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ; exact ⟦inl x⟧
def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : β) : glue_space hΦ hΨ :=
by letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ; exact ⟦inr y⟧
lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) :
(to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ :=
begin
letI : premetric_space (α ⊕ β) := glue_premetric hΦ hΨ,
funext,
simp only [comp, to_glue_l, to_glue_r, quotient.eq],
exact glue_dist_glued_points Φ Ψ 0 x
end
lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
end gluing --section
section inductive_limit
/- In this section, we define the inductive limit of
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric
space structure on Σn, X n, where the predistance dist x y is obtained by pushing x and y in a
common X k using composition by the f n, and taking the distance there. This does not depend on
the choice of k as the f n are isometries. The metric space associated to this premetric space
is the desired inductive limit.-/
open nat
variables {X : ℕ → Type u} [∀n, metric_space (X n)] {f : Πn, X n → X (n+1)}
/-- Predistance on the disjoint union Σn, X n. -/
def inductive_limit_dist (f : Πn, X n → X (n+1)) (x y : Σn, X n) : ℝ :=
dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1))
(le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1))
/-- The predistance on the disjoint union Σn, X n can be computed in any X k for large enough k.-/
lemma inductive_limit_dist_eq_dist (I : ∀n, isometry (f n))
(x y : Σn, X n) (m : ℕ) : ∀hx : x.1 ≤ m, ∀hy : y.1 ≤ m,
inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) :=
begin
induction m with m hm,
{ assume hx hy,
have A : max x.1 y.1 = 0, { rw [le_zero_iff_eq.1 hx, le_zero_iff_eq.1 hy], simp },
unfold inductive_limit_dist,
congr; simp only [A] },
{ assume hx hy,
by_cases h : max x.1 y.1 = m.succ,
{ unfold inductive_limit_dist,
congr; simp only [h] },
{ have : max x.1 y.1 ≤ succ m := by simp [hx, hy],
have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this,
have xm : x.1 ≤ m := le_trans (le_max_left _ _) this,
have ym : y.1 ≤ m := le_trans (le_max_right _ _) this,
rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq],
exact hm xm ym }}
end
/-- Premetric space structure on Σn, X n.-/
def inductive_premetric (I : ∀n, isometry (f n)) :
premetric_space (Σn, X n) :=
{ dist := inductive_limit_dist f,
dist_self := λx, by simp [dist, inductive_limit_dist],
dist_comm := λx y, begin
let m := max x.1 y.1,
have hx : x.1 ≤ m := le_max_left _ _,
have hy : y.1 ≤ m := le_max_right _ _,
unfold dist,
rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx,
dist_comm]
end,
dist_triangle := λx y z, begin
let m := max (max x.1 y.1) z.1,
have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _),
have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _),
have hz : z.1 ≤ m := le_max_right _ _,
calc inductive_limit_dist f x z
= dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) :
inductive_limit_dist_eq_dist I x z m hx hz
... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m)
+ dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) :
dist_triangle _ _ _
... = inductive_limit_dist f x y + inductive_limit_dist f y z :
by rw [inductive_limit_dist_eq_dist I x y m hx hy,
inductive_limit_dist_eq_dist I y z m hy hz]
end }
local attribute [instance] inductive_premetric premetric.dist_setoid
/-- The type giving the inductive limit in a metric space context. -/
def inductive_limit (I : ∀n, isometry (f n)) : Type* :=
@metric_quot _ (inductive_premetric I)
/-- Metric space structure on the inductive limit. -/
instance metric_space_inductive_limit (I : ∀n, isometry (f n)) :
metric_space (inductive_limit I) :=
@premetric.metric_space_quot _ (inductive_premetric I)
/-- Mapping each `X n` to the inductive limit. -/
def to_inductive_limit (I : ∀n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I :=
by letI : premetric_space (Σn, X n) := inductive_premetric I; exact ⟦sigma.mk n x⟧
/-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/
lemma to_inductive_limit_isometry (I : ∀n, isometry (f n)) (n : ℕ) :
isometry (to_inductive_limit I n) := isometry_emetric_iff_metric.2 $ λx y,
begin
change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y,
rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n),
le_rec_on_self, le_rec_on_self]
end
/-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/
lemma to_inductive_limit_commute (I : ∀n, isometry (f n)) (n : ℕ) :
(to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n :=
begin
funext,
simp only [comp, to_inductive_limit, quotient.eq],
show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0,
{ rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ,
le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self],
exact le_refl _,
exact le_refl _,
exact le_succ _ }
end
end inductive_limit --section
end metric --namespace
|
3a8b481d7ef17c596b779ee5f416ed95f50a2122 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/algebra/direct_sum/ring.lean | 8d6a415a8ad6178efa9cf2da582b8dddfbf7650f | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,250 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.algebra.basic
import algebra.algebra.operations
import algebra.direct_sum.basic
import group_theory.subgroup.basic
/-!
# Additively-graded multiplicative structures on `⨁ i, A i`
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an
additively-graded ring. The typeclasses are:
* `direct_sum.ghas_one A`
* `direct_sum.ghas_mul A`
* `direct_sum.gmonoid A`
* `direct_sum.gcomm_monoid A`
Respectively, these imbue the direct sum `⨁ i, A i` with:
* `direct_sum.has_one`
* `direct_sum.non_unital_non_assoc_semiring`
* `direct_sum.semiring`, `direct_sum.ring`
* `direct_sum.comm_semiring`, `direct_sum.comm_ring`
the base ring `A 0` with:
* `direct_sum.grade_zero.has_one`
* `direct_sum.grade_zero.non_unital_non_assoc_semiring`
* `direct_sum.grade_zero.semiring`, `direct_sum.grade_zero.ring`
* `direct_sum.grade_zero.comm_semiring`, `direct_sum.grade_zero.comm_ring`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* (nothing)
* `direct_sum.grade_zero.has_scalar (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)`
* `direct_sum.grade_zero.module (A 0)`
* (nothing)
Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action.
`direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring
homomorphism.
`direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`.
## Direct sums of subobjects
Additionally, this module provides helper functions to construct `gmonoid` and `gcomm_monoid`
instances for:
* `A : ι → submonoid S`:
`direct_sum.ghas_one.of_add_submonoids`, `direct_sum.ghas_mul.of_add_submonoids`,
`direct_sum.gmonoid.of_add_submonoids`, `direct_sum.gcomm_monoid.of_add_submonoids`.
* `A : ι → subgroup S`:
`direct_sum.ghas_one.of_add_subgroups`, `direct_sum.ghas_mul.of_add_subgroups`,
`direct_sum.gmonoid.of_add_subgroups`, `direct_sum.gcomm_monoid.of_add_subgroups`.
* `A : ι → submodule S`:
`direct_sum.ghas_one.of_submodules`, `direct_sum.ghas_mul.of_submodules`,
`direct_sum.gmonoid.of_submodules`, `direct_sum.gcomm_monoid.of_submodules`.
If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the
mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as
`direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`.
## tags
graded ring, filtered ring, direct sum, add_submonoid
-/
variables {ι : Type*} [decidable_eq ι]
namespace direct_sum
open_locale direct_sum
/-! ### Typeclasses -/
section defs
variables (A : ι → Type*)
/-- A graded version of `has_one`, which must be of grade 0. -/
class ghas_one [has_zero ι] :=
(one : A 0)
/-- A graded version of `has_mul` that also subsumes `non_unital_non_assoc_semiring` by requiring
the multiplication be an `add_monoid_hom`. Multiplication combines grades additively, like
`add_monoid_algebra`. -/
class ghas_mul [has_add ι] [Π i, add_comm_monoid (A i)] :=
(mul {i j} : A i →+ A j →+ A (i + j))
variables {A}
/-- `direct_sum.ghas_one` implies a `has_one (Σ i, A i)`, although this is only used as an instance
locally to define notation in `direct_sum.gmonoid` and similar typeclasses. -/
def ghas_one.to_sigma_has_one [has_zero ι] [ghas_one A] : has_one (Σ i, A i) := ⟨⟨_, ghas_one.one⟩⟩
/-- `direct_sum.ghas_mul` implies a `has_mul (Σ i, A i)`, although this is only used as an instance
locally to define notation in `direct_sum.gmonoid` and similar typeclasses. -/
def ghas_mul.to_sigma_has_mul [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] :
has_mul (Σ i, A i) :=
⟨λ (x y : Σ i, A i), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩
end defs
section defs
variables (A : ι → Type*)
local attribute [instance] ghas_one.to_sigma_has_one
local attribute [instance] ghas_mul.to_sigma_has_mul
/-- A graded version of `monoid`. -/
class gmonoid [add_monoid ι] [Π i, add_comm_monoid (A i)] extends ghas_mul A, ghas_one A :=
(one_mul (a : Σ i, A i) : 1 * a = a)
(mul_one (a : Σ i, A i) : a * 1 = a)
(mul_assoc (a : Σ i, A i) (b : Σ i, A i) (c : Σ i, A i) : a * b * c = a * (b * c))
/-- A graded version of `comm_monoid`. -/
class gcomm_monoid [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends gmonoid A :=
(mul_comm (a : Σ i, A i) (b : Σ i, A i) : a * b = b * a)
end defs
/-! ### Shorthands for creating the above typeclasses -/
section shorthands
variables {R : Type*}
/-! #### From `add_submonoid`s -/
/-- Build a `ghas_one` instance for a collection of `add_submonoid`s. -/
@[simps one]
def ghas_one.of_add_submonoids [semiring R] [has_zero ι]
(carriers : ι → add_submonoid R)
(one_mem : (1 : R) ∈ carriers 0) :
ghas_one (λ i, carriers i) :=
{ one := ⟨1, one_mem⟩ }
-- `@[simps]` doesn't generate a useful lemma, so we state one manually below.
/-- Build a `ghas_mul` instance for a collection of `add_submonoids`. -/
def ghas_mul.of_add_submonoids [semiring R] [has_add ι]
(carriers : ι → add_submonoid R)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
ghas_mul (λ i, carriers i) :=
{ mul := λ i j,
{ to_fun := λ a,
{ to_fun := λ b, ⟨(a * b : R), mul_mem a b⟩,
map_add' := λ _ _, subtype.ext (mul_add _ _ _),
map_zero' := subtype.ext (mul_zero _), },
map_add' := λ _ _, add_monoid_hom.ext $ λ _, subtype.ext (add_mul _ _ _),
map_zero' := add_monoid_hom.ext $ λ _, subtype.ext (zero_mul _) }, }
-- `@[simps]` doesn't generate this well
@[simp] lemma ghas_mul.of_add_submonoids_mul [semiring R] [has_add ι]
(carriers : ι → add_submonoid R) (mul_mem) {i j} (a : carriers i) (b : carriers j) :
@ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_submonoids carriers mul_mem) i j a b =
⟨a * b, mul_mem a b⟩ := rfl
/-- Build a `gmonoid` instance for a collection of `add_submonoid`s. -/
@[simps to_ghas_one to_ghas_mul]
def gmonoid.of_add_submonoids [semiring R] [add_monoid ι]
(carriers : ι → add_submonoid R)
(one_mem : (1 : R) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
gmonoid (λ i, carriers i) :=
{ one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _),
mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _),
mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩,
sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _),
..ghas_one.of_add_submonoids carriers one_mem,
..ghas_mul.of_add_submonoids carriers mul_mem }
/-- Build a `gcomm_monoid` instance for a collection of `add_submonoid`s. -/
@[simps to_gmonoid]
def gcomm_monoid.of_add_submonoids [comm_semiring R] [add_comm_monoid ι]
(carriers : ι → add_submonoid R)
(one_mem : (1 : R) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
gcomm_monoid (λ i, carriers i) :=
{ mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _),
..gmonoid.of_add_submonoids carriers one_mem mul_mem}
/-! #### From `add_subgroup`s -/
/-- Build a `ghas_one` instance for a collection of `add_subgroup`s. -/
@[simps one]
def ghas_one.of_add_subgroups [ring R] [has_zero ι]
(carriers : ι → add_subgroup R)
(one_mem : (1 : R) ∈ carriers 0) :
ghas_one (λ i, carriers i) :=
ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem
-- `@[simps]` doesn't generate a useful lemma, so we state one manually below.
/-- Build a `ghas_mul` instance for a collection of `add_subgroup`s. -/
def ghas_mul.of_add_subgroups [ring R] [has_add ι]
(carriers : ι → add_subgroup R)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
ghas_mul (λ i, carriers i) :=
ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem
-- `@[simps]` doesn't generate this well
@[simp] lemma ghas_mul.of_add_subgroups_mul [ring R] [has_add ι]
(carriers : ι → add_subgroup R) (mul_mem) {i j} (a : carriers i) (b : carriers j) :
@ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_subgroups carriers mul_mem) i j a b =
⟨a * b, mul_mem a b⟩ := rfl
/-- Build a `gmonoid` instance for a collection of `add_subgroup`s. -/
@[simps to_ghas_one to_ghas_mul]
def gmonoid.of_add_subgroups [ring R] [add_monoid ι]
(carriers : ι → add_subgroup R)
(one_mem : (1 : R) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
gmonoid (λ i, carriers i) :=
gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem
/-- Build a `gcomm_monoid` instance for a collection of `add_subgroup`s. -/
@[simps to_gmonoid]
def gcomm_monoid.of_add_subgroups [comm_ring R] [add_comm_monoid ι]
(carriers : ι → add_subgroup R)
(one_mem : (1 : R) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) :
gcomm_monoid (λ i, carriers i) :=
gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem
/-! #### From `submodules`s -/
variables {A : Type*}
/-- Build a `ghas_one` instance for a collection of `submodule`s. -/
@[simps one]
def ghas_one.of_submodules
[comm_semiring R] [semiring A] [algebra R A] [has_zero ι]
(carriers : ι → submodule R A)
(one_mem : (1 : A) ∈ carriers 0) :
ghas_one (λ i, carriers i) :=
ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem
-- `@[simps]` doesn't generate a useful lemma, so we state one manually below.
/-- Build a `ghas_mul` instance for a collection of `submodule`s. -/
def ghas_mul.of_submodules
[comm_semiring R] [semiring A] [algebra R A] [has_add ι]
(carriers : ι → submodule R A)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) :
ghas_mul (λ i, carriers i) :=
ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem
-- `@[simps]` doesn't generate this well
@[simp] lemma ghas_mul.of_submodules_mul
[comm_semiring R] [semiring A] [algebra R A] [has_add ι]
(carriers : ι → submodule R A) (mul_mem) {i j} (a : carriers i) (b : carriers j) :
@ghas_mul.mul _ _ _ _ _ (ghas_mul.of_submodules carriers mul_mem) i j a b =
⟨a * b, mul_mem a b⟩ := rfl
/-- Build a `gmonoid` instance for a collection of `submodules`s. -/
@[simps to_ghas_one to_ghas_mul]
def gmonoid.of_submodules
[comm_semiring R] [semiring A] [algebra R A] [add_monoid ι]
(carriers : ι → submodule R A)
(one_mem : (1 : A) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) :
gmonoid (λ i, carriers i) :=
gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem
/-- Build a `gcomm_monoid` instance for a collection of `submodules`s. -/
@[simps to_gmonoid]
def gcomm_monoid.of_submodules
[comm_semiring R] [comm_semiring A] [algebra R A] [add_comm_monoid ι]
(carriers : ι → submodule R A)
(one_mem : (1 : A) ∈ carriers 0)
(mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) :
gcomm_monoid (λ i, carriers i) :=
gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem
end shorthands
variables (A : ι → Type*)
/-! ### Instances for `⨁ i, A i` -/
section one
variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)]
instance : has_one (⨁ i, A i) :=
{ one := direct_sum.of (λ i, A i) 0 ghas_one.one}
end one
section mul
variables [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A]
open add_monoid_hom (map_zero map_add flip_apply coe_comp comp_hom_apply_apply)
/-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/
def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i :=
direct_sum.to_add_monoid $ λ i,
add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $
(direct_sum.of A _).comp_hom.comp ghas_mul.mul
instance : non_unital_non_assoc_semiring (⨁ i, A i) :=
{ mul := λ a b, mul_hom A a b,
zero := 0,
add := (+),
zero_mul := λ a, by simp only [map_zero, add_monoid_hom.zero_apply],
mul_zero := λ a, by simp only [map_zero],
left_distrib := λ a b c, by simp only [map_add],
right_distrib := λ a b c, by simp only [map_add, add_monoid_hom.add_apply],
.. direct_sum.add_comm_monoid _ _}
variables {A}
lemma mul_hom_of_of {i j} (a : A i) (b : A j) :
mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (ghas_mul.mul a b) :=
begin
unfold mul_hom,
rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app,
comp_hom_apply_apply, coe_comp, function.comp_app],
end
lemma of_mul_of {i j} (a : A i) (b : A j) :
of _ i a * of _ j b = of _ (i + j) (ghas_mul.mul a b) :=
mul_hom_of_of a b
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A]
open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply)
private lemma one_mul (x : ⨁ i, A i) : 1 * x = x :=
suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw mul_hom_of_of,
exact dfinsupp.single_eq_of_sigma_eq (gmonoid.one_mul ⟨i, xi⟩),
end
private lemma mul_one (x : ⨁ i, A i) : x * 1 = x :=
suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw [flip_apply, mul_hom_of_of],
exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_one ⟨i, xi⟩),
end
private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) :=
suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom
= (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom
(mul_hom A).flip.comp_hom.comp (mul_hom A)).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c,
begin
ext ai ax bi bx ci cx : 6,
dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply],
rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of],
exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_assoc ⟨ai, ax⟩ ⟨bi, bx⟩ ⟨ci, cx⟩),
end
/-- The `semiring` structure derived from `gmonoid A`. -/
instance semiring : semiring (⨁ i, A i) := {
one := 1,
mul := (*),
zero := 0,
add := (+),
one_mul := one_mul A,
mul_one := mul_one A,
mul_assoc := mul_assoc A,
..direct_sum.non_unital_non_assoc_semiring _, }
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A]
private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a :=
suffices mul_hom A = (mul_hom A).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b,
begin
apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx,
rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of],
exact dfinsupp.single_eq_of_sigma_eq (gcomm_monoid.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩),
end
/-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/
instance comm_semiring : comm_semiring (⨁ i, A i) := {
one := 1,
mul := (*),
zero := 0,
add := (+),
mul_comm := mul_comm A,
..direct_sum.semiring _, }
end comm_semiring
section ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A]
/-- The `ring` derived from `gmonoid A`. -/
instance ring : ring (⨁ i, A i) := {
one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.semiring _),
..(direct_sum.add_comm_group _), }
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A]
/-- The `comm_ring` derived from `gcomm_monoid A`. -/
instance comm_ring : comm_ring (⨁ i, A i) := {
one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.ring _),
..(direct_sum.comm_semiring _), }
end comm_ring
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various
types of multiplicative structure.
-/
section grade_zero
section one
variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)]
/-- `1 : A 0` is the value provided in `direct_sum.ghas_one.one`. -/
@[nolint unused_arguments]
instance grade_zero.has_one : has_one (A 0) :=
⟨ghas_one.one⟩
@[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl
end one
section mul
variables [add_monoid ι] [Π i, add_comm_monoid (A i)] [ghas_mul A]
/-- `(•) : A 0 → A i → A i` is the value provided in `direct_sum.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + i)` into `A i`.
-/
instance grade_zero.has_scalar (i : ι) : has_scalar (A 0) (A i) :=
{ smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) }
/-- `(*) : A 0 → A 0 → A 0` is the value provided in `direct_sum.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + 0)` into `A 0`.
-/
instance grade_zero.has_mul : has_mul (A 0) :=
{ mul := (•) }
@[simp]lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl
@[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b :=
begin
rw of_mul_of,
dsimp [has_mul.mul, direct_sum.of, dfinsupp.single_add_hom_apply],
congr' 1,
rw zero_add,
apply eq_rec_heq,
end
@[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:=
of_zero_smul A a b
instance grade_zero.non_unital_non_assoc_semiring : non_unital_non_assoc_semiring (A 0) :=
function.injective.non_unital_non_assoc_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of A 0).map_add (of_zero_mul A)
instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) :=
begin
letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom,
refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A),
end
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A]
/-- The `semiring` structure derived from `gmonoid A`. -/
instance grade_zero.semiring : semiring (A 0) :=
function.injective.semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
/-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/
def of_zero_ring_hom : A 0 →+* (⨁ i, A i) :=
{ map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) }
/-- Each grade `A i` derives a `A 0`-module structure from `gmonoid A`. Note that this results
in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`.
-/
instance grade_zero.module {i} : module (A 0) (A i) :=
begin
letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A),
exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a),
end
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A]
/-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/
instance grade_zero.comm_semiring : comm_semiring (A 0) :=
function.injective.comm_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
end comm_semiring
section ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A]
/-- The `ring` derived from `gmonoid A`. -/
instance grade_zero.ring : ring (A 0) :=
function.injective.ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A]
/-- The `comm_ring` derived from `gcomm_monoid A`. -/
instance grade_zero.comm_ring : comm_ring (A 0) :=
function.injective.comm_ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
end comm_ring
end grade_zero
section to_semiring
variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] [semiring R]
variables {A}
/-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`,
then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext' (F G : (⨁ i, A i) →+* R)
(h : ∀ i, (F : (⨁ i, A i) →+ R).comp (of _ i) = (G : (⨁ i, A i) →+ R).comp (of _ i)) : F = G :=
ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h
/-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`.
Of particular interest is the case when `A i` are bundled subojects, `f` is the family of
coercions such as `add_submonoid.subtype (A i)`, and the `[gmonoid A]` structure originates from
`direct_sum.gmonoid.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul`
can be discharged by `rfl`. -/
@[simps]
def to_semiring
(f : Π i, A i →+ R) (hone : f _ (ghas_one.one) = 1)
(hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (ghas_mul.mul ai aj) = f _ ai * f _ aj) :
(⨁ i, A i) →+* R :=
{ to_fun := to_add_monoid f,
map_one' := begin
change (to_add_monoid f) (of _ 0 _) = 1,
rw to_add_monoid_of,
exact hone
end,
map_mul' := begin
rw (to_add_monoid f).map_mul_iff,
ext xi xv yi yv : 4,
show to_add_monoid f (of A xi xv * of A yi yv) =
to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv),
rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of],
exact hmul _ _,
end,
.. to_add_monoid f}
@[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) :
to_semiring f hone hmul (of _ i x) = f _ x :=
to_add_monoid_of f i x
@[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul):
(to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl
/-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`.
-/
@[simps]
def lift_ring_hom :
{f : Π {i}, A i →+ R //
f (ghas_one.one) = 1 ∧
∀ {i j} (ai : A i) (aj : A j), f (ghas_mul.mul ai aj) = f ai * f aj} ≃
((⨁ i, A i) →+* R) :=
{ to_fun := λ f, to_semiring f.1 f.2.1 f.2.2,
inv_fun := λ F,
⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw ←F.map_one,
refl
end, λ i j ai aj, begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw [←F.map_mul, of_mul_of],
end⟩,
left_inv := λ f, begin
ext xi xv,
exact to_add_monoid_of f.1 xi xv,
end,
right_inv := λ F, begin
apply ring_hom.coe_add_monoid_hom_injective,
ext xi xv,
simp only [ring_hom.coe_add_monoid_hom_mk,
direct_sum.to_add_monoid_of,
add_monoid_hom.mk_coe,
add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom],
end}
/-- Two `ring_hom`s out of a direct sum are equal if they agree on the generators.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext ⦃f g : (⨁ i, A i) →+* R⦄
(h : ∀ i, (↑f : (⨁ i, A i) →+ R).comp (of A i) = (↑g : (⨁ i, A i) →+ R).comp (of A i)) :
f = g :=
direct_sum.lift_ring_hom.symm.injective $ subtype.ext $ funext h
end to_semiring
end direct_sum
/-! ### Concrete instances -/
/-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/
instance semiring.direct_sum_gmonoid {R : Type*} [add_monoid ι] [semiring R] :
direct_sum.gmonoid (λ i : ι, R) :=
{ mul := λ i j, add_monoid_hom.mul,
one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)),
mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)),
mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)),
one := 1 }
@[simp] lemma semiring.direct_sum_mul {R : Type*} [add_monoid ι] [semiring R] {i j} (x y : R) :
@direct_sum.ghas_mul.mul _ _ (λ _ : ι, R) _ _ _ i j x y = x * y := rfl
open_locale direct_sum
-- To check the lemma above does match
example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) :
(direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) :=
by rw [direct_sum.of_mul_of, semiring.direct_sum_mul]
/-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure.
-/
instance comm_semiring.direct_sum_gcomm_monoid {R : Type*} [add_comm_monoid ι] [comm_semiring R] :
direct_sum.gcomm_monoid (λ i : ι, R) :=
{ mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)),
.. semiring.direct_sum_gmonoid }
namespace submodule
variables {R A : Type*} [comm_semiring R]
/-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/
instance nat_power_direct_sum_gmonoid [semiring A] [algebra R A] (S : submodule R A) :
direct_sum.gmonoid (λ i : ℕ, ↥(S ^ i)) :=
direct_sum.gmonoid.of_submodules _
(by { rw [←one_le, pow_zero], exact le_rfl })
(λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop })
/-- A direct sum of powers of a submodule of a commutative algebra has a commutative multiplicative
structure. -/
instance nat_power_direct_sum_gcomm_monoid [comm_semiring A] [algebra R A] (S : submodule R A) :
direct_sum.gcomm_monoid (λ i : ℕ, ↥(S ^ i)) :=
direct_sum.gcomm_monoid.of_submodules _
(by { rw [←one_le, pow_zero], exact le_rfl })
(λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop })
end submodule
|
16c4e9e640e027b58c8f47ac957f14d3e58fedbf | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/topology/metric_space/basic.lean | d27a5ed4c4592d0d1c56a2628c7eb45348b8e8f8 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 75,262 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Metric spaces.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
-/
import topology.metric_space.emetric_space
import topology.algebra.ordered
open set filter classical topological_space
noncomputable theory
open_locale uniformity topological_space big_operators filter
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos h two_pos) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
section prio
set_option default_priority 100 -- see Note [default priority]
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
-/
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)
(edist : α → α → ennreal := λx y, ennreal.of_real (dist x y))
(edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
end prio
variables [metric_space α]
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_uniform_space' : uniform_space α :=
metric_space.to_uniform_space
@[priority 200] -- see Note [lower instance priority]
instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩
@[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x
theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
metric_space.edist_dist x y
@[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc
dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _)
... = ∑ i in finset.Ico m (n+1), _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this two_pos
@[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
@[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b :=
abs_of_nonneg dist_nonneg
theorem eq_of_forall_dist_le {x y : α} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/-- Distance as a nonnegative real number. -/
def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] }
/--In a metric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ :=
by rw [edist_dist x y]; apply ennreal.coe_ne_top
/--In a metric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ :=
ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y)
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) :=
by rw [dist_nndist, nnreal.of_real_coe]
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle x y z
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
by simpa [nnreal.coe_le_coe] using dist_triangle_left x y z
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle_right x y z
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate metric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
@[simp] lemma nonempty_ball (h : 0 < ε) : (ball x ε).nonempty :=
⟨x, by simp [h]⟩
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
lemma nonempty_closed_ball (h : 0 ≤ ε) : (closed_ball x ε).nonempty :=
⟨x, by simp [h]⟩
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm]
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt dist_nonneg hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@two_pos ℝ _)]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
@[simp] theorem ball_eq_empty_iff_nonpos : ball x ε = ∅ ↔ ε ≤ 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0,
λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩
@[simp] theorem closed_ball_eq_empty_iff_neg : closed_ball x ε = ∅ ↔ ε < 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λ h, not_le.1 $ λ ε0, h x $ mem_closed_ball_self ε0,
λ ε0 y h, not_lt_of_le (mem_closed_ball.1 h) (lt_of_lt_of_le ε0 dist_nonneg)⟩
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty_iff_nonpos]
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩)
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases dense ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
begin
dsimp [uniform_continuous_on],
rw (metric.uniformity_basis_dist.inf_principal (s.prod s)).tendsto_iff metric.uniformity_basis_dist,
simp only [and_imp, exists_prop, prod.forall, mem_inter_eq, gt_iff_lt, mem_set_of_eq, mem_prod],
finish,
end
theorem uniform_embedding_iff [metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : α → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_sets_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball]
theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
end metric
open metric
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_separated : separated_space α :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-Instantiate a metric space as an emetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
metric.uniformity_basis_edist.eq_binfi
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹metric_space α› }
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball_nnreal {x : α} {ε : nnreal} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball_nnreal {x : α} {ε : nnreal} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α)
(H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') :
metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans metric_space.uniformity_dist }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
let m : metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_edist, metric.uniformity_edist], refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
begin
-- this follows from the same criterion in emetric spaces. We just need to translate
-- the convergence assumption from `dist` to `edist`
apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)),
{ simp [hB] },
{ assume u Hu,
apply H,
assume N n m hn hm,
rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist],
exact Hu N n m hn hm }
end
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ dist := λx y, abs (x - y),
dist_self := by simp [abs_zero],
eq_of_dist_eq_zero := by simp [sub_eq_zero],
dist_comm := assume x y, abs_sub _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x :=
by simp [real.dist_eq]
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x, begin
simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r,
by simp [abs_sub, ball, real.dist_eq]],
apply le_antisymm,
{ simp [le_infi_iff],
exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) },
{ intros s h,
rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩,
exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) },
end
lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a metric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the metric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : h m n N hm hn
... ≤ abs (b N) : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N))
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, real.le_Sup _ (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : metric_space β) : metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe (λ x y, subtype.ext) t
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
section nnreal
instance : metric_space nnreal := by unfold nnreal; apply_instance
lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl
lemma nnreal.nndist_eq (a b : nnreal) :
nndist a b = max (a - b) (b - a) :=
begin
wlog h : a ≤ b,
{ apply nnreal.coe_eq.1,
rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq,
nnreal.coe_sub h, abs, neg_sub],
apply max_eq_right,
linarith [nnreal.coe_le_coe.2 h] },
rwa [nndist_comm, max_comm]
end
end nnreal
section prod
instance prod.metric_space_max [metric_space β] : metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, ← this.map_max]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp only [uniformity_basis_dist.eq_binfi, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in metric spaces-/
theorem mem_closure_iff {α : Type u} [metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
instance metric_space_pi : metric_space (Πb, π b) :=
begin
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine emetric_space.to_metric_space_of_dist
(λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _,
show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤,
{ assume x y,
rw ← lt_top_iff_ne_top,
have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top,
simp [edist, this],
assume b,
rw lt_top_iff_ne_top,
exact edist_ne_top (x b) (y b) },
show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) =
ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))),
{ assume x y,
have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))),
{ simp [edist_nndist],
refine eq.symm (comp_sup_eq_sup_comp_of_is_total _ _ _),
exact (assume x y h, ennreal.coe_le_coe.2 h), refl },
rw this,
refl }
end
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to nnreal using le_of_lt hr,
rw_mod_cast [dist_pi_def, finset.sup_lt_iff],
{ simp [nndist], refl },
{ exact hr }
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to nnreal using hr,
rw_mod_cast [dist_pi_def, finset.sup_le_iff],
simp [nndist],
refl
end
/-- An open ball in a product space is a product of open balls. The assumption `0 < r`
is necessary for the case of the empty product. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = { y | ∀b, y b ∈ ball (x b) r } :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r`
is necessary for the case of the empty product. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } :=
by { ext p, simp [dist_pi_le_iff hr] }
end pi
section compact
/-- Any compact set in a metric space can be covered by finitely many balls of a given positive
radius -/
lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A metric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [metric_space α] : Prop :=
(compact_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R (le_refl _)).inter_right is_closed_ball }
end⟩
/- A compact metric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
begin
apply locally_compact_of_compact_nhds,
intros x,
existsi closed_ball x 1,
split,
{ apply mem_nhds_iff.2,
existsi (1 : ℝ),
simp,
exact ⟨zero_lt_one, ball_subset_closed_ball⟩ },
{ apply proper_space.compact_ball }
end
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases A with ⟨t, ⟨t_fset, ht⟩⟩,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt),
have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this,
rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this)
with ⟨y, _, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A proper metric space is separable, and therefore second countable. Indeed, any ball is
compact, and therefore admits a countable dense subset. Taking a countable union over the balls
centered at a fixed point and with integer radius, one obtains a countable set which is
dense in the whole space. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
/- We show that the space admits a countable dense subset. The case where the space is empty
is special, and trivial. -/
have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩,
have B : (univ : set α).nonempty → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
begin
/- When the space is not empty, we take a point `x` in the space, and then a countable set
`T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set
`t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union
of countable sets, and dense in the space by construction. -/
rintros ⟨x, x_univ⟩,
choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t),
from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _),
let t := (⋃n:ℕ, T (n : ℝ)),
have T₁ : countable t := by finish [countable_Union],
have T₂ : closure t ⊆ univ := by simp,
have T₃ : univ ⊆ closure t :=
begin
intros y y_univ,
rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩,
have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large,
have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish,
have : y ∈ closure (T (n : ℝ)) := by rwa h' at h,
show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))),
end,
exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩
end,
haveI : separable_space α := ⟨(eq_empty_or_nonempty univ).elim A B⟩,
apply emetric.second_countable_of_separable,
end
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply compact_pi_infinite (λb, _),
apply (h b).compact_ball
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if, for every `ε > 0`, there is a countable set which is
`ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
choose T T_dense using H,
have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 :=
λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)),
have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos.2 (I1 n),
let t := ⋃n:ℕ, T (n+1)⁻¹ (I n),
have count_t : countable t := by finish [countable_Union],
have clos_t : closure t = univ,
{ refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff.2 (λε εpos, _)),
rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩,
have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one),
have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this,
rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩,
have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))),
exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ },
haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩,
exact emetric.second_countable_of_separable α
end
/-- A metric space space is second countable if one can reconstruct up to any `ε>0` any element of
the space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a metric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.subset ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.subset hC }
end
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
begin
cases h with C h,
replace h : ∀ p : α × α, p ∈ set.prod s s → dist p.1 p.2 ∈ { d | d ≤ C },
{ rintros ⟨x, y⟩ ⟨x_in, y_in⟩,
exact h x y x_in y_in },
use C,
suffices : ∀ p : α × α, p ∈ closure (set.prod s s) → dist p.1 p.2 ∈ { d | d ≤ C },
{ rw closure_prod_eq at this,
intros x y x_in y_in,
exact this (x, y) (mk_mem_prod x_in y_in) },
intros p p_in,
have := mem_closure continuous_dist p_in h,
rwa (is_closed_le' C).closure_eq at this
end
alias bounded_closure_of_bounded ← bounded.closure
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A compact set is bounded -/
lemma bounded_of_compact {s : set α} (h : is_compact s) : bounded s :=
-- We cover the compact set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in
bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
alias bounded_of_compact ← is_compact.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
h.is_compact.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.subset (subset_univ _)
/-- The Heine–Borel theorem:
In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, begin
rintro ⟨hc, hb⟩,
cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]},
rcases h with ⟨x, hx⟩,
rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr
end⟩
/-- The image of a proper space under an expanding onto map is proper. -/
lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β)
(f_cont : continuous f) (hf : range f = univ) (C : ℝ)
(hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β :=
begin
apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _),
let K := f ⁻¹' (closed_ball x₀ r),
have A : is_closed K :=
continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) is_closed_ball,
have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc
dist x y ≤ C * dist (f x) (f y) : hC x y
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg)
... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) :
mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _)
... ≤ max C 0 * (r + r) : begin
simp only [mem_closed_ball, mem_preimage] at hx hy,
exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _)
end⟩,
have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩,
have C : is_compact (f '' K) := this.image f_cont,
have : f '' K = closed_ball x₀ r,
by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ },
rwa this at C
end
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le_of_forall_edist_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top
(ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy))
(λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
begin
simp only [bounded_iff_ediam_ne_top, not_not, ne.def] at h,
simp [diam, h]
end
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
classical, by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.subset (subset_union_left _ _),
have ht : bounded t, from H.subset (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (le_of_lt two_pos) h) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
|
fc0264d2897a05663f1f6508352542d48c87754d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/interval_cases_auto.lean | 160cd7275eba3812456037406479887f6ba32714 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,429 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
Case bashing on variables in finite intervals.
In particular, `interval_cases n`
1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b`
(although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed),
and also makes use of lower and upper bounds found via `le_top` and `bot_le`
(so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then
2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`,
assuming an appropriate `fintype` instance can be found for the type of `n`.
The variable `n` can belong to any type `α`, with the following restrictions:
* only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?)
* an instance of `decidable_eq α` is available,
* an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`,
* an explicit upper bound can be found amongst the hypotheses, or from `le_top n`,
* if multiple bounds are located, an instance of `linear_order α` is available, and
* an instance of `fintype set.Ico l u` is available for the relevant bounds.
You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`.
The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`,
in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.fin_cases
import Mathlib.data.fintype.intervals
import Mathlib.PostPort
universes u_1
namespace Mathlib
namespace tactic
namespace interval_cases
/--
If `e` easily implies `(%%n < %%b)`
for some explicit `b`,
return that proof.
-/
-- We use `expr.to_rat` merely to decide if an `expr` is an explicit number.
-- It would be more natural to use `expr.to_int`, but that hasn't been implemented.
/--
If `e` easily implies `(%%n ≥ %%b)`
for some explicit `b`,
return that proof.
-/
/-- Combine two upper bounds. -/
/-- Combine two lower bounds. -/
/-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/
/--
Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`.
-/
/--
Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`.
-/
/-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/
/-- The finset of elements of a set `s` for which we have `fintype s`. -/
def set_elems {α : Type u_1} [DecidableEq α] (s : set α) [fintype ↥s] : finset α :=
finset.image subtype.val (fintype.elems ↥s)
/-- Each element of `s` is a member of `set_elems s`. -/
theorem mem_set_elems {α : Type u_1} [DecidableEq α] (s : set α) [fintype ↥s] {a : α} (h : a ∈ s) :
a ∈ set_elems s :=
iff.mpr finset.mem_image
(Exists.intro { val := a, property := h }
(Exists.intro (fintype.complete { val := a, property := h }) rfl))
end interval_cases
/-- Call `fin_cases` on membership of the finset built from
an `Ico` interval corresponding to a lower and an upper bound.
Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and
`hu` should be of the form `n < b`, for some explicit `b`.
By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`.
-/
namespace interactive
/--
`interval_cases n` searches for upper and lower bounds on a variable `n`,
and if bounds are found,
splits into separate cases for each possible value of `n`.
As an example, in
```
example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
begin
interval_cases n,
all_goals {simp}
end
```
after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`.
You can also explicitly specify a lower and upper bound to use,
as `interval_cases using hl hu`.
The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`,
in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`.
You can specify a name `h` for the new hypothesis,
as `interval_cases n with h` or `interval_cases n using hl hu with h`.
-/
/--
`interval_cases n` searches for upper and lower bounds on a variable `n`,
end Mathlib |
f8e2c5101e9fd80f1ffdc051d6dac98f0bfef5f0 | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/analysis/normed_space/basic.lean | 50864be84462792ab6ff8642a7cd086cdee581c9 | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 59,450 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.instances.nnreal
import topology.algebra.module
import topology.metric_space.antilipschitz
/-!
# Normed spaces
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space big_operators nnreal ennreal
/-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to
be extended in more interesting classes specifying the properties of the norm. -/
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
/-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines
a metric space structure. -/
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 },
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }
end }
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this },
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }
end }
/-- A normed group can be built from a norm that satisfies algebraic properties. This is
formalised in this structure. -/
structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop :=
(norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0)
(triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥)
(norm_neg : ∀ x : α, ∥-x∥ = ∥x∥)
/-- Constructing a normed group from core properties of a norm, i.e., registering the distance and
the metric space structure from the norm properties. -/
noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α]
(C : normed_group.core α) : normed_group α :=
{ dist := λ x y, ∥x - y∥,
dist_eq := assume x y, by refl,
dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp),
eq_of_dist_eq_zero := assume x y h, sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h,
dist_triangle := assume x y z,
calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel
... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _,
dist_comm := assume x y,
calc ∥x - y∥ = ∥ -(y - x)∥ : by simp
... = ∥y - x∥ : by { rw [C.norm_neg] } }
instance : normed_group ℝ :=
{ norm := λ x, abs x,
dist_eq := assume x y, rfl }
lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
lemma dist_eq_norm' (g h : α) : dist g h = ∥h - g∥ :=
by rw [dist_comm, dist_eq_norm]
@[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ :=
by rw [dist_eq_norm, sub_zero]
@[simp] lemma dist_zero_left : dist (0:α) = norm :=
funext $ λ g, by rw [dist_comm, dist_zero_right]
lemma tendsto_norm_cocompact_at_top [proper_space α] :
tendsto norm (cocompact α) at_top :=
by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0:α)
lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ :=
by simpa only [dist_eq_norm] using dist_comm g h
@[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ :=
by simpa using norm_sub_rev 0 g
@[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h :=
by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev]
@[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ :=
by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg]
@[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ :=
by simpa only [sub_eq_add_neg] using dist_add_right _ _ _
/-- Triangle inequality for the norm. -/
lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 (-h)
lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ + g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂)
lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ :=
le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂)
lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ :=
le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) :
abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) :=
by simpa only [dist_add_left, dist_add_right, dist_comm h₂]
using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂)
@[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ :=
by { rw[←dist_zero_right], exact dist_nonneg }
@[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 :=
dist_zero_right g ▸ dist_eq_zero
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl
@[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 :=
by rw [subsingleton.elim x 0, norm_zero]
lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ :=
finset.le_sum_of_subadditive norm norm_zero norm_add_le
lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) :
∥∑ b in s, f b∥ ≤ ∑ b in s, n b :=
le_trans (norm_sum_le s f) (finset.sum_le_sum h)
@[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 :=
dist_zero_right g ▸ dist_pos
@[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
lemma eq_of_norm_sub_le_zero {g h : α} (a : ∥g - h∥ ≤ 0) : g = h :=
by rwa [← sub_eq_zero, ← norm_le_zero_iff]
lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 h
lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ - g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ :=
by { rw dist_eq_norm, apply norm_sub_le }
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
by simpa [dist_eq_norm] using abs_dist_sub_le g h 0
lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ :=
le_trans (le_abs_self _) (abs_norm_sub_norm_le g h)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v :=
begin
apply eq_of_dist_eq_zero,
rwa dist_eq_norm
end
lemma norm_sub_eq_zero_iff {u v : α} : ∥u - v∥ = 0 ↔ u = v :=
begin
convert dist_eq_zero,
rwa dist_eq_norm
end
lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ :=
calc ∥v∥ = ∥u - (u - v)∥ : by abel
... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _
lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} :=
set.ext $ assume a, by simp
lemma mem_ball_iff_norm {g h : α} {r : ℝ} :
h ∈ ball g r ↔ ∥h - g∥ < r :=
by rw [mem_ball, dist_eq_norm]
lemma mem_ball_iff_norm' {g h : α} {r : ℝ} :
h ∈ ball g r ↔ ∥g - h∥ < r :=
by rw [mem_ball', dist_eq_norm]
lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} :
h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r :=
by rw [mem_closed_ball, dist_eq_norm]
lemma mem_closed_ball_iff_norm' {g h : α} {r : ℝ} :
h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r :=
by rw [mem_closed_ball', dist_eq_norm]
lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) :
∥h∥ ≤ ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H }
lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) :
∥h∥ < ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H }
@[simp] lemma mem_sphere_iff_norm (v w : α) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r :=
by simp [dist_eq_norm]
@[simp] lemma mem_sphere_zero_iff_norm {w : α} {r : ℝ} : w ∈ sphere (0:α) r ↔ ∥w∥ = r :=
by simp [dist_eq_norm]
@[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:α) r) : ∥(x:α)∥ = r :=
mem_sphere_zero_iff_norm.mp x.2
lemma nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:α) r) : (x:α) ≠ 0 :=
by rwa [← norm_pos_iff, norm_eq_of_mem_sphere]
lemma nonzero_of_mem_unit_sphere (x : sphere (0:α) 1) : (x:α) ≠ 0 :=
by { apply nonzero_of_mem_sphere, norm_num }
/-- We equip the sphere, in a normed group, with a formal operation of negation, namely the
antipodal map. -/
instance {r : ℝ} : has_neg (sphere (0:α) r) :=
{ neg := λ w, ⟨-↑w, by simp⟩ }
@[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0:α) r) :
(((-v) : sphere _ _) : α) = - (v:α) :=
rfl
theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} :
tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε :=
metric.tendsto_nhds.trans $ by simp only [dist_zero_right]
lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} :
tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε :=
by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm]
/-- A homomorphism `f` of normed groups is Lipschitz, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
lipschitz_with (nnreal.of_real C) f :=
lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y)
lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} :
lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ :=
by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm]
lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s)
{x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ :=
lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in
/-- A homomorphism `f` of normed groups is continuous, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.continuous_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
continuous f :=
(f.lipschitz_of_bound C h).continuous
section nnnorm
/-- Version of the norm taking values in nonnegative reals. -/
def nnnorm (a : α) : ℝ≥0 := ⟨norm a, norm_nonneg a⟩
@[simp, norm_cast] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
@[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
nnreal.coe_le_coe.2 $ norm_add_le g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
nnreal.coe_le_coe.2 $ dist_norm_norm_le g h
lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ℝ≥0∞) :=
ennreal.of_real_eq_coe_nnreal _
lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ℝ≥0∞) :=
by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm]
lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ℝ≥0∞) :=
by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero]
lemma mem_emetric_ball_0_iff {x : β} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : β) r ↔ ↑(nnnorm x) < r :=
by rw [emetric.mem_ball, edist_eq_coe_nnnorm]
lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) :
nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ :=
nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂
lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) :
edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ :=
by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le }
lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α),
nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) :=
finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le
end nnnorm
lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : ℝ≥0} {f : α → β}
(hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) :=
λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y
lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : ℝ≥0} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x + g x) :=
λ x y,
calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_add_add_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : ℝ≥0} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x - g x) :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : ℝ≥0} {f : α → β}
(hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g)
(hK : Kg < Kf⁻¹) :
antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) :=
begin
refine antilipschitz_with.of_le_mul_dist (λ x y, _),
rw [nnreal.coe_inv, ← div_eq_inv_mul],
rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK),
rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul],
calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) :
sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y)
... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _)
end
/-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/
instance add_subgroup.normed_group {E : Type*} [normed_group E] (s : add_subgroup E) :
normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- If `x` is an element of a subgroup `s` of a normed group `E`, its norm in `s` is equal to its
norm in `E`. -/
@[simp] lemma coe_norm_subgroup {E : Type*} [normed_group E] {s : add_subgroup E} (x : s) :
∥x∥ = ∥(x:E)∥ :=
rfl
/-- A submodule of a normed group is also a normed group, with the restriction of the norm.
See note [implicit instance arguments]. -/
instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its
norm in `s`.
See note [implicit instance arguments]. -/
@[simp, norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) :
∥(x : E)∥ = ∥x∥ :=
rfl
@[simp] lemma submodule.norm_mk {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : E) (hx : x ∈ s) :
∥(⟨x, hx⟩ : s)∥ = ∥x∥ :=
rfl
/-- normed group instance on the product of two normed groups, using the sup norm. -/
instance prod.normed_group : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl
lemma prod.nnnorm_def (x : α × β) : nnnorm x = max (nnnorm x.1) (nnnorm x.2) :=
by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this }
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
le_max_left _ _
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
le_max_right _ _
lemma norm_prod_le_iff {x : α × β} {r : ℝ} :
∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r :=
max_le_iff
/-- normed group instance on the product of finitely many normed groups, using the sup norm. -/
instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] :
normed_group (Πi, π i) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : ℝ≥0) : ℝ),
dist_eq := assume x y,
congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a,
show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
/-- The norm of an element in a product space is `≤ r` if and only if the norm of each
component is. -/
lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r)
{x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r :=
by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply]
/-- The norm of an element in a product space is `< r` if and only if the norm of each
component is. -/
lemma pi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 < r)
{x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r :=
by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply]
lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) :
∥x i∥ ≤ ∥x∥ :=
(pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i
@[simp] lemma pi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ :=
by simpa only [← dist_zero_right] using dist_pi_const a 0
@[simp] lemma pi_nnnorm_const [nonempty ι] [fintype ι] (a : α) :
nnnorm (λ i : ι, a) = nnnorm a :=
nnreal.eq $ pi_norm_const a
lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} :
tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) :=
by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] }
lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} :
tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) :=
by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] }
/-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real
function `g` which tends to `0`, then `f` tends to `0`.
In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of
similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is
phrased using "eventually" and the non-`'` version is phrased absolutely. -/
lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ}
(h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n)
(h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_zero_iff_norm_tendsto_zero.mpr
(squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h')
/-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which
tends to `0`, then `f` tends to `0`. -/
lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ}
(h : ∀ (n:γ), ∥f n∥ ≤ g n)
(h' : tendsto g t₀ (𝓝 0)) :
tendsto f t₀ (𝓝 0) :=
squeeze_zero_norm' (eventually_of_forall h) h'
lemma tendsto_norm_sub_self (x : α) : tendsto (λ g : α, ∥g - x∥) (𝓝 x) (𝓝 0) :=
by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:α)) (𝓝 x) _)
lemma tendsto_norm {x : α} : tendsto (λg : α, ∥g∥) (𝓝 x) (𝓝 ∥x∥) :=
by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (0:α)) _ _)
lemma tendsto_norm_zero : tendsto (λg : α, ∥g∥) (𝓝 0) (𝓝 0) :=
by simpa using tendsto_norm_sub_self (0:α)
@[continuity]
lemma continuous_norm : continuous (λg:α, ∥g∥) :=
by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:α)))
@[continuity]
lemma continuous_nnnorm : continuous (nnnorm : α → ℝ≥0) :=
continuous_subtype_mk _ continuous_norm
lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : α → ℝ) :=
by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : α)
lemma uniform_continuous_norm : uniform_continuous (norm : α → ℝ) :=
lipschitz_with_one_norm.uniform_continuous
lemma uniform_continuous_nnnorm : uniform_continuous (nnnorm : α → ℝ≥0) :=
uniform_continuous_subtype_mk uniform_continuous_norm _
lemma tendsto_norm_nhds_within_zero : tendsto (norm : α → ℝ) (𝓝[{0}ᶜ] 0) (𝓝[set.Ioi 0] 0) :=
(continuous_norm.tendsto' (0 : α) 0 norm_zero).inf $ tendsto_principal_principal.2 $
λ x, norm_pos_iff.2
section
variables {l : filter γ} {f : γ → α} {a : α}
lemma filter.tendsto.norm {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) :=
tendsto_norm.comp h
lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) :
tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) :=
tendsto.comp continuous_nnnorm.continuous_at h
end
section
variables [topological_space γ] {f : γ → α} {s : set γ} {a : γ} {b : α}
lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h
lemma continuous.nnnorm (h : continuous f) : continuous (λ x, nnnorm (f x)) :=
continuous_nnnorm.comp h
lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm
lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, nnnorm (f x)) a := h.nnnorm
lemma continuous_within_at.norm (h : continuous_within_at f s a) :
continuous_within_at (λ x, ∥f x∥) s a :=
h.norm
lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) :
continuous_within_at (λ x, nnnorm (f x)) s a :=
h.nnnorm
lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s :=
λ x hx, (h x hx).norm
lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, nnnorm (f x)) s :=
λ x hx, (h x hx).nnnorm
end
/-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/
lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α}
(h : tendsto (λ y, ∥f y∥) l at_top) (x : α) :
∀ᶠ y in l, f y ≠ x :=
begin
have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)),
refine this.mono (λ y hy hxy, _),
subst x,
exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy)
end
/-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly
continuous. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_uniform_group : uniform_add_group α :=
⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩
@[priority 100] -- see Note [lower instance priority]
instance normed_top_monoid : has_continuous_add α :=
by apply_instance -- short-circuit type class inference
@[priority 100] -- see Note [lower instance priority]
instance normed_top_group : topological_add_group α :=
by apply_instance -- short-circuit type class inference
lemma nat.norm_cast_le [has_one α] : ∀ n : ℕ, ∥(n : α)∥ ≤ n * ∥(1 : α)∥
| 0 := by simp
| (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul],
exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl }
end normed_group
section normed_ring
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A normed commutative ring is a commutative ring endowed with a norm which satisfies
the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_comm_ring (α : Type*) extends normed_ring α :=
(mul_comm : ∀ x y : α, x * y = y * x)
/-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this
axiom. -/
class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop :=
(norm_one : ∥(1:α)∥ = 1)
export norm_one_class (norm_one)
attribute [simp] norm_one
@[simp] lemma nnnorm_one [normed_group α] [has_one α] [norm_one_class α] : nnnorm (1:α) = 1 :=
nnreal.eq norm_one
@[priority 100] -- see Note [lower instance priority]
instance normed_comm_ring.to_comm_ring [β : normed_comm_ring α] : comm_ring α := { ..β }
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α]
[normed_group β] [has_one β] [norm_one_class β] :
norm_one_class (α × β) :=
⟨by simp [prod.norm_def]⟩
variables [normed_ring α]
lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod
| [] h := (h rfl).elim
| [a] _ := by simp
| (a :: b :: l) _ :=
begin
rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥],
refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)),
exact list.norm_prod_le' (list.cons_ne_nil b l)
end
lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod
| [] := by simp
| (a::l) := list.norm_prod_le' (list.cons_ne_nil a l)
lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
have : l.map f ≠ [], by simpa using hs,
simpa using list.norm_prod_le' this
end
lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
simpa using (l.map f).norm_prod_le
end
/-- If `α` is a normed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/
lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul_le a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
/-- If `α` is a normed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/
lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n
| 0 := by simp
| (n+1) := norm_pow_le' a n.zero_lt_succ
lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n :=
eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩
lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ :=
norm_pos_iff.mpr (units.ne_zero x)
/-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/
lemma mul_left_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ :=
norm_mul_le x
/-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/
lemma mul_right_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ :=
λ y, by {rw mul_comm, convert norm_mul_le y x}
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.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_le (x.1) (y.1)) (norm_mul_le (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.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance normed_ring_top_monoid [normed_ring α] : has_continuous_mul α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
begin
have : ∀ e : α × α, ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥,
{ intro e,
calc ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2∥ :
by rw [mul_sub, sub_mul, sub_add_sub_cancel]
... ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥ :
norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) },
refine squeeze_zero (λ e, norm_nonneg _) this _,
convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub
tendsto_const_nhds).norm).add
(((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _),
show tendsto _ _ _, from tendsto_const_nhds,
simp
end ⟩
/-- A normed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply tendsto_norm_sub_self ⟩
/-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/
class normed_field (α : Type*) extends has_norm α, field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A nondiscrete normed field is a normed field in which there is an element of norm different from
`0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication
by the powers of any element, and thus to relate algebra and topology. -/
class nondiscrete_normed_field (α : Type*) extends normed_field α :=
(non_trivial : ∃x:α, 1<∥x∥)
namespace normed_field
section normed_field
variables [normed_field α]
@[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
normed_field.norm_mul' a b
@[priority 100] -- see Note [lower instance priority]
instance to_normed_comm_ring : normed_comm_ring α :=
{ norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› }
@[priority 900]
instance to_norm_one_class : norm_one_class α :=
⟨mul_left_cancel' (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $
by rw [← norm_mul, mul_one, mul_one]⟩
@[simp] lemma nnnorm_mul (a b : α) : nnnorm (a * b) = nnnorm a * nnnorm b :=
nnreal.eq $ norm_mul a b
/-- `norm` as a `monoid_hom`. -/
@[simps] def norm_hom : monoid_with_zero_hom α ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩
/-- `nnnorm` as a `monoid_hom`. -/
@[simps] def nnnorm_hom : monoid_with_zero_hom α ℝ≥0 :=
⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩
@[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n :=
norm_hom.to_monoid_hom.map_pow a
@[simp] lemma nnnorm_pow (a : α) (n : ℕ) : nnnorm (a ^ n) = nnnorm a ^ n :=
nnnorm_hom.to_monoid_hom.map_pow a n
@[simp] lemma norm_prod (s : finset β) (f : β → α) :
∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ :=
(norm_hom.to_monoid_hom : α →* ℝ).map_prod f s
@[simp] lemma nnnorm_prod (s : finset β) (f : β → α) :
nnnorm (∏ b in s, f b) = ∏ b in s, nnnorm (f b) :=
(nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s
@[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ :=
(norm_hom : monoid_with_zero_hom α ℝ).map_div a b
@[simp] lemma nnnorm_div (a b : α) : nnnorm (a / b) = nnnorm a / nnnorm b :=
(nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_div a b
@[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ :=
(norm_hom : monoid_with_zero_hom α ℝ).map_inv' a
@[simp] lemma nnnorm_inv (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ :=
nnreal.eq $ by simp
@[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n :=
(norm_hom : monoid_with_zero_hom α ℝ).map_fpow
@[simp] lemma nnnorm_fpow : ∀ (a : α) (n : ℤ), nnnorm (a^n) = (nnnorm a)^n :=
(nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_fpow
@[priority 100] -- see Note [lower instance priority]
instance : has_continuous_inv' α :=
begin
refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩,
have r0' : 0 < ∥r∥ := norm_pos_iff.2 r0,
rcases exists_between r0' with ⟨ε, ε0, εr⟩,
have : ∀ᶠ e in 𝓝 r, ∥e⁻¹ - r⁻¹∥ ≤ ∥r - e∥ / ∥r∥ / ε,
{ filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr],
intros e he,
have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he),
calc ∥e⁻¹ - r⁻¹∥ = ∥r - e∥ / ∥r∥ / ∥e∥ : by field_simp [mul_comm]
... ≤ ∥r - e∥ / ∥r∥ / ε :
div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le },
refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _,
refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _,
simp
end
end normed_field
variables (α) [nondiscrete_normed_field α]
lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial
lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 :=
begin
rcases exists_one_lt_norm α with ⟨y, hy⟩,
refine ⟨y⁻¹, _, _⟩,
{ simp only [inv_eq_zero, ne.def, norm_pos_iff],
rintro rfl,
rw norm_zero at hy,
exact lt_asymm zero_lt_one hy },
{ simp [inv_lt_one hy] }
end
lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in
⟨w^n, by rwa norm_pow⟩
lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in
⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _},
by rwa norm_fpow⟩
variable {α}
@[instance]
lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[{x}ᶜ] x) :=
begin
rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff],
rintros ε ε0,
rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩,
refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩,
rwa [dist_comm, dist_eq_norm, add_sub_cancel'],
end
@[instance]
lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) :=
by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α)
end normed_field
instance : normed_field ℝ :=
{ norm_mul' := abs_mul,
.. real.normed_group }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
namespace real
lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x :=
abs_of_nonneg hx
@[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg
@[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp
@[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _)
@[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp
lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : nnnorm x = ⟨x, hx⟩ :=
nnreal.eq $ norm_of_nonneg hx
lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (nnnorm x : ℝ≥0∞) = ennreal.of_real x :=
by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] }
end real
namespace nnreal
open_locale nnreal
@[simp] lemma norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x :=
by rw [real.norm_eq_abs, x.abs_eq]
@[simp] lemma nnnorm_eq (x : ℝ≥0) : nnnorm (x : ℝ) = x :=
nnreal.eq $ real.norm_of_nonneg x.2
end nnreal
@[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
real.norm_of_nonneg (norm_nonneg _)
@[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a :=
by simp only [nnnorm, norm_norm]
/-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/
lemma normed_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [normed_group β]
{f : α → β} {b : β} :
tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ∥f n - b∥ < ε :=
(at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm])
/--
A variant of `normed_group.tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
lemma normed_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_top_order α]
{β : Type*} [normed_group β]
{f : α → β} {b : β} :
tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ∥f n - b∥ < ε :=
(at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm])
instance : normed_comm_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub],
mul_comm := mul_comm }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
instance : norm_one_class ℤ :=
⟨by simp [← int.norm_cast_real]⟩
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
section normed_space
section prio
set_option extends_priority 920
-- Here, we set a rather high priority for the instance `[normed_space α β] : semimodule α β`
-- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better
-- unification properties.
-- see Note[vector space definition] for why we extend `semimodule`.
/-- A normed space over a normed field is a vector space endowed with a norm which satisfies the
equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove
`∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/
class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β]
extends semimodule α β :=
(norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥)
end prio
variables [normed_field α] [normed_group β]
instance normed_field.to_normed_space : normed_space α α :=
{ norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
begin
by_cases h : s = 0,
{ simp [h] },
{ refine le_antisymm (normed_space.norm_smul_le s x) _,
calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h]
... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) :
mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _)
... = ∥s • x∥ :
by rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] }
end
@[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ :=
(abs_eq (norm_nonneg z)).mpr (or.inl rfl)
lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y :=
by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub]
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
lemma nndist_smul [normed_space α β] (s : α) (x y : β) :
nndist (s • x) (s • y) = nnnorm s * nndist x y :=
nnreal.eq $ dist_smul s x y
lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ :=
by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht]
variables {E : Type*} {F : Type*}
[normed_group E] [normed_space α E] [normed_group F] [normed_space α F]
@[priority 100] -- see Note [lower instance priority]
instance normed_space.topological_vector_space : topological_vector_space α E :=
begin
refine { continuous_smul := continuous_iff_continuous_at.2 $
λ p, tendsto_iff_norm_tendsto_zero.2 _ },
refine squeeze_zero (λ _, norm_nonneg _) _ _,
{ exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ },
{ intro q,
rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul],
exact norm_add_le _ _ },
{ conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr,
rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] },
exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul
(continuous_snd.tendsto p).norm).add
(tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) }
end
theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) :
∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε :=
have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0),
from (continuous_const.smul (continuous_id.sub continuous_const)).norm.tendsto' _ _ (by simp),
this.eventually (gt_mem_nhds h)
theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
closure (ball x r) = closed_ball x r :=
begin
refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _),
have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 :=
((continuous_id.smul continuous_const).add continuous_const).continuous_within_at,
convert this.mem_closure _ _,
{ rw [one_smul, sub_add_cancel] },
{ simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] },
{ rintros c ⟨hc0, hc1⟩,
rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs,
abs_of_nonneg hc0, mul_comm, ← mul_one r],
rw [mem_closed_ball, dist_eq_norm] at hy,
apply mul_lt_mul'; assumption }
end
theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (ball x r) = sphere x r :=
begin
rw [frontier, closure_ball x hr, is_open_ball.interior_eq],
ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm
end
theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
interior (closed_ball x r) = ball x r :=
begin
refine set.subset.antisymm _ ball_subset_interior_closed_ball,
intros y hy,
rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr },
set f : ℝ → E := λ c : ℝ, c • (y - x) + x,
suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1,
{ have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const,
have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f],
have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) :=
interior_mono this (preimage_interior_subset_interior_preimage hfc hf1),
contrapose h1,
simp },
intros c hc,
rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr],
simpa [f, dist_eq_norm, norm_smul] using hc
end
theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
interior (closed_ball x r) = ball x r :=
begin
rcases lt_trichotomy r 0 with hr|rfl|hr,
{ simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] },
{ suffices : x ∉ interior {x},
{ rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff],
intros y hy,
obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy),
exact this hy },
rw [← set.mem_compl_iff, ← closure_compl],
rcases exists_ne (0 : E) with ⟨z, hz⟩,
suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E),
by simpa only [zero_smul, add_zero] using this,
have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi],
refine (continuous_const.add (continuous_id.smul
continuous_const)).continuous_within_at.mem_closure this _,
intros c hc,
simp [smul_eq_zero, hz, ne_of_gt hc] },
{ exact interior_closed_ball x hr }
end
theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball x hr,
closed_ball_diff_ball]
theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball]
variables (α)
lemma ne_neg_of_mem_sphere [char_zero α] {r : ℝ} (hr : 0 < r) (x : sphere (0:E) r) : x ≠ - x :=
λ h, nonzero_of_mem_sphere hr x (eq_zero_of_eq_neg α (by { conv_lhs {rw h}, simp }))
lemma ne_neg_of_mem_unit_sphere [char_zero α] (x : sphere (0:E) 1) : x ≠ - x :=
ne_neg_of_mem_sphere α (by norm_num) x
variables {α}
open normed_field
/-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to
any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows
up in applications. -/
lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) :
∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) :=
begin
have xεpos : 0 < ∥x∥/ε := div_pos (norm_pos_iff.2 hx) εpos,
rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩,
have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc,
have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 },
refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩,
show (c ^ (n + 1))⁻¹ ≠ 0,
by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff],
show ∥(c ^ (n + 1))⁻¹ • x∥ < ε,
{ rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow],
exact (div_lt_iff εpos).1 (hn.2) },
show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥,
{ rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos),
fpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos),
one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm],
exact (le_div_iff εpos).1 hn.1 },
show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥,
{ have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring,
rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul],
exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) }
end
/-- The product of two normed spaces is a normed space, with the sup norm. -/
instance : normed_space α (E × F) :=
{ norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg],
-- TODO: without the next two lines Lean unfolds `≤` to `real.le`
add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _),
smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _),
..prod.normed_group,
..prod.semimodule }
/-- The product of finitely many normed spaces is a normed space, with the sup norm. -/
instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)]
[∀i, normed_space α (E i)] : normed_space α (Πi, E i) :=
{ norm_smul_le := λ a f, le_of_eq $
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] }
/-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/
instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s :=
{ norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) }
end normed_space
section normed_algebra
/-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of
`𝕜` in `𝕜'` is an isometry. -/
class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
extends algebra 𝕜 𝕜' :=
(norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥)
@[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ :=
normed_algebra.norm_algebra_map_eq _
variables (𝕜 : Type*) [normed_field 𝕜]
variables (𝕜' : Type*) [normed_ring 𝕜']
@[priority 100]
instance normed_algebra.to_normed_space [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' :=
{ norm_smul_le := λ s x, calc
∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl }
... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _
... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq,
..h }
instance normed_algebra.id : normed_algebra 𝕜 𝕜 :=
{ norm_algebra_map_eq := by simp,
.. algebra.id 𝕜}
variables (𝕜') [normed_algebra 𝕜 𝕜']
include 𝕜
lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 :=
by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜))
lemma normed_algebra.norm_one_class : norm_one_class 𝕜' :=
⟨normed_algebra.norm_one 𝕜 𝕜'⟩
lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 :=
begin
refine (norm_pos_iff.mp _).symm,
rw normed_algebra.norm_one 𝕜 𝕜', norm_num,
end
lemma normed_algebra.nontrivial : nontrivial 𝕜' :=
⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜 𝕜'⟩⟩
end normed_algebra
section restrict_scalars
variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
(E : Type*) [normed_group E] [normed_space 𝕜' E]
/-- Warning: This declaration should be used judiciously.
Please consider using `is_scalar_tower` instead.
`𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a
normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred.
The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default.
-/
def normed_space.restrict_scalars : normed_space 𝕜 E :=
{ norm_smul_le := λc x, le_of_eq $ begin
change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥,
simp [norm_smul]
end,
..restrict_scalars.semimodule 𝕜 𝕜' E }
instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] :
normed_group (restrict_scalars 𝕜 𝕜' E) := I
instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*}
[normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] :
normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I
instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) :=
(normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E)
end restrict_scalars
section summable
open_locale classical
open finset filter
variables [normed_group α] [normed_group β]
lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} :
cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔
∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
begin
rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff],
{ simp only [ball_0_eq, set.mem_set_of_eq] },
{ rintros s t hst ⟨s', hs'⟩,
exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ }
end
lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} :
summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm]
lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) :=
cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε,
let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in
⟨s, assume t ht,
have ∥∑ i in t, g i∥ < ε := hs t ht,
have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)),
lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $
by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩
lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) :
cauchy_seq (λ s : finset ι, ∑ a in s, f a) :=
cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _)
/-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space
its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable
with sum `a`. -/
lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥))
{s : γ → finset ι} {p : filter γ} [ne_bot p]
(hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) :
has_sum f a :=
tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha
lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
⟨λ h, h.tendsto_sum_nat,
λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩
/-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g`
which is summable, then `f` is summable. -/
lemma summable_of_norm_bounded
[complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) :
summable f :=
by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h }
lemma has_sum.norm_le_of_bounded {f : ι → α} {g : ι → ℝ} {a : α} {b : ℝ}
(hf : has_sum f a) (hg : has_sum g b) (h : ∀ i, ∥f i∥ ≤ g i) :
∥a∥ ≤ b :=
le_of_tendsto_of_tendsto' hf.norm hg $ λ s, norm_sum_le_of_le _ $ λ i hi, h i
/-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is
summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not
assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a)
(h : ∀ i, ∥f i∥ ≤ g i) :
∥∑' i : ι, f i∥ ≤ a :=
begin
by_cases hf : summable f,
{ exact hf.has_sum.norm_le_of_bounded hg h },
{ rw [tsum_eq_zero_of_not_summable hf, norm_zero],
exact ge_of_tendsto' hg (λ s, sum_nonneg $ λ i hi, (norm_nonneg _).trans (h i)) }
end
/-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume
that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) :
∥∑'i, f i∥ ≤ ∑' i, ∥f i∥ :=
tsum_of_norm_bounded hf.has_sum $ λ i, le_rfl
variable [complete_space α]
/-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a
real function `g` which is summable, then `f` is summable. -/
lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f :=
begin
replace h := mem_cofinite.1 h,
refine h.summable_compl_iff.mp _,
refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _,
rintros ⟨a, h'⟩,
simpa using h'
end
lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → ℝ≥0) (hg : summable g)
(h : ∀i, nnnorm (f i) ≤ g i) : summable f :=
summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i)
lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f :=
summable_of_norm_bounded _ hf (assume i, le_refl _)
lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f :=
summable_of_nnnorm_bounded _ hf (assume i, le_refl _)
end summable
|
aad8e059c049261989fb23890e0373eee6cf0b09 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/sequences.lean | cb0fcc7e0f7eb6df3fdbfceb557071d63c30770d | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 10,521 | lean | /-
Copyright (c) 2018 Jan-David Salchow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow
Sequences in topological spaces.
In this file we define sequences in topological spaces and show how they are related to
filters and the topology. In particular, we
* associate a filter with a sequence and prove equivalence of convergence of the two,
* define the sequential closure of a set and prove that it's contained in the closure,
* define a type class "sequential_space" in which closure and sequential closure agree,
* define sequential continuity and show that it coincides with continuity in sequential spaces,
* provide an instance that shows that every metric space is a sequential space.
TODO:
* There should be an instance that associates a sequential space with a first countable space.
* Sequential compactness should be handled here.
-/
import topology.basic topology.metric_space.basic
import analysis.specific_limits
open set filter
variables {α : Type*} {β : Type*}
local notation f `⟶` limit := tendsto f at_top (nhds limit)
/- Statements about sequences in general topological spaces. -/
section topological_space
variables [topological_space α] [topological_space β]
/-- A sequence converges in the sence of topological spaces iff the associated statement for filter
holds. -/
lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} :
tendsto x at_top (nhds limit) ↔
∀ U : set α, limit ∈ U → is_open U → ∃ n0 : ℕ, ∀ n ≥ n0, (x n) ∈ U :=
iff.intro
(assume ttol : tendsto x at_top (nhds limit),
show ∀ U : set α, limit ∈ U → is_open U → ∃ n0 : ℕ, ∀ n ≥ n0, (x n) ∈ U, from
assume U limitInU isOpenU,
have {n | (x n) ∈ U} ∈ at_top :=
mem_map.mp $ le_def.mp ttol U $ mem_nhds_sets isOpenU limitInU,
show ∃ n0 : ℕ, ∀ n ≥ n0, (x n) ∈ U, from mem_at_top_sets.mp this)
(assume xtol : ∀ U : set α, limit ∈ U → is_open U → ∃ n0 : ℕ, ∀ n ≥ n0, (x n) ∈ U,
suffices ∀ U, is_open U → limit ∈ U → x ⁻¹' U ∈ at_top,
from tendsto_nhds.mpr this,
assume U isOpenU limitInU,
suffices ∃ n0 : ℕ, ∀ n ≥ n0, (x n) ∈ U, by simp [this],
xtol U limitInU isOpenU)
/-- The sequential closure of a subset M ⊆ α of a topological space α is
the set of all p ∈ α which arise as limit of sequences in M. -/
def sequential_closure (M : set α) : set α :=
{p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)}
lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M :=
assume p (_ : p ∈ M), show p ∈ sequential_closure M, from
⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩
def is_seq_closed (A : set α) : Prop := A = sequential_closure A
/-- A convenience lemma for showing that a set is sequentially closed. -/
lemma is_seq_closed_of_def {A : set α}
(h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A :=
show A = sequential_closure A, from subset.antisymm
(subset_sequential_closure A)
(show ∀ p, p ∈ sequential_closure A → p ∈ A, from
(assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›))
/-- The sequential closure of a set is contained in the closure of that set.
The converse is not true. -/
lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M :=
show ∀ p, p ∈ sequential_closure M → p ∈ closure M, from
assume p,
assume : ∃ x : ℕ → α, (∀ n : ℕ, ((x n) ∈ M)) ∧ (x ⟶ p),
let ⟨x, ⟨_, _⟩⟩ := this in
show p ∈ closure M, from
-- we have to show that p is in the closure of M
-- using mem_closure_iff, this is equivalent to proving that every open neighbourhood
-- has nonempty intersection with M, but this is witnessed by our sequence x
suffices ∀ O, is_open O → p ∈ O → O ∩ M ≠ ∅, from mem_closure_iff.mpr this,
have ∀ (U : set α), p ∈ U → is_open U → (∃ n0, ∀ n, n ≥ n0 → x n ∈ U), by rwa[←topological_space.seq_tendsto_iff],
assume O is_open_O p_in_O,
let ⟨n0, _⟩ := this O ‹p ∈ O› ‹is_open O› in
have (x n0) ∈ O, from ‹∀ n ≥ n0, x n ∈ O› n0 (show n0 ≥ n0, from le_refl n0),
have (x n0) ∈ O ∩ M, from ⟨this, ‹∀n, x n ∈ M› n0⟩,
set.ne_empty_of_mem this
/-- A set is sequentially closed if it is closed. -/
lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M :=
suffices sequential_closure M ⊆ M, from
set.eq_of_subset_of_subset (subset_sequential_closure M) this,
calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M
... = M : closure_eq_of_is_closed ‹is_closed M›
/-- The limit of a convergent sequence in a sequentially closed set is in that set.-/
lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α}
(_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A :=
have limit ∈ sequential_closure A, from
show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩,
eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A›
/-- The limit of a convergent sequence in a closed set is in that set.-/
lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α}
(_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A :=
mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)›
/-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be
formalised by demanding that the sequential closure and the closure coincide. The following
statements show that other topological properties can be deduced from sequences in sequential
spaces. -/
class sequential_space (α : Type*) [topological_space α] : Prop :=
(sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M)
/-- In a sequential space, a set is closed iff it's sequentially closed. -/
lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} :
is_seq_closed M ↔ is_closed M :=
iff.intro
(assume _, closure_eq_iff_is_closed.mp (eq.symm
(calc M = sequential_closure M : by assumption
... = closure M : sequential_space.sequential_closure_eq_closure M)))
(is_seq_closed_of_is_closed M)
/-- A function between topological spaces is sequentially continuous if it commutes with limit of
convergent sequences. -/
def sequentially_continuous (f : α → β) : Prop :=
∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit)
/- A continuous function is sequentially continuous. -/
lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) :
sequentially_continuous f :=
assume x limit (_ : x ⟶ limit),
have tendsto f (nhds limit) (nhds (f limit)), from continuous.tendsto ‹continuous f› limit,
show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)›
/-- In a sequential space, continuity and sequential continuity coincide. -/
lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] :
continuous f ↔ sequentially_continuous f :=
iff.intro
(assume _, ‹continuous f›.to_sequentially_continuous)
(assume : sequentially_continuous f, show continuous f, from
suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from
continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›),
assume A (_ : is_closed A),
is_seq_closed_of_def $
assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p),
have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›,
show f p ∈ A, from
mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›)
end topological_space
/- Statements about sequences in metric spaces -/
namespace metric
variable [metric_space α]
variables {ε : ℝ}
-- necessary for the next instance
set_option eqn_compiler.zeta true
/-- Show that every metric space is sequential. -/
instance : sequential_space α :=
⟨show ∀ M, sequential_closure M = closure M, from assume M,
suffices closure M ⊆ sequential_closure M,
from set.subset.antisymm (sequential_closure_subset_closure M) this,
assume (p : α) (_ : p ∈ closure M),
-- we construct a sequence in α, with values in M, that converges to p
-- the first step is to use (p ∈ closure M) ↔ "all nhds of p contain elements of M" on metric
-- balls
have ∀ n : ℕ, ball p ((1:ℝ)/((n+1):ℝ)) ∩ M ≠ ∅ := assume n : ℕ,
mem_closure_iff.mp ‹p ∈ (closure M)› (ball p ((1:ℝ)/((n+1):ℝ))) (is_open_ball)
(mem_ball_self $ one_div_pos_of_pos $ add_pos_of_nonneg_of_pos (nat.cast_nonneg n) zero_lt_one),
-- from this, construct a "sequence of hypothesis" h, (h n) := _ ∈ {x // x ∈ ball (1/n+1) p ∩ M}
let h := λ n : ℕ, (classical.indefinite_description _ (set.exists_mem_of_ne_empty (this n))),
-- and the actual sequence
x := λ n : ℕ, (h n).val in
-- now we construct the promised sequence and show the claim
show ∃ x : ℕ → α, (∀ n : ℕ, ((x n) ∈ M)) ∧ (x ⟶ p), from
⟨x, assume n,
have (x n) ∈ ball p ((1:ℝ)/((n+1):ℝ)) ∩ M := (h n).property, this.2,
suffices ∀ ε > 0, ∃ n0 : ℕ, ∀ n ≥ n0, dist (x n) p < ε,
by simpa only [metric.tendsto_at_top],
assume ε _,
-- we apply that 1/n converges to zero to the fact that (x n) ∈ ball p ε
have ∀ ε > 0, ∃ n0 : ℕ, ∀ n ≥ n0, dist (1 / (↑n + 1)) (0:ℝ) < ε :=
metric.tendsto_at_top.mp tendsto_one_div_add_at_top_nhds_0_nat,
let ⟨n0, hn0⟩ := this ε ‹ε > 0› in
show ∃ n0 : ℕ, ∀ n ≥ n0, dist (x n) p < ε, from
⟨n0, assume n ngtn0,
calc dist (x n) p < (1:ℝ)/↑(n+1) : (h n).property.1
... = abs ((1:ℝ)/↑(n+1)) :
eq.symm $ abs_of_nonneg $ div_nonneg' zero_le_one $ nat.cast_nonneg _
... = abs ((1:ℝ)/↑(n+1) - 0) : by simp
... = dist ((1:ℝ)/↑(n+1)) 0 : eq.symm $ real.dist_eq ((1:ℝ)/↑(n+1)) 0
... < ε : hn0 n ‹n ≥ n0›⟩⟩⟩
set_option eqn_compiler.zeta false
end metric
|
07fc0e8490e15520c7d3ecedd223738e383b8d66 | 8f209eb34c0c4b9b6be5e518ebfc767a38bed79c | /code/src/internal/Ant/main.lean | 3d76326a219bdc58bc4ab6aa22370f2dccdaf340 | [] | no_license | hediet/masters-thesis | 13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5 | dc40c14cc4ed073673615412f36b4e386ee7aac9 | refs/heads/master | 1,680,591,056,302 | 1,617,710,887,000 | 1,617,710,887,000 | 311,762,038 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 54 | lean | import .eval
import .implies
import .map
import .rhss
|
05bcfd9fcb7dbce00a74dadad4d05937bafa9080 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/polynomial/content.lean | c7e32b7fb268cda9802092d41156d1735209997a | [
"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 | 17,143 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import algebra.gcd_monoid.finset
import data.polynomial.field_division
import data.polynomial.erase_lead
import data.polynomial.cancel_leads
/-!
# GCD structures on polynomials
Definitions and basic results about polynomials over GCD domains, particularly their contents
and primitive polynomials.
## Main Definitions
Let `p : polynomial R`.
- `p.content` is the `gcd` of the coefficients of `p`.
- `p.is_primitive` indicates that `p.content = 1`.
## Main Results
- `polynomial.content_mul`:
If `p q : polynomial R`, then `(p * q).content = p.content * q.content`.
- `polynomial.normalized_gcd_monoid`:
The polynomial ring of a GCD domain is itself a GCD domain.
-/
namespace polynomial
section primitive
variables {R : Type*} [comm_semiring R]
/-- A polynomial is primitive when the only constant polynomials dividing it are units -/
def is_primitive (p : polynomial R) : Prop :=
∀ (r : R), C r ∣ p → is_unit r
lemma is_primitive_iff_is_unit_of_C_dvd {p : polynomial R} :
p.is_primitive ↔ ∀ (r : R), C r ∣ p → is_unit r :=
iff.rfl
@[simp]
lemma is_primitive_one : is_primitive (1 : polynomial R) :=
λ r h, is_unit_C.mp (is_unit_of_dvd_one (C r) h)
lemma monic.is_primitive {p : polynomial R} (hp : p.monic) : p.is_primitive :=
begin
rintros r ⟨q, h⟩,
exact is_unit_of_mul_eq_one r (q.coeff p.nat_degree) (by rwa [←coeff_C_mul, ←h]),
end
lemma is_primitive.ne_zero [nontrivial R] {p : polynomial R} (hp : p.is_primitive) : p ≠ 0 :=
begin
rintro rfl,
exact (hp 0 (dvd_zero (C 0))).ne_zero rfl,
end
end primitive
variables {R : Type*} [comm_ring R] [integral_domain R]
section normalized_gcd_monoid
variable [normalized_gcd_monoid R]
/-- `p.content` is the `gcd` of the coefficients of `p`. -/
def content (p : polynomial R) : R := (p.support).gcd p.coeff
lemma content_dvd_coeff {p : polynomial R} (n : ℕ) : p.content ∣ p.coeff n :=
begin
by_cases h : n ∈ p.support,
{ apply finset.gcd_dvd h },
rw [mem_support_iff, not_not] at h,
rw h,
apply dvd_zero,
end
@[simp] lemma content_C {r : R} : (C r).content = normalize r :=
begin
rw content,
by_cases h0 : r = 0,
{ simp [h0] },
have h : (C r).support = {0} := support_monomial _ _ h0,
simp [h],
end
@[simp] lemma content_zero : content (0 : polynomial R) = 0 :=
by rw [← C_0, content_C, normalize_zero]
@[simp] lemma content_one : content (1 : polynomial R) = 1 :=
by rw [← C_1, content_C, normalize_one]
lemma content_X_mul {p : polynomial R} : content (X * p) = content p :=
begin
rw [content, content, finset.gcd_def, finset.gcd_def],
refine congr rfl _,
have h : (X * p).support = p.support.map ⟨nat.succ, nat.succ_injective⟩,
{ ext a,
simp only [exists_prop, finset.mem_map, function.embedding.coe_fn_mk, ne.def,
mem_support_iff],
cases a,
{ simp [coeff_X_mul_zero, nat.succ_ne_zero] },
rw [mul_comm, coeff_mul_X],
split,
{ intro h,
use a,
simp [h] },
{ rintros ⟨b, ⟨h1, h2⟩⟩,
rw ← nat.succ_injective h2,
apply h1 } },
rw h,
simp only [finset.map_val, function.comp_app, function.embedding.coe_fn_mk, multiset.map_map],
refine congr (congr rfl _) rfl,
ext a,
rw mul_comm,
simp [coeff_mul_X],
end
@[simp] lemma content_X_pow {k : ℕ} : content ((X : polynomial R) ^ k) = 1 :=
begin
induction k with k hi,
{ simp },
rw [pow_succ, content_X_mul, hi]
end
@[simp] lemma content_X : content (X : polynomial R) = 1 :=
by { rw [← mul_one X, content_X_mul, content_one] }
lemma content_C_mul (r : R) (p : polynomial R) : (C r * p).content = normalize r * p.content :=
begin
by_cases h0 : r = 0, { simp [h0] },
rw content, rw content, rw ← finset.gcd_mul_left,
refine congr (congr rfl _) _; ext; simp [h0, mem_support_iff]
end
@[simp] lemma content_monomial {r : R} {k : ℕ} : content (monomial k r) = normalize r :=
by { rw [monomial_eq_C_mul_X, content_C_mul, content_X_pow, mul_one] }
lemma content_eq_zero_iff {p : polynomial R} : content p = 0 ↔ p = 0 :=
begin
rw [content, finset.gcd_eq_zero_iff],
split; intro h,
{ ext n,
by_cases h0 : n ∈ p.support,
{ rw [h n h0, coeff_zero], },
{ rw mem_support_iff at h0,
push_neg at h0,
simp [h0] } },
{ intros x h0,
simp [h] }
end
@[simp] lemma normalize_content {p : polynomial R} : normalize p.content = p.content :=
finset.normalize_gcd
lemma content_eq_gcd_range_of_lt (p : polynomial R) (n : ℕ) (h : p.nat_degree < n) :
p.content = (finset.range n).gcd p.coeff :=
begin
apply dvd_antisymm_of_normalize_eq normalize_content finset.normalize_gcd,
{ rw finset.dvd_gcd_iff,
intros i hi,
apply content_dvd_coeff _ },
{ apply finset.gcd_mono,
intro i,
simp only [nat.lt_succ_iff, mem_support_iff, ne.def, finset.mem_range],
contrapose!,
intro h1,
apply coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le h h1), }
end
lemma content_eq_gcd_range_succ (p : polynomial R) :
p.content = (finset.range p.nat_degree.succ).gcd p.coeff :=
content_eq_gcd_range_of_lt _ _ (nat.lt_succ_self _)
lemma content_eq_gcd_leading_coeff_content_erase_lead (p : polynomial R) :
p.content = gcd_monoid.gcd p.leading_coeff (erase_lead p).content :=
begin
by_cases h : p = 0,
{ simp [h] },
rw [← leading_coeff_eq_zero, leading_coeff, ← ne.def, ← mem_support_iff] at h,
rw [content, ← finset.insert_erase h, finset.gcd_insert, leading_coeff, content,
erase_lead_support],
refine congr rfl (finset.gcd_congr rfl (λ i hi, _)),
rw finset.mem_erase at hi,
rw [erase_lead_coeff, if_neg hi.1],
end
lemma dvd_content_iff_C_dvd {p : polynomial R} {r : R} : r ∣ p.content ↔ C r ∣ p :=
begin
rw C_dvd_iff_dvd_coeff,
split,
{ intros h i,
apply h.trans (content_dvd_coeff _) },
{ intro h,
rw [content, finset.dvd_gcd_iff],
intros i hi,
apply h i }
end
lemma C_content_dvd (p : polynomial R) : C p.content ∣ p :=
dvd_content_iff_C_dvd.1 dvd_rfl
lemma is_primitive_iff_content_eq_one {p : polynomial R} : p.is_primitive ↔ p.content = 1 :=
begin
rw [←normalize_content, normalize_eq_one, is_primitive],
simp_rw [←dvd_content_iff_C_dvd],
exact ⟨λ h, h p.content (dvd_refl p.content), λ h r hdvd, is_unit_of_dvd_unit hdvd h⟩,
end
lemma is_primitive.content_eq_one {p : polynomial R} (hp : p.is_primitive) : p.content = 1 :=
is_primitive_iff_content_eq_one.mp hp
open_locale classical
noncomputable theory
section prim_part
/-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by
`p.content`. If `p = 0`, then `p.prim_part = 1`. -/
def prim_part (p : polynomial R) : polynomial R :=
if p = 0 then 1 else classical.some (C_content_dvd p)
lemma eq_C_content_mul_prim_part (p : polynomial R) : p = C p.content * p.prim_part :=
begin
by_cases h : p = 0, { simp [h] },
rw [prim_part, if_neg h, ← classical.some_spec (C_content_dvd p)],
end
@[simp]
lemma prim_part_zero : prim_part (0 : polynomial R) = 1 := if_pos rfl
lemma is_primitive_prim_part (p : polynomial R) : p.prim_part.is_primitive :=
begin
by_cases h : p = 0, { simp [h] },
rw ← content_eq_zero_iff at h,
rw is_primitive_iff_content_eq_one,
apply mul_left_cancel₀ h,
conv_rhs { rw [p.eq_C_content_mul_prim_part, mul_one, content_C_mul, normalize_content] }
end
lemma content_prim_part (p : polynomial R) : p.prim_part.content = 1 :=
p.is_primitive_prim_part.content_eq_one
lemma prim_part_ne_zero (p : polynomial R) : p.prim_part ≠ 0 := p.is_primitive_prim_part.ne_zero
lemma nat_degree_prim_part (p : polynomial R) : p.prim_part.nat_degree = p.nat_degree :=
begin
by_cases h : C p.content = 0,
{ rw [C_eq_zero, content_eq_zero_iff] at h, simp [h] },
conv_rhs { rw [p.eq_C_content_mul_prim_part,
nat_degree_mul h p.prim_part_ne_zero, nat_degree_C, zero_add] },
end
@[simp]
lemma is_primitive.prim_part_eq {p : polynomial R} (hp : p.is_primitive) : p.prim_part = p :=
by rw [← one_mul p.prim_part, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_prim_part]
lemma is_unit_prim_part_C (r : R) : is_unit (C r).prim_part :=
begin
by_cases h0 : r = 0,
{ simp [h0] },
unfold is_unit,
refine ⟨⟨C ↑(norm_unit r)⁻¹, C ↑(norm_unit r),
by rw [← ring_hom.map_mul, units.inv_mul, C_1],
by rw [← ring_hom.map_mul, units.mul_inv, C_1]⟩, _⟩,
rw [← normalize_eq_zero, ← C_eq_zero] at h0,
apply mul_left_cancel₀ h0,
conv_rhs { rw [← content_C, ← (C r).eq_C_content_mul_prim_part], },
simp only [units.coe_mk, normalize_apply, ring_hom.map_mul],
rw [mul_assoc, ← ring_hom.map_mul, units.mul_inv, C_1, mul_one],
end
lemma prim_part_dvd (p : polynomial R) : p.prim_part ∣ p :=
dvd.intro_left (C p.content) p.eq_C_content_mul_prim_part.symm
end prim_part
lemma gcd_content_eq_of_dvd_sub {a : R} {p q : polynomial R} (h : C a ∣ p - q) :
gcd_monoid.gcd a p.content = gcd_monoid.gcd a q.content :=
begin
rw content_eq_gcd_range_of_lt p (max p.nat_degree q.nat_degree).succ
(lt_of_le_of_lt (le_max_left _ _) (nat.lt_succ_self _)),
rw content_eq_gcd_range_of_lt q (max p.nat_degree q.nat_degree).succ
(lt_of_le_of_lt (le_max_right _ _) (nat.lt_succ_self _)),
apply finset.gcd_eq_of_dvd_sub,
intros x hx,
cases h with w hw,
use w.coeff x,
rw [← coeff_sub, hw, coeff_C_mul]
end
lemma content_mul_aux {p q : polynomial R} :
gcd_monoid.gcd (p * q).erase_lead.content p.leading_coeff =
gcd_monoid.gcd (p.erase_lead * q).content p.leading_coeff :=
begin
rw [gcd_comm (content _) _, gcd_comm (content _) _],
apply gcd_content_eq_of_dvd_sub,
rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add,
sub_sub_cancel, leading_coeff_mul, ring_hom.map_mul, mul_assoc, mul_assoc],
apply dvd_sub (dvd.intro _ rfl) (dvd.intro _ rfl),
end
@[simp]
theorem content_mul {p q : polynomial R} : (p * q).content = p.content * q.content :=
begin
classical,
suffices h : ∀ (n : ℕ) (p q : polynomial R), ((p * q).degree < n) →
(p * q).content = p.content * q.content,
{ apply h,
apply (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_succ_self _))) },
intro n,
induction n with n ih,
{ intros p q hpq,
rw [with_bot.coe_zero, nat.with_bot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq,
rcases hpq with rfl | rfl; simp },
intros p q hpq,
by_cases p0 : p = 0, { simp [p0] },
by_cases q0 : q = 0, { simp [q0] },
rw [degree_eq_nat_degree (mul_ne_zero p0 q0), with_bot.coe_lt_coe, nat.lt_succ_iff_lt_or_eq,
← with_bot.coe_lt_coe, ← degree_eq_nat_degree (mul_ne_zero p0 q0), nat_degree_mul p0 q0] at hpq,
rcases hpq with hlt | heq, { apply ih _ _ hlt },
rw [← p.nat_degree_prim_part, ← q.nat_degree_prim_part, ← with_bot.coe_eq_coe, with_bot.coe_add,
← degree_eq_nat_degree p.prim_part_ne_zero, ← degree_eq_nat_degree q.prim_part_ne_zero] at heq,
rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part],
suffices h : (q.prim_part * p.prim_part).content = 1,
{ rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.prim_part, mul_assoc, content_C_mul,
content_C_mul, h, mul_one, content_prim_part, content_prim_part, mul_one, mul_one] },
rw [← normalize_content, normalize_eq_one, is_unit_iff_dvd_one,
content_eq_gcd_leading_coeff_content_erase_lead, leading_coeff_mul, gcd_comm],
apply (gcd_mul_dvd_mul_gcd _ _ _).trans,
rw [content_mul_aux, ih, content_prim_part, mul_one, gcd_comm,
← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part, one_mul,
mul_comm q.prim_part, content_mul_aux, ih, content_prim_part, mul_one, gcd_comm,
← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part],
{ rw [← heq, degree_mul, with_bot.add_lt_add_iff_right],
{ apply degree_erase_lt p.prim_part_ne_zero },
{ rw [ne.def, degree_eq_bot],
apply q.prim_part_ne_zero } },
{ rw [mul_comm, ← heq, degree_mul, with_bot.add_lt_add_iff_left],
{ apply degree_erase_lt q.prim_part_ne_zero },
{ rw [ne.def, degree_eq_bot],
apply p.prim_part_ne_zero } }
end
theorem is_primitive.mul {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) :
(p * q).is_primitive :=
by rw [is_primitive_iff_content_eq_one, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one]
@[simp]
theorem prim_part_mul {p q : polynomial R} (h0 : p * q ≠ 0) :
(p * q).prim_part = p.prim_part * q.prim_part :=
begin
rw [ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0,
apply mul_left_cancel₀ h0,
conv_lhs { rw [← (p * q).eq_C_content_mul_prim_part,
p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part] },
rw [content_mul, ring_hom.map_mul],
ring,
end
lemma is_primitive.is_primitive_of_dvd {p q : polynomial R} (hp : p.is_primitive) (hdvd : q ∣ p) :
q.is_primitive :=
begin
rcases hdvd with ⟨r, rfl⟩,
rw [is_primitive_iff_content_eq_one, ← normalize_content, normalize_eq_one, is_unit_iff_dvd_one],
apply dvd.intro r.content,
rwa [is_primitive_iff_content_eq_one, content_mul] at hp,
end
lemma is_primitive.dvd_prim_part_iff_dvd {p q : polynomial R}
(hp : p.is_primitive) (hq : q ≠ 0) :
p ∣ q.prim_part ↔ p ∣ q :=
begin
refine ⟨λ h, h.trans (dvd.intro_left _ q.eq_C_content_mul_prim_part.symm), λ h, _⟩,
rcases h with ⟨r, rfl⟩,
apply dvd.intro _,
rw [prim_part_mul hq, hp.prim_part_eq],
end
theorem exists_primitive_lcm_of_is_primitive {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive) :
∃ r : polynomial R, r.is_primitive ∧ (∀ s : polynomial R, p ∣ s ∧ q ∣ s ↔ r ∣ s) :=
begin
classical,
have h : ∃ (n : ℕ) (r : polynomial R), r.nat_degree = n ∧ r.is_primitive ∧ p ∣ r ∧ q ∣ r :=
⟨(p * q).nat_degree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩,
rcases nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩,
refine ⟨r, rprim, λ s, ⟨_, λ rs, ⟨pr.trans rs, qr.trans rs⟩⟩⟩,
suffices hs : ∀ (n : ℕ) (s : polynomial R), s.nat_degree = n → (p ∣ s ∧ q ∣ s → r ∣ s),
{ apply hs s.nat_degree s rfl },
clear s,
by_contra con,
push_neg at con,
rcases nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩,
have s0 : s ≠ 0,
{ contrapose! rs, simp [rs] },
have hs := nat.find_min' h ⟨_, s.nat_degree_prim_part, s.is_primitive_prim_part,
(hp.dvd_prim_part_iff_dvd s0).2 ps, (hq.dvd_prim_part_iff_dvd s0).2 qs⟩,
rw ← rdeg at hs,
by_cases sC : s.nat_degree ≤ 0,
{ rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), is_primitive_iff_content_eq_one,
content_C, normalize_eq_one] at rprim,
rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs,
apply rs rprim.dvd },
have hcancel := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree hs (lt_of_not_ge sC),
rw sdeg at hcancel,
apply nat.find_min con hcancel,
refine ⟨_, rfl, ⟨dvd_cancel_leads_of_dvd_of_dvd pr ps, dvd_cancel_leads_of_dvd_of_dvd qr qs⟩,
λ rcs, rs _⟩,
rw ← rprim.dvd_prim_part_iff_dvd s0,
rw [cancel_leads, nat.sub_eq_zero_of_le hs, pow_zero, mul_one] at rcs,
have h := dvd_add rcs (dvd.intro_left _ rfl),
have hC0 := rprim.ne_zero,
rw [ne.def, ← leading_coeff_eq_zero, ← C_eq_zero] at hC0,
rw [sub_add_cancel, ← rprim.dvd_prim_part_iff_dvd (mul_ne_zero hC0 s0)] at h,
rcases is_unit_prim_part_C r.leading_coeff with ⟨u, hu⟩,
apply h.trans (associated.symm ⟨u, _⟩).dvd,
rw [prim_part_mul (mul_ne_zero hC0 s0), hu, mul_comm],
end
lemma dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part
{p q : polynomial R} (hq : q ≠ 0) :
p ∣ q ↔ p.content ∣ q.content ∧ p.prim_part ∣ q.prim_part :=
begin
split; intro h,
{ rcases h with ⟨r, rfl⟩,
rw [content_mul, p.is_primitive_prim_part.dvd_prim_part_iff_dvd hq],
exact ⟨dvd.intro _ rfl, p.prim_part_dvd.trans (dvd.intro _ rfl)⟩ },
{ rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part],
exact mul_dvd_mul (ring_hom.map_dvd C h.1) h.2 }
end
@[priority 100]
instance normalized_gcd_monoid : normalized_gcd_monoid (polynomial R) :=
normalized_gcd_monoid_of_exists_lcm $ λ p q, begin
rcases exists_primitive_lcm_of_is_primitive p.is_primitive_prim_part q.is_primitive_prim_part
with ⟨r, rprim, hr⟩,
refine ⟨C (lcm p.content q.content) * r, λ s, _⟩,
by_cases hs : s = 0,
{ simp [hs] },
by_cases hpq : C (lcm p.content q.content) = 0,
{ rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq,
rcases hpq with hpq | hpq; simp [hpq, hs] },
iterate 3 { rw dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part hs },
rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff,
prim_part_mul (mul_ne_zero hpq rprim.ne_zero), rprim.prim_part_eq,
is_unit.mul_left_dvd _ _ _ (is_unit_prim_part_C (lcm p.content q.content)), ← hr s.prim_part],
tauto,
end
end normalized_gcd_monoid
end polynomial
|
281ecc2431efe9822033d5b85d27632051c95ac0 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/ring_theory/polynomial/symmetric.lean | fcbd03d10cde6a200573de0fac6eb3961b68eac9 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,147 | lean | /-
Copyright (c) 2020 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hanting Zhang, Johan Commelin
-/
import tactic
import data.mv_polynomial.rename
import data.mv_polynomial.comm_ring
import algebra.algebra.subalgebra
/-!
# Symmetric Polynomials and Elementary Symmetric Polynomials
This file defines symmetric `mv_polynomial`s and elementary symmetric `mv_polynomial`s.
We also prove some basic facts about them.
## Main declarations
* `mv_polynomial.is_symmetric`
* `mv_polynomial.symmetric_subalgebra`
* `mv_polynomial.esymm`
## Notation
+ `esymm σ R n`, is the `n`th elementary symmetric polynomial in `mv_polynomial σ R`.
As in other polynomial files, we typically use the notation:
+ `σ τ : Type*` (indexing the variables)
+ `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients)
+ `r : R` elements of the coefficient ring
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `φ ψ : mv_polynomial σ R`
-/
open equiv (perm)
open_locale big_operators
noncomputable theory
namespace mv_polynomial
variables {σ : Type*} {R : Type*}
variables {τ : Type*} {S : Type*}
/-- A `mv_polynomial φ` is symmetric if it is invariant under
permutations of its variables by the `rename` operation -/
def is_symmetric [comm_semiring R] (φ : mv_polynomial σ R) : Prop :=
∀ e : perm σ, rename e φ = φ
variables (σ R)
/-- The subalgebra of symmetric `mv_polynomial`s. -/
def symmetric_subalgebra [comm_semiring R] : subalgebra R (mv_polynomial σ R) :=
{ carrier := set_of is_symmetric,
algebra_map_mem' := λ r e, rename_C e r,
mul_mem' := λ a b ha hb e, by rw [alg_hom.map_mul, ha, hb],
add_mem' := λ a b ha hb e, by rw [alg_hom.map_add, ha, hb] }
variables {σ R}
@[simp] lemma mem_symmetric_subalgebra [comm_semiring R] (p : mv_polynomial σ R) :
p ∈ symmetric_subalgebra σ R ↔ p.is_symmetric := iff.rfl
namespace is_symmetric
section comm_semiring
variables [comm_semiring R] [comm_semiring S] {φ ψ : mv_polynomial σ R}
@[simp]
lemma C (r : R) : is_symmetric (C r : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).algebra_map_mem r
@[simp]
lemma zero : is_symmetric (0 : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).zero_mem
@[simp]
lemma one : is_symmetric (1 : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).one_mem
lemma add (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ + ψ) :=
(symmetric_subalgebra σ R).add_mem hφ hψ
lemma mul (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ * ψ) :=
(symmetric_subalgebra σ R).mul_mem hφ hψ
lemma smul (r : R) (hφ : is_symmetric φ) : is_symmetric (r • φ) :=
(symmetric_subalgebra σ R).smul_mem hφ r
@[simp]
lemma map (hφ : is_symmetric φ) (f : R →+* S) : is_symmetric (map f φ) :=
λ e, by rw [← map_rename, hφ]
end comm_semiring
section comm_ring
variables [comm_ring R] {φ ψ : mv_polynomial σ R}
lemma neg (hφ : is_symmetric φ) : is_symmetric (-φ) :=
(symmetric_subalgebra σ R).neg_mem hφ
lemma sub (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ - ψ) :=
(symmetric_subalgebra σ R).sub_mem hφ hψ
end comm_ring
end is_symmetric
section elementary_symmetric
open finset
variables (σ R) [comm_semiring R] [comm_semiring S] [fintype σ] [fintype τ]
/-- The `n`th elementary symmetric `mv_polynomial σ R`. -/
def esymm (n : ℕ) : mv_polynomial σ R :=
∑ t in powerset_len n univ, ∏ i in t, X i
/-- We can define `esymm σ R n` by summing over a subtype instead of over `powerset_len`. -/
lemma esymm_eq_sum_subtype (n : ℕ) : esymm σ R n =
∑ t : {s : finset σ // s.card = n}, ∏ i in (t : finset σ), X i :=
begin
rw esymm,
let i : Π (a : finset σ), a ∈ powerset_len n univ → {s : finset σ // s.card = n} :=
λ a ha, ⟨_, (mem_powerset_len.mp ha).2⟩,
refine sum_bij i (λ a ha, mem_univ (i a ha)) _ (λ _ _ _ _ hi, subtype.ext_iff_val.mp hi) _,
{ intros,
apply prod_congr,
simp only [subtype.coe_mk],
intros, refl,},
{ refine (λ b H, ⟨b.val, mem_powerset_len.mpr ⟨subset_univ b.val, b.property⟩, _⟩),
simp [i] },
end
/-- We can define `esymm σ R n` as a sum over explicit monomials -/
lemma esymm_eq_sum_monomial (n : ℕ) : esymm σ R n =
∑ t in powerset_len n univ, monomial (∑ i in t, finsupp.single i 1) 1 :=
begin
refine sum_congr rfl (λ x hx, _),
rw monic_monomial_eq,
rw finsupp.prod_pow,
rw ← prod_subset (λ y _, finset.mem_univ y : x ⊆ univ) (λ y _ hy, _),
{ refine prod_congr rfl (λ x' hx', _),
convert (pow_one _).symm,
convert (finsupp.apply_add_hom x' : (σ →₀ ℕ) →+ ℕ).map_sum _ x,
classical,
simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card],
rw if_pos hx', },
{ convert pow_zero _,
convert (finsupp.apply_add_hom y : (σ →₀ ℕ) →+ ℕ).map_sum _ x,
classical,
simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card],
rw if_neg hy, }
end
@[simp] lemma esymm_zero : esymm σ R 0 = 1 :=
by simp only [esymm, powerset_len_zero, sum_singleton, prod_empty]
lemma map_esymm (n : ℕ) (f : R →+* S) : map f (esymm σ R n) = esymm σ S n :=
begin
rw [esymm, (map f).map_sum],
refine sum_congr rfl (λ x hx, _),
rw (map f).map_prod,
simp,
end
lemma rename_esymm (n : ℕ) (e : σ ≃ τ) : rename e (esymm σ R n) = esymm τ R n :=
begin
rw [esymm_eq_sum_subtype, esymm_eq_sum_subtype, (rename ⇑e).map_sum],
let e' : {s : finset σ // s.card = n} ≃ {s : finset τ // s.card = n} :=
equiv.subtype_equiv (equiv.finset_congr e) (by simp),
rw ← equiv.sum_comp e'.symm,
apply fintype.sum_congr,
intro,
calc _ = (∏ i in (e'.symm a : finset σ), (rename e) (X i)) : (rename e).map_prod _ _
... = (∏ i in (a : finset τ), (rename e) (X (e.symm i))) : prod_map (a : finset τ) _ _
... = _ : _,
apply finset.prod_congr rfl,
intros,
simp,
end
lemma esymm_is_symmetric (n : ℕ) : is_symmetric (esymm σ R n) :=
by { intro, rw rename_esymm }
lemma support_esymm'' (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion
(λ t, (finsupp.single (∑ (i : σ) in t, finsupp.single i 1) (1:R)).support) :=
begin
rw esymm_eq_sum_monomial,
simp only [monomial],
convert finsupp.support_sum_eq_bUnion (powerset_len n (univ : finset σ)) _,
intros s t hst d,
simp only [finsupp.support_single_ne_zero one_ne_zero, and_imp, inf_eq_inter, mem_inter,
mem_singleton],
rintro h rfl,
have := congr_arg finsupp.support h,
rw [finsupp.support_sum_eq_bUnion, finsupp.support_sum_eq_bUnion] at this,
{ simp only [finsupp.support_single_ne_zero one_ne_zero, bUnion_singleton_eq_self] at this,
exact absurd this hst.symm },
all_goals { intros x y, simp [finsupp.support_single_disjoint] }
end
lemma support_esymm' (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support =
(powerset_len n (univ : finset σ)).bUnion (λ t, {∑ (i : σ) in t, finsupp.single i 1}) :=
begin
rw support_esymm'',
congr,
funext,
exact finsupp.support_single_ne_zero one_ne_zero
end
lemma support_esymm (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support =
(powerset_len n (univ : finset σ)).image (λ t, ∑ (i : σ) in t, finsupp.single i 1) :=
by { rw support_esymm', exact bUnion_singleton }
lemma degrees_esymm [nontrivial R]
(n : ℕ) (hpos : 0 < n) (hn : n ≤ fintype.card σ) :
(esymm σ R n).degrees = (univ : finset σ).val :=
begin
classical,
have : (finsupp.to_multiset ∘ λ (t : finset σ), ∑ (i : σ) in t, finsupp.single i 1) = finset.val,
{ funext, simp [finsupp.to_multiset_sum_single] },
rw [degrees, support_esymm, sup_finset_image, this, ←comp_sup_eq_sup_comp],
{ obtain ⟨k, rfl⟩ := nat.exists_eq_succ_of_ne_zero hpos.ne',
simpa using powerset_len_sup _ _ (nat.lt_of_succ_le hn) },
{ intros,
simp only [union_val, sup_eq_union],
congr },
{ refl }
end
end elementary_symmetric
end mv_polynomial
|
3efa66e5baeb48cf4d8450f5ce934427e836a444 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /logic/function.lean | 16ea359e44e7b8ab5ea078b445cb3c7cd8ac7f9d | [
"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 | 8,671 | lean | /-
Copyright (c) 2016 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Miscellaneous function constructions and lemmas.
-/
import logic.basic data.option
universes u v w
namespace function
section
variables {α : Sort u} {β : Sort v} {f : α → β}
lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a}
(hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' :=
begin
subst hα,
have : ∀a, f a == f' a,
{ intro a, exact h a a (heq.refl a) },
have : β = β',
{ funext a, exact type_eq_of_heq (this a) },
subst this,
apply heq_of_eq,
funext a,
exact eq_of_heq (this a)
end
lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) :=
iff.intro (assume h a, h ▸ rfl) funext
lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) :
(f ∘ g) a = f (g a) := rfl
@[simp] theorem injective.eq_iff (I : injective f) {a b : α} :
f a = f b ↔ a = b :=
⟨@I _ _, congr_arg f⟩
def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α
| a b := decidable_of_iff _ I.eq_iff
instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*)
[Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp)
| f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm
theorem cantor_surjective {α} (f : α → α → Prop) : ¬ function.surjective f | h :=
let ⟨D, e⟩ := h (λ a, ¬ f a a) in
(iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D)
theorem cantor_injective {α : Type*} (f : (α → Prop) → α) :
¬ function.injective f | i :=
cantor_surjective (λ a b, ∀ U, a = f U → U b) $
surjective_of_has_right_inverse ⟨f, λ U, funext $
λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩⟩
/-- `g` is a partial inverse to `f` (an injective but not necessarily
surjective function) if `g y = some x` implies `f x = y`, and `g y = none`
implies that `y` is not in the range of `f`. -/
def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop :=
∀ x y, g y = some x ↔ f x = y
theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x :=
(H _ _).2 rfl
theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f :=
λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl)
theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g)
(x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y :=
((H _ _).1 h₁).symm.trans ((H _ _).1 h₂)
theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=
funext h
theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=
funext h
theorem left_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) :=
assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a]
theorem right_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=
left_inverse.comp hh hf
local attribute [instance] classical.prop_decidable
/-- We can use choice to construct explicitly a partial inverse for
a given injective function `f`. -/
noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α :=
if h : ∃ a, f a = b then some (classical.some h) else none
theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) :
is_partial_inv f (partial_inv f) | a b :=
⟨λ h, if h' : ∃ a, f a = b then begin
rw [partial_inv, dif_pos h'] at h,
injection h with h, subst h,
apply classical.some_spec h'
end else by rw [partial_inv, dif_neg h'] at h; contradiction,
λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩,
(dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩
theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x :=
is_partial_inv_left (partial_inv_of_injective I)
end
section inv_fun
variables {α : Type u} [inhabited α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β}
local attribute [instance] classical.prop_decidable
/-- Construct the inverse for a function `f` on domain `s`. -/
noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α :=
if h : ∃a, a ∈ s ∧ f a = b then classical.some h else default α
theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b :=
by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h
theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left
theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right
theorem inv_fun_on_eq' (h : ∀ x y ∈ s, f x = f y → x = y) (ha : a ∈ s) :
inv_fun_on f s (f a) = a :=
have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩,
h _ _ (inv_fun_on_mem this) ha (inv_fun_on_eq this)
theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = default α :=
by rw [bex_def] at h; rw [inv_fun_on, dif_neg h]
/-- The inverse of a function (which is a left inverse if `f` is injective
and a right inverse if `f` is surjective). -/
noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ
theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b :=
inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩
theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α}
(hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=
funext $ assume b,
hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end
lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f :=
assume b, inv_fun_eq $ hf b
lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f :=
assume b,
have f (inv_fun f (f b)) = f b,
from inv_fun_eq ⟨b, rfl⟩,
hf this
lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) :=
surjective_of_has_right_inverse ⟨_, left_inverse_inv_fun hf⟩
lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf
lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f :=
⟨inv_fun f, left_inverse_inv_fun hf⟩
lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f :=
⟨injective.has_left_inverse, injective_of_has_left_inverse⟩
end inv_fun
section surj_inv
variables {α : Sort u} {β : Sort v} {f : α → β}
/-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require
`α` to be inhabited.) -/
noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b)
lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b)
lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f :=
surj_inv_eq hf
lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f :=
right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2)
lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f :=
⟨_, right_inverse_surj_inv hf⟩
lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f :=
⟨surjective.has_right_inverse, surjective_of_has_right_inverse⟩
lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f :=
⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩,
λ ⟨g, gl, gr⟩, ⟨injective_of_left_inverse gl, surjective_of_has_right_inverse ⟨_, gr⟩⟩⟩
lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) :=
injective_of_has_left_inverse ⟨f, right_inverse_surj_inv h⟩
end surj_inv
section update
variables {α : Sort u} {β : α → Sort v} [decidable_eq α]
def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a :=
if h : a = a' then eq.rec v h.symm else f a
@[simp] lemma update_same {a : α} {v : β a} {f : Πa, β a} : update f a v a = v :=
dif_pos rfl
@[simp] lemma update_noteq {a a' : α} {v : β a'} {f : Πa, β a} (h : a ≠ a') : update f a' v a = f a :=
dif_neg h
end update
lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) :=
funext $ assume ⟨a, b⟩, rfl
end function
|
cabb525d41b24c07024086ae47bd04919b06cb8d | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/data/nat/prime.lean | 2de92d0b60ac693a1d5a7747fc7726daf6b61252 | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 20,201 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.nat.sqrt data.nat.gcd data.list.defs data.list.perm
import algebra.group_power
import tactic.wlog
/-!
# Prime numbers
This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`.
## Important declarations
All the following declarations exist in the namespace `nat`.
- `prime`: the predicate that expresses that a natural number `p` is prime
- `primes`: the subtype of natural numbers that are prime
- `min_fac n`: the minimal prime factor of a natural number `n ≠ 1`
- `exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers
- `factors n`: the prime factorization of `n`
- `factors_unique`: uniqueness of the prime factorisation
-/
open bool subtype
namespace nat
open decidable
/-- `prime p` means that `p` is a prime number, that is, a natural number
at least 2 whose only divisors are `p` and `1`. -/
def prime (p : ℕ) := 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p
theorem prime.two_le {p : ℕ} : prime p → 2 ≤ p := and.left
theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le
lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 :=
ne.symm $ (ne_of_lt hp.one_lt)
theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 :=
and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h l d, (h d).resolve_right (ne_of_lt l),
λ h d, (decidable.lt_or_eq_of_le $
le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩
theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p :=
prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial),
λ h l d, begin
rcases m with _|_|m,
{ rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial },
{ refl },
{ exact (h dec_trivial l).elim d }
end⟩
theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧
∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p :=
prime_def_lt'.trans $ and_congr_right $ λ p2,
⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2,
λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from
λ m k mk m1 e, a m m1
(le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩,
λ m m2 l ⟨k, e⟩, begin
cases (le_total m k) with mk km,
{ exact this mk m2 e },
{ rw [mul_comm] at e,
refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e,
rwa [one_mul, ← e] }
end⟩
/--
This instance is slower than the instance `decidable_prime` defined below,
but has the advantage that it works in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
def decidable_prime_1 (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_lt'
local attribute [instance] decidable_prime_1
lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 :=
assume hn : n = 0,
have h2 : ¬ prime 0, from dec_trivial,
h2 (hn ▸ h)
theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p :=
lt_of_succ_lt pp.one_lt
theorem not_prime_zero : ¬ prime 0 := dec_trivial
theorem not_prime_one : ¬ prime 1 := dec_trivial
theorem prime_two : prime 2 := dec_trivial
theorem prime_three : prime 3 := dec_trivial
theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p :=
lt_pred_iff.2 pp.one_lt
theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p :=
succ_pred_eq_of_pos pp.pos
theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p :=
⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩
theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p :=
(dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H
theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1
| d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d
theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) :=
λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $
by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _)
section min_fac
private lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) :
sqrt n - k < sqrt n + 2 - k :=
(nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $
nat.lt_add_of_pos_right dec_trivial
def min_fac_aux (n : ℕ) : ℕ → ℕ | k :=
if h : n < k * k then n else
if k ∣ n then k else
have _, from min_fac_lemma n k h,
min_fac_aux (k + 2)
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : ℕ → ℕ
| 0 := 2
| 1 := 1
| (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3
@[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl
@[simp] theorem min_fac_one : min_fac 1 = 1 := rfl
theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3
| 0 := rfl
| 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl
| (n+2) :=
have 2 ∣ n + 2 ↔ 2 ∣ n, from
(nat.dvd_add_iff_left (by refl)).symm,
by simp [min_fac, this]; congr
private def min_fac_prop (n k : ℕ) :=
2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m
theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) (nd2 : ¬ 2 ∣ n) :
∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k)
| k := λ i e a, begin
rw min_fac_aux,
by_cases h : n < k*k; simp [h],
{ have pp : prime n :=
prime_def_le_sqrt.2 ⟨n2, λ m m2 l d,
not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩,
from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq
((dvd_prime_two_le pp m2).1 d).symm⟩ },
have k2 : 2 ≤ k, { subst e, exact dec_trivial },
by_cases dk : k ∣ n; simp [dk],
{ exact ⟨k2, dk, a⟩ },
{ refine have _, from min_fac_lemma n k h,
min_fac_aux_has_prop (k+2) (i+1)
(by simp [e, left_distrib]) (λ m m2 d, _),
cases nat.eq_or_lt_of_le (a m m2 d) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [← me, e] at d, change 2 * (i + 2) ∣ n at d,
have := dvd_of_mul_right_dvd d, contradiction }
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) :
min_fac_prop n (min_fac n) :=
begin
by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]},
have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial },
simp [min_fac_eq],
by_cases d2 : 2 ∣ n; simp [d2],
{ exact ⟨le_refl _, d2, λ k k2 d, k2⟩ },
{ refine min_fac_aux_has_prop n2 d2 3 0 rfl
(λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)),
exact λ e, e.symm ▸ d }
end
theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1]
theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) :=
let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in
prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩
theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m :=
by by_cases n1 : n = 1;
[exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2,
exact (min_fac_has_prop n1).2.2]
theorem min_fac_pos (n : ℕ) : 0 < min_fac n :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos]
theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n :=
le_of_dvd H (min_fac_dvd n)
theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p :=
⟨λ pp, ⟨pp.two_le,
let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in
((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩,
λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩
/--
This instance is faster in the virtual machine than `decidable_prime_1`,
but slower in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
instance decidable_prime (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_min_fac
theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n :=
(not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $
(lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm
lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n :=
match min_fac_dvd n with
| ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial
| ⟨1, h1⟩ :=
begin
rw mul_one at h1,
rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np,
rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one]
end
| ⟨(x+2), hx⟩ :=
begin
conv_rhs { congr, rw hx },
rw [nat.mul_div_cancel_left _ (min_fac_pos _)],
exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩
end
end
end min_fac
theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt,
ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) :
∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n :=
⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le,
(not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_prime_and_dvd {n : ℕ} (n2 : 2 ≤ n) : ∃ p, prime p ∧ p ∣ n :=
⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩
/-- Euclid's theorem. There exist infinitely many prime numbers.
Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/
theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p :=
let p := min_fac (fact n + 1) in
have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _,
have pp : prime p, from min_fac_prime f1,
have np : n ≤ p, from le_of_not_ge $ λ h,
have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h,
have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _),
pp.not_dvd_one h₂,
⟨p, np, pp⟩
lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 :=
(nat.mod_two_eq_zero_or_one p).elim
(λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm)
or.inr
theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 :=
div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt
/-- `factors n` is the prime factorization of `n`, listed in increasing order. -/
def factors : ℕ → list ℕ
| 0 := []
| 1 := []
| n@(k+2) :=
let m := min_fac n in have n / m < n := factors_lemma,
m :: factors (n / m)
lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p
| 0 := λ p, false.elim
| 1 := λ p, false.elim
| n@(k+2) := λ p h,
let m := min_fac n in have n / m < n := factors_lemma,
have h₁ : p = m ∨ p ∈ (factors (n / m)) :=
(list.mem_cons_iff _ _ _).1 h,
or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial)
mem_factors
lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n
| 0 := (lt_irrefl _).elim
| 1 := λ h, rfl
| n@(k+2) := λ h,
let m := min_fac n in have n / m < n := factors_lemma,
show list.prod (m :: factors (n / m)) = n, from
have h₁ : 0 < n / m :=
nat.pos_of_ne_zero $ λ h,
have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h,
by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this,
by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)]
lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] :=
begin
have : p = (p - 2) + 2 := (nat.sub_eq_iff_eq_add hp.1).mp rfl,
rw [this, nat.factors],
simp only [eq.symm this],
have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2,
split,
{ exact this, },
{ simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], },
end
theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n :=
⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]),
λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_two_le pp m2).1 mp).symm ▸ nd⟩
theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n :=
iff_not_comm.2 pp.coprime_iff_not_dvd
theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n :=
⟨λ H, or_iff_not_imp_left.2 $ λ h,
(pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H,
or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩
theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p)
(Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n :=
mt pp.dvd_mul.1 $ by simp [Hm, Hn]
theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m :=
by induction n with n IH;
[exact pp.not_dvd_one.elim h,
exact (pp.dvd_mul.1 h).elim IH id]
lemma prime.mul_eq_prime_pow_two_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) :
x * y = p ^ 2 ↔ x = p ∧ y = p :=
⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [nat.pow_two],
begin
wlog := hp.dvd_mul.1 pdvdxy using x y,
cases case with a ha,
have hap : a ∣ p, from ⟨y, by rwa [ha, nat.pow_two,
mul_assoc, nat.mul_left_inj hp.pos, eq_comm] at h⟩,
exact ((nat.dvd_prime hp).1 hap).elim
(λ _, by clear_aux_decl; simp [*, nat.pow_two, nat.mul_left_inj hp.pos] at *
{contextual := tt})
(λ _, by clear_aux_decl; simp [*, nat.pow_two, mul_comm, mul_assoc,
nat.mul_left_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at *
{contextual := tt})
end,
λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (nat.pow_two _).symm⟩
lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n
| 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos)
| (n+1) p hp := begin
rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp],
exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le,
λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ)
(λ h, or.inl $ by rw h)⟩
end
theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) :=
(pp.coprime_iff_not_dvd.2 h).symm.pow_right _
theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q :=
pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le
theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) :
coprime (p^n) (q^m) :=
((coprime_primes pp pq).2 h).pow _ _
theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i :=
by rw [pp.dvd_iff_not_coprime]; apply em
theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k :=
begin
induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *},
by_cases p ∣ i,
{ cases h with a e, subst e,
rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH],
split; intro h; rcases h with ⟨k, h, e⟩,
{ exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ },
cases k with k,
{ apply pp.not_dvd_one.elim,
simp at e, rw ← e, apply dvd_mul_right },
{ refine ⟨k, le_of_succ_le_succ h, _⟩,
rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } },
{ split; intro d,
{ rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d,
exact ⟨0, zero_le _, rfl⟩ },
{ rcases d with ⟨k, l, e⟩,
rw e, exact pow_dvd_pow _ l } }
end
section
open list
lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) :
∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l
| [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp)
| (q :: l) := λ h₁ h₂,
have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂,
have hq : prime q := h₁ q (mem_cons_self _ _),
or.cases_on ((prime.dvd_mul hp).1 h₃)
(λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h;
exact h ▸ mem_cons_self _ _)
(λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)),
(mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h)))
lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n :=
⟨λ h, prod_factors hn ▸ list.dvd_prod h,
λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩
lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ →
(∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂
| [] [] _ _ _ := perm.nil
| [] (a :: l) h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _)))
| (a :: l) [] h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _)))
| (a :: l₁) (b :: l₂) h hl₁ hl₂ :=
have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp),
have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp),
have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂
(h ▸ by rw prod_cons; exact dvd_mul_right _ _),
have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha,
have hl : prod l₁ = prod ((b :: l₂).erase a) :=
(nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $
by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb],
perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm
lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n :=
have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin
rw h at *, clear h,
induction l with a l hi,
{ exact absurd h₁ dec_trivial },
{ rw prod_cons at h₁,
exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm
(hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ }
end,
perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _)
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ}
(hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) :
p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n :=
have hpd : p^(k+l) * p ∣ m*n, from hpmn,
have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd,
have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2,
have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3,
have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4,
show p^k*p ∣ m ∨ p^l*p ∣ n, from
hpd5.elim
(assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this)
(assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this)
/-- The type of prime numbers -/
def primes := {p : ℕ // p.prime}
namespace primes
instance : has_repr nat.primes := ⟨λ p, repr p.val⟩
instance : inhabited primes := ⟨⟨2, prime_two⟩⟩
instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩
theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q :=
λ h, subtype.eq h
end primes
instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩
end nat
|
53ff07b7bd3fbfcc6a9fb95e7246d0120ffeb500 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/computability/turing_machine.lean | 2d7bde5959a75ae6f389317cbcdab2be359d3ab6 | [
"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 | 109,935 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.basic
import data.pfun
import logic.function.iterate
import order.basic
import tactic.apply_fun
/-!
# Turing machines
This file defines a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
to prove that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → stmt`, although different models have different ways of halting and other actions.
* `step : cfg → option cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : input → cfg` sets up the initial state. The type `input` depends on the model;
in most cases it is `list Γ`.
* `eval : machine → input → part output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to
the final state to obtain the result. The type `output` depends on the model.
* `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
open relation
open nat (iterate)
open function (update iterate_succ iterate_succ_apply iterate_succ'
iterate_succ_apply' iterate_zero_apply)
namespace turing
/-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding
blanks (`default Γ`) to the end of `l₁`. -/
def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
∃ n, l₂ = l₁ ++ list.repeat (default Γ) n
@[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l :=
⟨0, by simp⟩
@[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ :=
by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩
theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l l₁ → blank_extends l l₂ →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i,
simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h,
simp only [← list.repeat_add, add_sub_cancel_of_le h, list.append_assoc],
end
/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the
longer of `l₁` and `l₂`). -/
def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ}
(h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) :
{l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} :=
if h : l₁.length ≤ l₂.length then
⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩
else
⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩
theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l₁ l → blank_extends l₂ l →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j,
refine list.append_right_cancel (e.symm.trans _),
rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel],
apply_fun list.length at e,
simp only [list.length_append, list.length_repeat] at e,
rwa [← add_le_add_iff_left, e, add_le_add_iff_right]
end
/-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence
relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/
def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
blank_extends l₁ l₂ ∨ blank_extends l₂ l₁
@[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l :=
or.inl (blank_extends.refl _)
@[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm
@[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ :=
begin
rintro (h₁|h₁) (h₂|h₂),
{ exact or.inl (h₁.trans h₂) },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.above_of_le h₂ h) },
{ exact or.inr (h₂.above_of_le h₁ h) } },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.below_of_le h₂ h) },
{ exact or.inr (h₂.below_of_le h₁ h) } },
{ exact or.inr (h₂.trans h₁) },
end
/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/
def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l₁ l ∧ blank_extends l₂ l} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩
else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/
def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l l₁ ∧ blank_extends l l₂} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩
else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) :=
⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩
/-- Construct a setoid instance for `blank_rel`. -/
def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩
/-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to
represent half-tapes of a Turing machine, so that we can pretend that the list continues
infinitely with blanks. -/
def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ)
instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩
instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩
/-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger
precondition `blank_extends` instead of `blank_rel`. -/
@[elab_as_eliminator, reducible]
protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α)
(H : ∀ a b, blank_extends a b → f a = f b) : α :=
l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm]
/-- The quotient map turning a `list` into a `list_blank`. -/
def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk'
@[elab_as_eliminator]
protected lemma list_blank.induction_on {Γ} [inhabited Γ]
{p : list_blank Γ → Prop} (q : list_blank Γ)
(h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h
/-- The head of a `list_blank` is well defined. -/
def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ :=
l.lift_on list.head begin
rintro _ _ ⟨i, rfl⟩,
cases a, {cases i; refl}, refl
end
@[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.head (list_blank.mk l) = l.head := rfl
/-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/
def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk l.tail) begin
rintro _ _ ⟨i, rfl⟩,
refine quotient.sound' (or.inl _),
cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩]
end
@[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl
/-- We can cons an element onto a `list_blank`. -/
def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk (list.cons a l)) begin
rintro _ _ ⟨i, rfl⟩,
exact quotient.sound' (or.inl ⟨i, rfl⟩),
end
@[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) :
list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl
@[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).head = a :=
quotient.ind' $ by exact λ l, rfl
@[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).tail = l :=
quotient.ind' $ by exact λ l, rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
@[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] :
∀ (l : list_blank Γ), l.tail.cons l.head = l :=
quotient.ind' begin
refine (λ l, quotient.sound' (or.inr _)),
cases l, {exact ⟨1, rfl⟩}, {refl},
end
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) :
∃ a l', l = list_blank.cons a l' :=
⟨_, _, (list_blank.cons_head_tail _).symm⟩
/-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/
def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ :=
l.lift_on (λ l, list.inth l n) begin
rintro l _ ⟨i, rfl⟩,
simp only [list.inth],
cases lt_or_le _ _ with h h, {rw list.nth_append h},
rw list.nth_len_le h,
cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂},
rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat]
end
@[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) :
(list_blank.mk l).nth n = l.inth n := rfl
@[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) :
l.nth (n + 1) = l.tail.nth n :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} :
(∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ :=
list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H,
begin
wlog h : l₁.length ≤ l₂.length using l₁ l₂,
swap, { exact (this $ λ i, (H i).symm).symm },
refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩),
refine list.ext_le _ (λ i h h₂, eq.symm _),
{ simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] },
simp at H,
cases lt_or_le i l₁.length with h' h',
{ simpa only [list.nth_le_append _ h',
list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i },
{ simpa only [list.nth_le_append_right h', list.nth_le_repeat,
list.nth_le_nth h, list.nth_len_le h', option.iget] using H i },
end
/-- Apply a function to a value stored at the nth position of the list. -/
@[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ
| 0 L := L.tail.cons (f L.head)
| (n+1) L := (L.tail.modify_nth n).cons L.head
theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) :
(L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i :=
begin
induction n with n IH generalizing i L,
{ cases i; simp only [list_blank.nth_zero, if_true,
list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true,
list_blank.nth_succ, if_false, list_blank.tail_cons] },
{ cases i,
{ rw if_neg (nat.succ_ne_zero _).symm,
simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] },
{ simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons],
congr } }
end
/-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/
structure {u v} pointed_map (Γ : Type u) (Γ' : Type v)
[inhabited Γ] [inhabited Γ'] : Type (max u v) :=
(f : Γ → Γ') (map_pt' : f (default _) = default _)
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') :=
⟨⟨λ _, default _, rfl⟩⟩
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') :=
⟨_, pointed_map.f⟩
@[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl
@[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _
@[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head :=
by cases l; [exact (pointed_map.map_pt f).symm, refl]
/-- The `map` function on lists is well defined on `list_blank`s provided that the map is
pointed. -/
def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.map f l)) begin
rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩),
simp only [pointed_map.map_pt, list.map_append, list.map_repeat],
end
@[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl
@[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) :=
begin
refine (list_blank.cons_head_tail _).symm.trans _,
simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons]
end
@[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) :=
l.induction_on begin
intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth],
cases l.nth n, {exact f.2.symm}, {refl}
end
/-- The `i`-th projection as a pointed map. -/
def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) :
pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩
theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι)
(L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i :=
by rw list_blank.nth_map; refl
theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ']
(F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ')
(H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) :
(L.modify_nth f n).map F = (L.map F).modify_nth f' n :=
by induction n with n IH generalizing L; simp only [*,
list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map]
/-- Append a list on the left side of a list_blank. -/
@[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ
| [] L := L
| (a :: l) L := list_blank.cons a (list_blank.append l L)
@[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) :
list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) :=
by induction l₁; simp only [*,
list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk]
theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) :
list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) :=
l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc]
/-- The `bind` function on lists is well defined on `list_blank`s provided that the default element
is sent to a sequence of default elements. -/
def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list_blank Γ) (f : Γ → list Γ')
(hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.bind l f)) begin
rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩),
rw [list.bind_append, mul_comm], congr,
induction i with i IH, refl,
simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind],
end
@[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list Γ) (f : Γ → list Γ') (hf) :
(list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl
@[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) :
(l.cons a).bind f hf = (l.bind f hf).append (f a) :=
l.induction_on $ by intro; simp only [list_blank.append_mk,
list_blank.bind_mk, list_blank.cons_mk, list.cons_bind]
/-- The tape of a Turing machine is composed of a head element (which we imagine to be the
current position of the head), together with two `list_blank`s denoting the portions of the tape
going off to the left and right. When the Turing machine moves right, an element is pulled from the
right side and becomes the new head, while the head element is consed onto the left side. -/
structure tape (Γ : Type*) [inhabited Γ] :=
(head : Γ)
(left : list_blank Γ)
(right : list_blank Γ)
instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) :=
⟨by constructor; apply default⟩
/-- A direction for the turing machine `move` command, either
left or right. -/
@[derive decidable_eq, derive inhabited]
inductive dir | left | right
/-- The "inclusive" left side of the tape, including both `left` and `head`. -/
def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head
/-- The "inclusive" right side of the tape, including both `right` and `head`. -/
def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head
/-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes
`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/
def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ
| dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩
| dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩
@[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.left).move dir.right = T :=
by cases T; simp [tape.move]
@[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.right).move dir.left = T :=
by cases T; simp [tape.move]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩
@[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).left = L := rfl
@[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).head = R.head := rfl
@[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right = R.tail := rfl
@[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right₀ = R := list_blank.cons_head_tail _
@[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) :
tape.mk' T.left T.right₀ = T :=
by cases T; simp only [tape.right₀, tape.mk',
list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self]
theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) :
∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩
@[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
@[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ :=
tape.mk' (list_blank.mk L) (list_blank.mk R)
/-- Construct a tape from a list, with the head of the list at the TM head and the rest going
to the right. -/
def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ :=
tape.mk₂ [] l
/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes
on the left and positive indexes on the right. (Picture a number line.) -/
def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ
| 0 := T.head
| (n+1:ℕ) := T.right.nth n
| -[1+ n] := T.left.nth n
@[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl
theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n :=
by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero,
list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons]
@[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) :
(tape.mk' L R).nth n = R.nth n :=
by rw [← tape.right₀_nth, tape.mk'_right₀]
@[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] :
∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1)
| ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm
| ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm
| ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _)
| ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin
rw add_sub_cancel,
change (R.cons a).nth (n+1) = R.nth n,
rw [list_blank.nth_succ, list_blank.tail_cons]
end
@[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) :
(T.move dir.right).nth i = T.nth (i+1) :=
by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel]
@[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) :
((tape.move dir.right)^[i] T).head = T.nth i :=
by induction i generalizing T; [refl, simp only [*,
tape.move_right_nth, int.coe_nat_succ, iterate_succ]]
/-- Replace the current value of the head on the tape. -/
def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T}
@[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) :
∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i
| ⟨a, L, R⟩ 0 := rfl
| ⟨a, L, R⟩ (n+1:ℕ) := rfl
| ⟨a, L, R⟩ -[1+ n] := rfl
@[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) :
(tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) :=
by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons,
eq_self_iff_true, and_self]
/-- Apply a pointed map to a tape to change the alphabet. -/
def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' :=
⟨f T.1, T.2.map f, T.3.map f⟩
@[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 :=
by rintro ⟨⟩; refl
@[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) :
∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) :
((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) =
((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) :=
begin
induction n with n IH generalizing L R,
{ simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply],
rw [← tape.write_mk', list_blank.cons_head_tail] },
simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth,
tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH]
end
theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d :=
by cases T; cases d; simp only [tape.move, tape.map,
list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map]
theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) :=
by simp only [tape.mk', tape.map, list_blank.head_map,
eq_self_iff_true, and_self, list_blank.tail_map]
theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) :=
by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk]
theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _
/-- Run a state transition function `σ → option σ` "to completion". The return value is the last
state returned before a `none` result. If the state transition function always returns `some`,
then the computation diverges, returning `part.none`. -/
def eval {σ} (f : σ → option σ) : σ → part σ :=
pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr)
/-- The reflexive transitive closure of a state transition function. `reaches f a b` means
there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation permits zero steps of the state transition function. -/
def reaches {σ} (f : σ → option σ) : σ → σ → Prop :=
refl_trans_gen (λ a b, b ∈ f a)
/-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a
nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation does not permit zero steps of the state transition function. -/
def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop :=
trans_gen (λ a b, b ∈ f a)
theorem reaches₁_eq {σ} {f : σ → option σ} {a b c}
(h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c :=
trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm
theorem reaches_total {σ} {f : σ → option σ}
{a b c} (hab : reaches f a b) (hac : reaches f a c) :
reaches f b c ∨ reaches f c b :=
refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac
theorem reaches₁_fwd {σ} {f : σ → option σ}
{a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c :=
begin
rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩,
cases option.mem_unique hab h₂, exact hbc
end
/-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then
`reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with
equivalent states without taking a step. -/
def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop :=
∀ c, reaches₁ f b c → reaches₁ f a c
theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c
| d h₃ := h₁ _ (h₂ _ h₃)
@[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a
| b h := h
theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ}
(h : b ∈ f a) : reaches₀ f a b
| c h₂ := h₂.head h
theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ}
(h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=
(reaches₀.single h).trans h₂
theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=
h₁.trans (reaches₀.single h)
theorem reaches₀_eq {σ} {f : σ → option σ} {a b}
(e : f a = f b) : reaches₀ f a b
| d h := (reaches₁_eq e).2 h
theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches₁ f a b) : reaches₀ f a b
| c h₂ := h.trans h₂
theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches f a b) : reaches₀ f a b
| c h₂ := h₂.trans_right h
theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ}
(h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=
h _ (trans_gen.single h₂)
/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`
which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it
holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if
`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/
@[elab_as_eliminator] def eval_induction {σ}
{f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a)
(H : ∀ a, b ∈ eval f a →
(∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a :=
pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $
part.mem_some_iff.2 $ by rw e; refl)
theorem mem_eval {σ} {f : σ → option σ} {a b} :
b ∈ eval f a ↔ reaches f a b ∧ f b = none :=
⟨λ h, begin
refine eval_induction h (λ a h IH, _),
cases e : f a with a',
{ rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $
part.mem_some_iff.2 $ by rw e; refl),
exact ⟨refl_trans_gen.refl, e⟩ },
{ rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩;
rw e at h; cases part.mem_some_iff.1 h,
cases IH a' h' (by rwa e) with h₁ h₂,
exact ⟨refl_trans_gen.head e h₁, h₂⟩ }
end, λ ⟨h₁, h₂⟩, begin
refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _),
{ refine pfun.mem_fix_iff.2 (or.inl _),
rw h₂, apply part.mem_some },
{ refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩),
rw show f a = _, from h,
apply part.mem_some }
end⟩
theorem eval_maximal₁ {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc :=
let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in
by cases b0.symm.trans h'
theorem eval_maximal {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) {c} : reaches f b c ↔ c = b :=
let ⟨ab, b0⟩ := mem_eval.1 h in
refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h'
theorem reaches_eval {σ} {f : σ → option σ} {a b}
(ab : reaches f a b) : eval f a = eval f b :=
part.ext $ λ c,
⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in
mem_eval.2 ⟨(or_iff_left_of_imp $ by exact
λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1
(reaches_total ab ac), c0⟩,
λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩
/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions
`f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds
initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a
state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.
Such a relation `tr` is also known as a refinement. -/
def respects {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) :=
∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with
| some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂
| none := f₂ a₂ = none
end : Prop)
theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=
begin
induction ab with c₁ ac c₁ d₁ ac cd IH,
{ have := H aa,
rwa (show f₁ a₁ = _, from ac) at this },
{ rcases IH with ⟨c₂, cc, ac₂⟩,
have := H cc,
rw (show f₁ c₁ = _, from cd) at this,
rcases this with ⟨d₂, dd, cd₂⟩,
exact ⟨_, dd, ac₂.trans cd₂⟩ }
end
theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=
begin
rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,
{ exact ⟨_, aa, refl_trans_gen.refl⟩ },
{ exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in
⟨b₂, bb, h.to_refl⟩ }
end
theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) :
∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=
begin
induction ab with c₂ d₂ ac cd IH,
{ exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ },
{ rcases IH with ⟨e₁, e₂, ce, ee, ae⟩,
rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩,
{ have := H ee, revert this,
cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib],
{ intro c0, cases cd.symm.trans c0 },
{ intros g₂ gg cg,
rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩,
cases option.mem_unique cd cd',
exact ⟨_, _, dg, gg, ae.tail eg⟩ } },
{ cases option.mem_unique cd cd',
exact ⟨_, _, de, ee, ae⟩ } }
end
theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂)
(ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩,
refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩,
have := H bb, rwa b0 at this
end
theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂)
(ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩,
cases (refl_trans_gen_iff_eq
(by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,
refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩,
have := H cc, cases f₁ c₁ with d₁, {refl},
rcases this with ⟨d₂, dd, bd⟩,
rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩,
cases b0.symm.trans h
end
theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) :
(eval f₂ a₂).dom ↔ (eval f₁ a₁).dom :=
⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h,
λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩
/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/
def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop
| (some b₁) := reaches₁ f₂ a₂ (tr b₁)
| none := f₂ a₂ = none
theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂}
(h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁
| (some b₁) := reaches₁_eq h
| none := by unfold frespects; rw h
theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :
respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) :=
forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq']
theorem tr_eval' {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂)
(H : respects f₁ f₂ (λ a b, tr a = b))
(a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
part.ext $ λ b₂,
⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in
(part.mem_map_iff _).2 ⟨b₁, hb, bb⟩,
λ h, begin
rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩,
rcases tr_eval H rfl ab with ⟨_, rfl, h⟩,
rwa bb at h
end⟩
/-!
## The TM0 model
A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory.
A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function
`Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`
for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and
an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of
the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the
`step` function:
* If `M q T.head = none`, then the machine halts.
* If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions
to state `q'`.
The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head
of the tape and the rest of the list extends to the right, with the left side all blank. The final
state takes the entire right side of the tape right or equal to the current position of the
machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level
of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list
to remove the infinite tail of blanks.)
-/
namespace TM0
section
parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols
parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
inductive stmt
| move : dir → stmt
| write : Γ → stmt
instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
@[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment
def machine := Λ → Γ → option (Λ × stmt)
instance machine.inhabited : inhabited machine := by unfold machine; apply_instance
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape, represented in
the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
structure cfg :=
(q : Λ)
(tape : tape Γ)
instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩
parameters {Γ Λ}
/-- Execution semantics of the Turing machine. -/
def step (M : machine) : cfg → option cfg
| ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q',
match a with
| stmt.move d := T.move d
| stmt.write a := T.write a
end⟩)
/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps from `s₂`. -/
def reaches (M : machine) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- The initial configuration. -/
def init (l : list Γ) : cfg :=
⟨default Λ, tape.mk₁ l⟩
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval (M : machine) (l : list Γ) : part (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def supports (M : machine) (S : set Λ) :=
default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports (M : machine) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.q ∈ S → c'.q ∈ S
| ⟨q, T⟩ c' h₁ h₂ := begin
rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩,
exact ss.2 h h₂,
end
theorem univ_supports (M : machine) : supports M set.univ :=
⟨trivial, λ q a q' s h₁ h₂, trivial⟩
end
section
variables {Γ : Type*} [inhabited Γ]
variables {Γ' : Type*} [inhabited Γ']
variables {Λ : Type*} [inhabited Λ]
variables {Λ' : Type*} [inhabited Λ']
/-- Map a TM statement across a function. This does nothing to move statements and maps the write
values. -/
def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ'
| (stmt.move d) := stmt.move d
| (stmt.write a) := stmt.write (f a)
/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and
`g : Λ → Λ'` a map of the machine states. -/
def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ'
| ⟨q, T⟩ := ⟨g q, T.map f⟩
variables (M : machine Γ Λ)
(f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)
/-- Because the state transition function uses the alphabet and machine states in both the input
and output, to map a machine from one alphabet and machine state space to another we need functions
in both directions, essentially an `equiv` without the laws. -/
def machine.map : machine Γ' Λ'
| q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁))
theorem machine.map_step {S : set Λ}
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
∀ c : cfg Γ Λ, c.q ∈ S →
(step M c).map (cfg.map f₁ g₁) =
step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c)
| ⟨q, T⟩ h := begin
unfold step machine.map cfg.map,
simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _],
rcases M q T.1 with _|⟨q', d|a⟩, {refl},
{ simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl },
{ simp only [step, cfg.map, option.map_some', tape.map_write], refl }
end
theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) :
(init l).map f₁ g₁ = init (l.map f₁) :=
congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _)
theorem machine.map_respects
(g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ)
{S} (ss : supports M S)
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
respects (step M) (step (M.map f₁ f₂ g₁ g₂))
(λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b)
| c _ ⟨cs, rfl⟩ := begin
cases e : step M c with c'; unfold respects,
{ rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl },
{ refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩,
rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl }
end
end
end TM0
/-!
## The TM1 model
The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of
Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which
is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local
variables and the value `T.head` on the tape to calculate what to write or how to change local
state, but the statements themselves have a fixed structure. The `stmt`s can be as follows:
* `move d q`: move left or right, and then do `q`
* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`
* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`
* `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`
* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`
* `halt`: Transition to the halting state, which halts on the following step
Note that here most statements do not have labels; `goto` commands can only go to a new function.
Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on
statements and so take 0 steps. (There is a uniform bound on many statements can be executed before
the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)
The `halt` command has a one step stutter before actually halting so that any changes made before
the halt have a chance to be "committed", since the `eval` relation uses the final configuration
before the halt as the output, and `move` and `write` etc. take 0 steps in this model.
-/
namespace TM1
section
parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive stmt
| move : dir → stmt → stmt
| write : (Γ → σ → Γ) → stmt → stmt
| load : (Γ → σ → σ) → stmt → stmt
| branch : (Γ → σ → bool) → stmt → stmt → stmt
| goto : (Γ → σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
structure cfg :=
(l : option Λ)
(var : σ)
(tape : tape Γ)
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ}
/-- The semantics of TM1 evaluation. -/
def step_aux : stmt → σ → tape Γ → cfg
| (move d q) v T := step_aux q v (T.move d)
| (write a q) v T := step_aux q v (T.write (a T.1 v))
| (load s q) v T := step_aux q (s T.1 v) T
| (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T)
| (goto l) v T := ⟨some (l T.1 v), v, T⟩
| halt v T := ⟨none, v, T⟩
/-- The state transition function. -/
def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, T⟩ := none
| ⟨some l, v, T⟩ := some (step_aux (M l) v T)
/-- A set `S` of labels supports the statement `q` if all the `goto`
statements in `q` refer only to other functions in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (move d q) := supports_stmt q
| (write a q) := supports_stmt q
| (load s q) := supports_stmt q
| (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ a v, l a v ∈ S
| halt := true
open_locale classical
/-- The subterm closure of a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(move d q) := insert Q (stmts₁ q)
| Q@(write a q) := insert Q (stmts₁ q)
| Q@(load s q) := insert Q (stmts₁ q)
| Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂,
iterate 3 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } },
case TM1.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM1.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM1.stmt.goto : l { subst h, exact hs },
case TM1.stmt.halt { subst h, trivial }
end
/-- The set of all statements in a turing machine, plus one extra value `none` representing the
halt state. This is used in the TM1 to TM0 reduction. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bUnion (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T;
intro hs,
iterate 3 { exact IH _ _ hs },
case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p T.1 v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) },
case TM1.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state, given a finite input that is placed on the tape starting at the TM head and
going to the right. -/
def init (l : list Γ) : cfg :=
⟨some (default _), default _, tape.mk₁ l⟩
/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate
number of blanks on the end). -/
def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
end
end TM1
/-!
## TM1 emulator in TM0
To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a
TM0 program. So suppose a TM1 program is given. We take the following:
* The alphabet `Γ` is the same for both TM1 and TM0
* The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none`
representing halt, and the possible settings of the internal variables.
Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume
that from the initial TM1 state, only finitely many other labels are reachable, and there are
only finitely many statements that appear in all of these functions.
Even though `stmt₁` contains a statement called `halt`, we must separate it from `none`
(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the
TM1 semantics.
-/
namespace TM1to0
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := TM1.stmt Γ Λ σ
local notation `cfg₁` := TM1.cfg Γ Λ σ
local notation `stmt₀` := TM0.stmt Γ
parameters (M : Λ → stmt₁)
include M
/-- The base machine state space is a pair of an `option stmt₁` representing the current program
to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,
not the tape). Because there are an infinite number of programs, this state space is infinite, but
for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are
reachable. -/
@[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption
-- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here.
-- But they are parameters so we cannot easily skip them for just this definition.
def Λ' := option stmt₁ × σ
instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩
open TM0.stmt
/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the
`stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular
instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the
latter case we emit a dummy `write s` step and transition to the new target location. -/
def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀
| (TM1.stmt.move d q) v := ((some q, v), move d)
| (TM1.stmt.write a q) v := ((some q, v), write (a s v))
| (TM1.stmt.load a q) v := tr_aux q (a s v)
| (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v)
| (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s)
| TM1.stmt.halt v := ((none, v), write s)
local notation `cfg₀` := TM0.cfg Γ Λ'
/-- The translated TM0 machine (given the TM1 machine input). -/
def tr : TM0.machine Γ Λ'
| (none, v) s := none
| (some q, v) s := some (tr_aux s q v)
/-- Translate configurations from TM1 to TM0. -/
def tr_cfg : cfg₁ → cfg₀
| ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩
theorem tr_respects : respects (TM1.step M) (TM0.step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
cases l₁ with l₁, {exact rfl},
unfold tr_cfg TM1.step frespects option.map function.comp option.bind,
induction M l₁ with _ q IH _ q IH _ q IH generalizing v T,
case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold TM1.step_aux, cases e : p T.1 v,
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) },
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } },
iterate 2 {
exact trans_gen.single (congr_arg some
(congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) }
end
theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l :=
(congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin
rw [part.map_eq_map, part.map_map, TM1.eval],
congr' with ⟨⟩, refl
end
variables [fintype σ]
/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible
machine states in the target (even though the type `Λ'` is infinite). -/
noncomputable def tr_stmts (S : finset Λ) : finset Λ' :=
(TM1.stmts M S).product finset.univ
open_locale classical
local attribute [simp] TM1.stmts₁_self
theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) :
TM0.supports tr (↑(tr_stmts S)) :=
⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2
(finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩),
finset.mem_univ _⟩,
λ q a q' s h₁ h₂, begin
rcases q with ⟨_|q, v⟩, {cases h₁},
cases q' with q' v', simp only [tr_stmts, finset.mem_coe,
finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢,
cases q', {exact multiset.mem_cons_self _ _},
simp only [tr, option.mem_def] at h₁,
have := TM1.stmts_supports_stmt ss h₂,
revert this, induction q generalizing v; intro hs,
case TM1.stmt.move : d q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.write : b q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.load : b q IH {
refine IH (TM1.stmts_trans _ h₂) _ h₁ hs,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
change cond (p a v) _ _ = ((some q', v'), s) at h₁,
cases p a v,
{ refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) },
{ refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } },
case TM1.stmt.goto : l {
cases h₁, exact finset.some_mem_insert_none.2
(finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) },
case TM1.stmt.halt { cases h₁ }
end⟩
end
end TM1to0
/-!
## TM1(Γ) emulator in TM1(bool)
The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`.
Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the
alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.
The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a
fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine
wants to read a symbol from the tape, it traverses over the block, performing `n` `branch`
instructions to each any of the `2^n` results.
For the `write` instruction, we have to use a `goto` because we need to follow a different code
path depending on the local state, which is not available in the TM1 model, so instead we jump to
a label computed using the read value and the local state, which performs the writing and returns
to normal execution.
Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are
exploiting the 0-step behavior of regular commands to avoid taking steps, but there are
nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are
finitely long.
-/
namespace TM1to1
open TM1
section
parameters {Γ : Type*} [inhabited Γ]
theorem exists_enc_dec [fintype Γ] :
∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ),
enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a :=
begin
letI := classical.dec_eq Γ,
let n := fintype.card Γ,
obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ,
let G : fin n ↪ fin n → bool := ⟨λ a b, a = b,
λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩,
let H := (F.to_embedding.trans G).trans
(equiv.vector_equiv_fin _ _).symm.to_embedding,
classical,
let enc := H.set_value (default _) (vector.repeat ff n),
exact ⟨_, enc, function.inv_fun enc,
H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩
end
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := stmt Γ Λ σ
local notation `cfg₁` := cfg Γ Λ σ
/-- The configuration state of the TM. -/
inductive Λ' : Type (max u_1 u_2 u_3)
| normal : Λ → Λ'
| write : Γ → stmt₁ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `stmt'` := stmt bool Λ' σ
local notation `cfg'` := cfg bool Λ' σ
/-- Read a vector of length `n` from the tape. -/
def read_aux : ∀ n, (vector bool n → stmt') → stmt'
| 0 f := f vector.nil
| (i+1) f := stmt.branch (λ a s, a)
(stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v)))
(stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v)))
parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ)
/-- A move left or right corresponds to `n` moves across the super-cell. -/
def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q
/-- To read a symbol from the tape, we use `read_aux` to traverse the symbol,
then return to the original position with `n` moves to the left. -/
def read (f : Γ → stmt') : stmt' :=
read_aux n (λ v, move dir.left $ f (dec v))
/-- Write a list of bools on the tape. -/
def write : list bool → stmt' → stmt'
| [] q := q
| (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q
/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that
we can access the current value of the tape. -/
def tr_normal : stmt₁ → stmt'
| (stmt.move d q) := move d $ tr_normal q
| (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q
| (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q
| (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂)
| (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s)
| stmt.halt := stmt.halt
theorem step_aux_move (d q v T) :
step_aux (move d q) v T =
step_aux q v ((tape.move d)^[n] T) :=
begin
suffices : ∀ i,
step_aux (stmt.move d^[i] q) v T =
step_aux q v (tape.move d^[i] T), from this n,
intro, induction i with i IH generalizing T, {refl},
rw [iterate_succ', step_aux, IH, iterate_succ]
end
theorem supports_stmt_move {S d q} :
supports_stmt S (move d q) = supports_stmt S q :=
suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this,
by intro; induction i generalizing q; simp only [*, iterate]; refl
theorem supports_stmt_write {S l q} :
supports_stmt S (write l q) = supports_stmt S q :=
by induction l with a l IH; simp only [write, supports_stmt, *]
theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'},
(∀ a, supports_stmt S (f a)) → supports_stmt S (read f) :=
suffices ∀ i (f : vector bool i → stmt'),
(∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f),
from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]),
λ i f hf, begin
induction i with i IH, {exact hf _},
split; apply IH; intro; apply hf,
end
parameter (enc0 : enc (default _) = vector.repeat ff n)
section
parameter {enc}
include enc0
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape' (L R : list_blank Γ) : tape bool :=
begin
refine tape.mk'
(L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩)
(R.bind (λ x, (enc x).to_list) ⟨n, _⟩);
simp only [enc0, vector.repeat,
list.reverse_repeat, bool.default_bool, vector.to_list_mk]
end
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀
theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R :=
by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀]
end
parameters (M : Λ → stmt₁)
/-- The top level program. -/
def tr : Λ' → stmt'
| (Λ'.normal l) := tr_normal (M l)
| (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q
/-- The machine configuration translation. -/
def tr_cfg : cfg₁ → cfg'
| ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩
parameter {enc}
include enc0
theorem tr_tape'_move_left (L R) :
(tape.move dir.left)^[n] (tr_tape' L R) =
(tr_tape' L.tail (R.cons L.head)) :=
begin
obtain ⟨a, L, rfl⟩ := L.exists_cons,
simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons],
suffices : ∀ {L' R' l₁ l₂}
(e : vector.to_list (enc a) = list.reverse_core l₁ l₂),
tape.move dir.left^[l₁.length]
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'),
{ simpa only [list.length_reverse, vector.to_list_length]
using this (list.reverse_reverse _).symm },
intros, induction l₁ with b l₁ IH generalizing l₂,
{ cases e, refl },
simp only [list.length, list.cons_append, iterate_succ_apply],
convert IH e,
simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons]
end
theorem tr_tape'_move_right (L R) :
(tape.move dir.right)^[n] (tr_tape' L R) =
(tr_tape' (L.cons R.head) R.tail) :=
begin
suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L,
{ refine (eq.symm _).trans (this n _),
simp only [tr_tape'_move_left, list_blank.cons_head_tail,
list_blank.head_cons, list_blank.tail_cons] },
intros, induction i with i IH, {refl},
rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH]
end
theorem step_aux_write (q v a b L R) :
step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) =
step_aux q v (tr_tape' (list_blank.cons a L) R) :=
begin
simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool)
(e : l₂'.length = l₂.length),
step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) =
step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'),
{ convert this [] _ _ ((enc b).2.trans (enc a).2.symm);
rw list_blank.cons_bind; refl },
clear a b L R, intros,
induction l₂ with a l₂ IH generalizing l₁ l₂',
{ cases list.length_eq_zero.1 e, refl },
cases l₂' with b l₂'; injection e with e,
dunfold write step_aux,
convert IH _ _ e using 1,
simp only [list_blank.head_cons, list_blank.tail_cons,
list_blank.append, tape.move_right_mk', tape.write_mk']
end
parameters (encdec : ∀ a, dec (enc a) = a)
include encdec
theorem step_aux_read (f v L R) :
step_aux (read f) v (tr_tape' L R) =
step_aux (f R.head) v (tr_tape' L R) :=
begin
suffices : ∀ f,
step_aux (read_aux n f) v (tr_tape' enc0 L R) =
step_aux (f (enc R.head)) v
(tr_tape' enc0 (L.cons R.head) R.tail),
{ rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0],
simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] },
obtain ⟨a, R, rfl⟩ := R.exists_cons,
simp only [list_blank.head_cons, list_blank.tail_cons,
tr_tape', list_blank.cons_bind, list_blank.append_assoc],
suffices : ∀ i f L' R' l₁ l₂ h,
step_aux (read_aux i f) v
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
step_aux (f ⟨l₂, h⟩) v
(tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'),
{ intro f, convert this n f _ _ _ _ (enc a).2; simp },
clear f L a R, intros, subst i,
induction l₂ with a l₂ IH generalizing l₁, {refl},
transitivity step_aux
(read_aux l₂.length (λ v, f (a ::ᵥ v))) v
(tape.mk' ((L'.append l₁).cons a) (R'.append l₂)),
{ dsimp [read_aux, step_aux], simp, cases a; refl },
rw [← list_blank.append, IH], refl
end
theorem tr_respects : respects (step M) (step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
obtain ⟨L, R, rfl⟩ := T.exists_mk',
cases l₁ with l₁, {exact rfl},
suffices : ∀ q R, reaches (step (tr enc dec M))
(step_aux (tr_normal dec q) v (tr_tape' enc0 L R))
(tr_cfg enc0 (step_aux q v (tape.mk' L R))),
{ refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R },
clear R l₁, intros,
induction q with _ q IH _ q IH _ q IH generalizing v L R,
case TM1.stmt.move : d q IH {
cases d; simp only [tr_normal, iterate, step_aux_move, step_aux,
list_blank.head_cons, tape.move_left_mk',
list_blank.cons_head_tail, list_blank.tail_cons,
tr_tape'_move_left enc0, tr_tape'_move_right enc0];
apply IH },
case TM1.stmt.write : f q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
refine refl_trans_gen.head rfl _,
obtain ⟨a, R, rfl⟩ := R.exists_cons,
rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons,
step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons,
list_blank.tail_cons, tape.write_mk'],
apply IH },
case TM1.stmt.load : a q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec],
apply IH },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
cases p R.head v; [apply IH₂, apply IH₁] },
case TM1.stmt.goto : l {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'],
apply refl_trans_gen.refl },
case TM1.stmt.halt {
simp only [tr_normal, step_aux, tr_cfg, step_aux_move,
tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'],
apply refl_trans_gen.refl }
end
omit enc0 encdec
open_locale classical
parameters [fintype Γ]
/-- The set of accessible `Λ'.write` machine states. -/
noncomputable def writes : stmt₁ → finset Λ'
| (stmt.move d q) := writes q
| (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q
| (stmt.load f q) := writes q
| (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂
| (stmt.goto l) := ∅
| stmt.halt := ∅
/-- The set of accessible machine states, assuming that the input machine is supported on `S`,
are the normal states embedded from `S`, plus all write states accessible from these states. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bUnion (λ l, insert (Λ'.normal l) (writes (M l)))
theorem tr_supports {S} (ss : supports M S) :
supports tr (tr_supp S) :=
⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩,
λ q h, begin
suffices : ∀ q, supports_stmt S q →
(∀ q' ∈ writes q, q' ∈ tr_supp M S) →
supports_stmt (tr_supp M S) (tr_normal dec q) ∧
∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),
{ rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩,
have := this _ (ss.2 _ hl) (λ q' hq,
finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩),
rcases finset.mem_insert.1 h with rfl | h,
exacts [this.1, this.2 _ h] },
intros q hs hw, induction q,
case TM1.stmt.move : d q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw, refine ⟨_, IH.2⟩,
cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] },
case TM1.stmt.write : f q IH {
unfold writes at hw ⊢,
simp only [finset.mem_image, finset.mem_union, finset.mem_univ,
exists_prop, true_and] at hw ⊢,
replace IH := IH hs (λ q hq, hw q (or.inr hq)),
refine ⟨supports_stmt_read _ $ λ a _ s,
hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩,
rcases hq with ⟨a, q₂, rfl⟩ | hq,
{ simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] },
{ exact IH.2 _ hq } },
case TM1.stmt.load : a q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw,
refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold writes at hw ⊢,
simp only [finset.mem_union] at hw ⊢,
replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)),
replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)),
exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩),
λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ },
case TM1.stmt.goto : l {
refine ⟨_, λ _, false.elim⟩,
refine supports_stmt_read _ (λ a _ s, _),
exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ },
case TM1.stmt.halt {
refine ⟨_, λ _, false.elim⟩,
simp only [supports_stmt, supports_stmt_move, tr_normal] }
end⟩
end
end TM1to1
/-!
## TM0 emulator in TM1
To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator
in TM1. The main complication here is that TM0 allows an action to depend on the value at the head
and local state, while TM1 doesn't (in order to have more programming language-like semantics).
So we use a computed `goto` to go to a state that performes the desired action and then returns to
normal execution.
One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step
to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an
unreachable branch).
-/
namespace TM0to1
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded
as `normal q` states, but the actual operation is split into two parts, a jump to `act s q`
followed by the action and a jump to the next `normal` state. -/
inductive Λ'
| normal : Λ → Λ'
| act : TM0.stmt Γ → Λ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `cfg₀` := TM0.cfg Γ Λ
local notation `stmt₁` := TM1.stmt Γ Λ' unit
local notation `cfg₁` := TM1.cfg Γ Λ' unit
parameters (M : TM0.machine Γ Λ)
open TM1.stmt
/-- The program. -/
def tr : Λ' → stmt₁
| (Λ'.normal q) :=
branch (λ a _, (M q a).is_none) halt $
goto (λ a _, match M q a with
| none := default _ -- unreachable
| some (q', s) := Λ'.act s q'
end)
| (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q)
| (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q)
/-- The configuration translation. -/
def tr_cfg : cfg₀ → cfg₁
| ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩
theorem tr_respects : respects (TM0.step M) (TM1.step tr)
(λ a b, tr_cfg a = b) :=
fun_respects.2 $ λ ⟨q, T⟩, begin
cases e : M q T.1,
{ simp only [TM0.step, tr_cfg, e]; exact eq.refl none },
cases val with q' s,
simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'],
have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ =
some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩,
{ cases s with d a; refl },
refine trans_gen.head _ (trans_gen.head' this _),
{ unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e, refl },
cases e' : M q' _,
{ apply refl_trans_gen.single,
unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e', refl },
{ refl }
end
end
end TM0to1
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`list_blank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
section
parameters {K : Type*} [decidable_eq K] -- Index type of stacks
parameters (Γ : K → Type*) -- Type of stack elements
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive stmt
| push : ∀ k, (σ → Γ k) → stmt → stmt
| peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| load : (σ → σ) → stmt → stmt
| branch : (σ → bool) → stmt → stmt → stmt
| goto : (σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite
size.) -/
structure cfg :=
(l : option Λ)
(var : σ)
(stk : ∀ k, list (Γ k))
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ K}
/-- The step function for the TM2 model. -/
@[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg
| (push k f q) v S := step_aux q v (update S k (f v :: S k))
| (peek k f q) v S := step_aux q (f v (S k).head') S
| (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail)
| (load a q) v S := step_aux q (a v) S
| (branch f q₁ q₂) v S :=
cond (f v) (step_aux q₁ v S) (step_aux q₂ v S)
| (goto f) v S := ⟨some (f v), v, S⟩
| halt v S := ⟨none, v, S⟩
/-- The step function for the TM2 model. -/
@[simp] def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, S⟩ := none
| ⟨some l, v, S⟩ := some (step_aux (M l) v S)
/-- The (reflexive) reachability relation for the TM2 model. -/
def reaches (M : Λ → stmt) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (push k f q) := supports_stmt q
| (peek k f q) := supports_stmt q
| (pop k f q) := supports_stmt q
| (load a q) := supports_stmt q
| (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ v, l v ∈ S
| halt := true
open_locale classical
/-- The set of subtree statements in a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(push k f q) := insert Q (stmts₁ q)
| Q@(peek k f q) := insert Q (stmts₁ q)
| Q@(pop k f q) := insert Q (stmts₁ q)
| Q@(load a q) := insert Q (stmts₁ q)
| Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto l) := {Q}
| Q@halt := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂,
iterate 4 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } },
case TM2.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM2.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM2.stmt.goto : l { subst h, exact hs },
case TM2.stmt.halt { subst h, trivial }
end
/-- The set of statements accessible from initial set `S` of labels. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bUnion (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in
`S` jump only to other states in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T;
intro hs,
iterate 4 { exact IH _ _ hs },
case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) },
case TM2.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init (k) (L : list (Γ k)) : cfg :=
⟨some (default _), default _, update (λ _, []) k L⟩
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) :=
(eval (step M) (init k L)).map $ λ c, c.stk k
end
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := bool × ∀ k, option (Γ k)`, where:
* `bottom : bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n)
(hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) :
L.nth n k = S.reverse.nth n :=
begin
rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map],
cases S.reverse.nth n; refl
end
section
parameters {K : Type*} [decidable_eq K]
parameters {Γ : K → Type*}
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₂` := TM2.stmt Γ Λ σ
local notation `cfg₂` := TM2.cfg Γ Λ σ
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
@[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip
-- the decidable_eq assumption, and this is a local definition anyway so it's not important.
def Γ' := bool × ∀ k, option (Γ k)
instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩
instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' :=
prod.fintype _ _
/-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' :=
list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩)
theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L :=
begin
simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _,
generalize : list_blank.tail L = L',
refine L'.induction_on _, intro l, simp,
rw (_ : _ ∘ _ = id), {simp},
funext a, refl
end
theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) :
(add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) :=
begin
cases n; simp only [add_bottom,
list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons],
congr, symmetry, apply list_blank.map_modify_nth, intro, refl
end
theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n :=
by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl
theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff :=
by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl
theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt :=
by rw [add_bottom, list_blank.head_cons]; refl
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive st_act (k : K)
| push : (σ → Γ k) → st_act
| peek : (σ → option (Γ k) → σ) → st_act
| pop : (σ → option (Γ k) → σ) → st_act
instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩
section
open st_act
/-- The TM2 statement corresponding to a stack action. -/
@[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than
-- it is worth to omit the typeclass assumption without breaking the parameters
def st_run {k : K} : st_act k → stmt₂ → stmt₂
| (push f) := TM2.stmt.push k f
| (peek f) := TM2.stmt.peek k f
| (pop f) := TM2.stmt.pop k f
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ
| (push f) := v
| (peek f) := f v l.head'
| (pop f) := f v l.head'
/-- The effect of a stack action on the stack. -/
def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k)
| (push f) := f v :: l
| (peek f) := l
| (pop f) := l.tail
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
@[elab_as_eliminator] def {l} stmt_st_rec
{C : stmt₂ → Sort l}
(H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q))
(H₂ : Π a q (IH : C q), C (TM2.stmt.load a q))
(H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂))
(H₄ : Π l, C (TM2.stmt.goto l))
(H₅ : C TM2.stmt.halt) : ∀ n, C n
| (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q)
| (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q)
| (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q)
| (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q)
| (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂)
| (TM2.stmt.goto l) := H₄ _
| TM2.stmt.halt := H₅
theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) :
TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=
by rcases s with _|_|_; refl
end
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ' : Type (max u_1 u_2 u_3 u_4)
| normal : Λ → Λ'
| go (k) : st_act k → stmt₂ → Λ'
| ret : stmt₂ → Λ'
open Λ'
instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩
local notation `stmt₁` := TM1.stmt Γ' Λ' σ
local notation `cfg₁` := TM1.cfg Γ' Λ' σ
open TM1.stmt
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁
| (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q
| (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q
| (st_act.pop f) :=
branch (λ a _, a.1)
( load (λ a s, f s none) q )
( move dir.left $
load (λ a s, f s (a.2 k)) $
write (λ a s, (a.1, update a.2 k none)) q )
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def tr_init (k) (L : list (Γ k)) : list Γ' :=
let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in
(tt, L'.head.2) :: L'.tail
theorem step_run {k : K} (q v S) : ∀ s : st_act k,
TM2.step_aux (st_run s q) v S =
TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s))
| (st_act.push f) := rfl
| (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl
| (st_act.pop f) := rfl
/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def tr_normal : stmt₂ → stmt₁
| (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q)
| (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q)
| (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q)
| (TM2.stmt.load a q) := load (λ _, a) (tr_normal q)
| (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂)
| (TM2.stmt.goto l) := goto (λ a s, normal (l s))
| TM2.stmt.halt := halt
theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) :=
by rcases s with _|_|_; refl
open_locale classical
/-- The set of machine states accessible from an initial TM2 statement. -/
noncomputable def tr_stmts₁ : stmt₂ → finset Λ'
| Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.load a q) := tr_stmts₁ q
| Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂
| _ := ∅
theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q :=
by rcases s with _|_|_; unfold tr_stmts₁ st_run
theorem tr_respects_aux₂
{k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) :
let v' := st_var v (S k) o,
Sk' := st_write v (S k) o,
S' := update S k Sk' in
∃ (L' : list_blank (∀ k, option (Γ k))),
(∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧
TM1.step_aux (tr_st_act q o) v
((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) =
TM1.step_aux q v'
((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) :=
begin
dsimp only, simp, cases o;
simp only [st_write, st_var, tr_st_act, TM1.step_aux],
case TM2to1.st_act.push : f {
have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))),
dsimp only at this,
refine ⟨_, λ k', _, by rw [
tape.move_right_n_head, list.length, tape.mk'_nth_nat, this,
add_bottom_modify_nth (λ a, update a k (some (f v))),
nat.add_one, iterate_succ']⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [list.reverse_cons,
function.update_same, list_blank.nth_mk, list.inth, list.map],
{ rw [list.nth_le_nth, list.nth_le_append_right];
simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos',
list.length_append, lt_add_iff_pos_right, list.length] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth],
cases lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw gt_iff_lt at h,
rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } },
case TM2to1.st_act.peek : f {
rw function.update_eq_self,
use [L, hL], rw [tape.move_left_right], congr,
cases e : S k, {refl},
rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head,
tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e,
list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl },
case TM2to1.st_act.pop : f {
cases e : S k,
{ simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk',
list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil],
rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ },
{ refine ⟨_, λ k', _, by rw [
list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst,
cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat,
tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)),
add_bottom_modify_nth (λ a, update a k none),
add_bottom_nth_snd, stk_nth_val _ (hL k), e,
show (list.cons hd tl).reverse.nth tl.length = some hd,
by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl,
list.head', list.tail]⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [
function.update_same, list_blank.nth_mk, list.tail, list.inth],
{ rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons],
cases lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } } },
end
parameters (M : Λ → stmt₂)
include M
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr : Λ' → stmt₁
| (normal q) := tr_normal (M q)
| (go k s q) :=
branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s)
(move dir.right $ goto (λ _ _, go k s q))
| (ret q) :=
branch (λ a s, a.1) (tr_normal q)
(move dir.left $ goto (λ _ _, ret q))
local attribute [pp_using_anonymous_constructor] turing.TM1.cfg
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive tr_cfg : cfg₂ → cfg₁ → Prop
| mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) :
(∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) →
tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩
theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) :
reaches₀ (TM1.step tr)
⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩
⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
apply (IH (le_of_lt H)).tail,
rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr,
tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd,
option.mem_def],
rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse
end
theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) :
reaches₀ (TM1.step tr)
⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩
⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
refine reaches₀.head _ IH,
rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat,
add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl,
end
theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)}
(hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse)
(o : st_act k)
(IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))},
(∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) →
(∃ b, tr_cfg (TM2.step_aux q v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) :
∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q))
v (tape.mk' ∅ (add_bottom T))) b :=
begin
simp only [tr_normal_run, step_run],
have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _),
obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o,
have hret := tr_respects_aux₃ M _,
have := hgo.tail' rfl,
rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd,
stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)),
option.is_none, cond, hrun, TM1.step_aux] at this,
obtain ⟨c, gc, rc⟩ := IH hT',
refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩,
rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst],
exact rc,
end
local attribute [simp] respects TM2.step TM2.step_aux tr_normal
theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg :=
λ c₁ c₂ h, begin
cases h with l v S L hT, clear h,
cases l, {constructor},
simp only [TM2.step, respects, option.map_some'],
suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _,
from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩,
rw [tr],
revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros,
{ exact tr_respects_aux M hT s @IH },
{ exact IH _ hT },
{ unfold TM2.step_aux tr_normal TM1.step_aux,
cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }
end
theorem tr_cfg_init (k) (L : list (Γ k)) :
tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=
begin
rw (_ : TM1.init _ = _),
{ refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘),
list.nth_map, proj, pointed_map.mk_val],
by_cases k' = k,
{ subst k', simp only [function.update_same],
rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] },
{ simp only [function.update_noteq h],
rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth],
cases L.reverse.nth i; refl } },
{ rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl},
simp only [list.map_map, list.tail_cons, list.map], refl }
end
theorem tr_eval_dom (k) (L : list (Γ k)) :
(TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom :=
tr_eval_dom tr_respects (tr_cfg_init _ _)
theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂}
(H₁ : L₁ ∈ TM1.eval tr (tr_init k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))),
add_bottom L' = L₁ ∧
(∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧
S k = L₂ :=
begin
obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁,
obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂,
obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂,
cases part.mem_unique h₁ h₃,
exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩
end
/-- The support of a set of TM2 states in the TM2 emulator. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l)))
theorem tr_supports {S} (ss : TM2.supports M S) :
TM1.supports tr (tr_supp S) :=
⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩,
λ l' h, begin
suffices : ∀ q (ss' : TM2.supports_stmt S q)
(sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S),
TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧
(∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')),
{ rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩,
have := this _ (ss.2 l lS) (λ x hx,
finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩),
rcases finset.mem_insert.1 h with rfl | h;
[exact this.1, exact this.2 _ h] },
clear h l', refine stmt_st_rec _ _ _ _ _; intros,
{ -- stack op
rw TM2to1.supports_run at ss',
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at sub,
have hgo := sub _ (or.inl $ or.inl rfl),
have hret := sub _ (or.inl $ or.inr rfl),
cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂,
refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩,
rw [tr_stmts₁_run] at h,
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at h,
rcases h with ⟨rfl | rfl⟩ | h,
{ unfold TM1.supports_stmt TM2to1.tr,
rcases s with _|_|_,
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } },
{ unfold TM1.supports_stmt TM2to1.tr,
exact ⟨IH₁, λ _ _, hret⟩ },
{ exact IH₂ _ h } },
{ -- load
unfold TM2to1.tr_stmts₁ at ss' sub ⊢,
exact IH ss' sub },
{ -- branch
unfold TM2to1.tr_stmts₁ at sub,
cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂,
cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂,
refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩,
rw [tr_stmts₁] at h,
rcases finset.mem_union.1 h with h | h;
[exact IH₁₂ _ h, exact IH₂₂ _ h] },
{ -- goto
rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt,
unfold TM2.supports_stmt at ss',
exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ },
{ exact ⟨trivial, λ _, false.elim⟩ } -- halt
end⟩
end
end TM2to1
end turing
|
d00ac7c47e4b660eaf1a05f4790b9f9b57d1116d | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Elab/PatternVar.lean | 68fbcec77729d62721957e61e710117581bf9343 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,860 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.MatchPatternAttr
import Lean.Elab.Arg
import Lean.Elab.MatchAltView
namespace Lean.Elab.Term
open Meta
inductive PatternVar where
| localVar (userName : Name)
-- anonymous variables (`_`) are encoded using metavariables
| anonymousVar (mvarId : MVarId)
instance : ToString PatternVar := ⟨fun
| PatternVar.localVar x => toString x
| PatternVar.anonymousVar mvarId => s!"?m{mvarId.name}"⟩
/--
Create an auxiliary Syntax node wrapping a fresh metavariable id.
We use this kind of Syntax for representing `_` occurring in patterns.
The metavariables are created before we elaborate the patterns into `Expr`s. -/
private def mkMVarSyntax : TermElabM Syntax := do
let mvarId ← mkFreshId
return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]]
/-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/
def getMVarSyntaxMVarId (stx : Syntax) : MVarId :=
{ name := stx[0].getKind }
/-
Patterns define new local variables.
This module collect them and preprocess `_` occurring in patterns.
Recall that an `_` may represent anonymous variables or inaccessible terms
that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`.
After we elaborate the pattern, if the metavariable remains unassigned, we transform it into
a regular pattern variable. Otherwise, it becomes an inaccessible term.
Macros occurring in patterns are expanded before the `collectPatternVars` method is executed.
The following kinds of Syntax are handled by this module
- Constructor applications
- Applications of functions tagged with the `[matchPattern]` attribute
- Identifiers
- Anonymous constructors
- Structure instances
- Inaccessible terms
- Named patterns
- Tuple literals
- Type ascriptions
- Literals: num, string and char
-/
namespace CollectPatternVars
structure State where
found : NameSet := {}
vars : Array PatternVar := #[]
abbrev M := StateRefT State TermElabM
private def throwCtorExpected {α} : M α :=
throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected"
private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat :=
forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do
let mut result := 0
for p in ps do
let localDecl ← getLocalDecl p.fvarId!
if localDecl.binderInfo.isExplicit then
result := result+1
pure result
private def throwInvalidPattern {α} : M α :=
throwError "invalid pattern"
/-
An application in a pattern can be
1- A constructor application
The elaborator assumes fields are accessible and inductive parameters are not accessible.
2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`.
The elaborator assumes implicit arguments are not accessible and explicit ones are accessible.
-/
structure Context where
funId : Syntax
ctorVal? : Option ConstructorVal -- It is `some`, if constructor application
explicit : Bool
ellipsis : Bool
paramDecls : Array (Name × BinderInfo) -- parameters names and binder information
paramDeclIdx : Nat := 0
namedArgs : Array NamedArg
args : List Arg
newArgs : Array Syntax := #[]
deriving Inhabited
private def isDone (ctx : Context) : Bool :=
ctx.paramDeclIdx ≥ ctx.paramDecls.size
private def finalize (ctx : Context) : M Syntax := do
if ctx.namedArgs.isEmpty && ctx.args.isEmpty then
let fStx ← `(@$(ctx.funId):ident)
return Syntax.mkApp fStx ctx.newArgs
else
throwError "too many arguments"
private def isNextArgAccessible (ctx : Context) : Bool :=
let i := ctx.paramDeclIdx
match ctx.ctorVal? with
| some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible
| none =>
if h : i < ctx.paramDecls.size then
-- For `[matchPattern]` applications, only explicit parameters are accessible.
let d := ctx.paramDecls.get ⟨i, h⟩
d.2.isExplicit
else
false
private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context :=
let i := ctx.paramDeclIdx
let d := ctx.paramDecls[i]
(d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 })
private def processVar (idStx : Syntax) : M Syntax := do
unless idStx.isIdent do
throwErrorAt idStx "identifier expected"
let id := idStx.getId
unless id.eraseMacroScopes.isAtomic do
throwError "invalid pattern variable, must be atomic"
if (← get).found.contains id then
throwError "invalid pattern, variable '{id}' occurred more than once"
modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id }
return idStx
private def nameToPattern : Name → TermElabM Syntax
| Name.anonymous => `(Name.anonymous)
| Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _)
| Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _)
private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax :=
match stx[0].isNameLit? with
| some val => nameToPattern val
| none => throwIllFormedSyntax
private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do
nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[2])
partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do
let k := stx.getKind
if k == identKind then
processId stx
else if k == ``Lean.Parser.Term.app then
processCtorApp stx
else if k == ``Lean.Parser.Term.anonymousCtor then
let elems ← stx[1].getArgs.mapSepElemsM collect
return stx.setArg 1 <| mkNullNode elems
else if k == ``Lean.Parser.Term.structInst then
/-
```
leading_parser "{" >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optional ".."
>> optional (" : " >> termParser)
>> " }"
```
-/
let withMod := stx[1]
unless withMod.isNone do
throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns"
let fields ← stx[2].getArgs.mapM fun p => do
-- p is of the form (group (structInstField >> optional ", "))
let field := p[0]
-- leading_parser structInstLVal >> " := " >> termParser
let newVal ← collect field[2]
let field := field.setArg 2 newVal
pure <| field.setArg 0 field
return stx.setArg 2 <| mkNullNode fields
else if k == ``Lean.Parser.Term.hole then
let r ← mkMVarSyntax
modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r }
return r
else if k == ``Lean.Parser.Term.paren then
let arg := stx[1]
if arg.isNone then
return stx -- `()`
else
let t := arg[0]
let s := arg[1]
if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then
-- Ignore `s`, since it empty or it is a type ascription
let t ← collect t
let arg := arg.setArg 0 t
return stx.setArg 1 arg
else
return stx
else if k == ``Lean.Parser.Term.explicitUniv then
processCtor stx[0]
else if k == ``Lean.Parser.Term.namedPattern then
/- Recall that
def namedPattern := check... >> trailing_parser "@" >> termParser -/
let id := stx[0]
discard <| processVar id
let pat := stx[2]
let pat ← collect pat
`(_root_.namedPattern $id $pat)
else if k == ``Lean.Parser.Term.binop then
let lhs ← collect stx[2]
let rhs ← collect stx[3]
return stx.setArg 2 lhs |>.setArg 3 rhs
else if k == ``Lean.Parser.Term.inaccessible then
return stx
else if k == strLitKind then
return stx
else if k == numLitKind then
return stx
else if k == scientificLitKind then
return stx
else if k == charLitKind then
return stx
else if k == ``Lean.Parser.Term.quotedName then
/- Quoted names have an elaboration function associated with them, and they will not be macro expanded.
Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum`
instead of the constructors `Name.str` and `Name.num` -/
quotedNameToPattern stx
else if k == ``Lean.Parser.Term.doubleQuotedName then
/- Similar to previous case -/
doubleQuotedNameToPattern stx
else if k == choiceKind then
throwError "invalid pattern, notation is ambiguous"
else
throwInvalidPattern
where
processCtorApp (stx : Syntax) : M Syntax := do
let (f, namedArgs, args, ellipsis) ← expandApp stx true
processCtorAppCore f namedArgs args ellipsis
processCtor (stx : Syntax) : M Syntax := do
processCtorAppCore stx #[] #[] false
/- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/
processId (stx : Syntax) : M Syntax := do
match (← resolveId? stx "pattern" (withInfo := true)) with
| none => processVar stx
| some f => match f with
| Expr.const fName _ _ =>
match (← getEnv).find? fName with
| some (ConstantInfo.ctorInfo _) => processCtor stx
| some _ =>
if hasMatchPatternAttribute (← getEnv) fName then
processCtor stx
else
processVar stx
| none => throwCtorExpected
| _ => processVar stx
pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do
match arg with
| Arg.stx stx =>
let stx ← if accessible then collect stx else pure stx
return { ctx with newArgs := ctx.newArgs.push stx }
| _ => unreachable!
processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do
match ctx.args with
| [] =>
if ctx.ellipsis then
pushNewArg accessible ctx (Arg.stx (← `(_)))
else
throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}"
| arg::args =>
pushNewArg accessible { ctx with args := args } arg
processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do
if ctx.explicit then
processExplicitArg accessible ctx
else
pushNewArg accessible ctx (Arg.stx (← `(_)))
processCtorAppContext (ctx : Context) : M Syntax := do
if isDone ctx then
finalize ctx
else
let accessible := isNextArgAccessible ctx
let (d, ctx) := getNextParam ctx
match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with
| some idx =>
let arg := ctx.namedArgs[idx]
let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx }
let ctx ← pushNewArg accessible ctx arg.val
processCtorAppContext ctx
| none =>
let ctx ← match d.2 with
| BinderInfo.implicit => processImplicitArg accessible ctx
| BinderInfo.strictImplicit => processImplicitArg accessible ctx
| BinderInfo.instImplicit => processImplicitArg accessible ctx
| _ => processExplicitArg accessible ctx
processCtorAppContext ctx
processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do
let args := args.toList
let (fId, explicit) ← match f with
| `($fId:ident) => pure (fId, false)
| `(@$fId:ident) => pure (fId, true)
| _ => throwError "identifier expected"
let some (Expr.const fName _ _) ← resolveId? fId "pattern" (withInfo := true) | throwCtorExpected
let fInfo ← getConstInfo fName
let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do
let d ← getFVarLocalDecl x
return (d.userName, d.binderInfo)
match fInfo with
| ConstantInfo.ctorInfo val =>
processCtorAppContext
{ funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
| _ =>
if hasMatchPatternAttribute (← getEnv) fName then
processCtorAppContext
{ funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
else
throwCtorExpected
def main (alt : MatchAltView) : M MatchAltView := do
let patterns ← alt.patterns.mapM fun p => do
trace[Elab.match] "collecting variables at pattern: {p}"
collect p
return { alt with patterns := patterns }
end CollectPatternVars
def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do
let (alt, s) ← (CollectPatternVars.main alt).run {}
return (s.vars, alt)
/- Return the pattern variables in the given pattern.
Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/
def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do
let patternStx ← liftMacroM <| expandMacros patternStx
let (_, s) ← (CollectPatternVars.collect patternStx).run {}
return s.vars
def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do
let collect : CollectPatternVars.M Unit := do
for pattern in patterns do
discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern)
let (_, s) ← collect.run {}
return s.vars
def getPatternVarNames (pvars : Array PatternVar) : Array Name :=
pvars.filterMap fun
| PatternVar.localVar x => some x
| _ => none
end Lean.Elab.Term
|
77415e1b02210946943c33844f2297f8ec5271fc | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/algebra/complete_lattice.lean | 0f434638aaa13bbafb56d230da5b7927df1786ee | [
"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 | 14,898 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Complete lattices
TODO: define dual complete lattice and simplify proof of dual theorems.
-/
import algebra.lattice data.set.basic algebra.monotone
open set
variable {A : Type}
structure complete_lattice [class] (A : Type) extends lattice A :=
(Inf : set A → A)
(Sup : set A → A)
(Inf_le : ∀ {a : A} {s : set A}, a ∈ s → le (Inf s) a)
(le_Inf : ∀ {b : A} {s : set A}, (∀ (a : A), a ∈ s → le b a) → le b (Inf s))
(le_Sup : ∀ {a : A} {s : set A}, a ∈ s → le a (Sup s))
(Sup_le : ∀ {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → le a b), le (Sup s) b)
section
variable [complete_lattice A]
definition Inf (S : set A) : A := complete_lattice.Inf S
prefix `⨅ `:70 := Inf
definition Sup (S : set A) : A := complete_lattice.Sup S
prefix `⨆ `:65 := Sup
theorem Inf_le {a : A} {s : set A} (H : a ∈ s) : (Inf s) ≤ a := complete_lattice.Inf_le H
theorem le_Inf {b : A} {s : set A} (H : ∀ (a : A), a ∈ s → b ≤ a) : b ≤ Inf s :=
complete_lattice.le_Inf H
theorem le_Sup {a : A} {s : set A} (H : a ∈ s) : a ≤ Sup s := complete_lattice.le_Sup H
theorem Sup_le {b : A} {s : set A} (H : ∀ (a : A), a ∈ s → a ≤ b) : Sup s ≤ b :=
complete_lattice.Sup_le H
end
-- Minimal complete_lattice definition based just on Inf.
-- We later show that complete_lattice_Inf is a complete_lattice.
structure complete_lattice_Inf [class] (A : Type) extends weak_order A :=
(Inf : set A → A)
(Inf_le : ∀ {a : A} {s : set A}, a ∈ s → le (Inf s) a)
(le_Inf : ∀ {b : A} {s : set A}, (∀ (a : A), a ∈ s → le b a) → le b (Inf s))
-- Minimal complete_lattice definition based just on Sup.
-- We later show that complete_lattice_Sup is a complete_lattice.
structure complete_lattice_Sup [class] (A : Type) extends weak_order A :=
(Sup : set A → A)
(le_Sup : ∀ {a : A} {s : set A}, a ∈ s → le a (Sup s))
(Sup_le : ∀ {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → le a b), le (Sup s) b)
namespace complete_lattice_Inf
variable [C : complete_lattice_Inf A]
include C
definition Sup (s : set A) : A :=
Inf {b | ∀ a, a ∈ s → a ≤ b}
local prefix `⨅`:70 := Inf
local prefix `⨆`:65 := Sup
lemma le_Sup {a : A} {s : set A} : a ∈ s → a ≤ ⨆ s :=
suppose a ∈ s, le_Inf
(show ∀ (b : A), (∀ (a : A), a ∈ s → a ≤ b) → a ≤ b, from
take b, assume h, h a `a ∈ s`)
lemma Sup_le {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → a ≤ b) : ⨆ s ≤ b :=
Inf_le h
definition inf (a b : A) := ⨅ '{a, b}
definition sup (a b : A) := ⨆ '{a, b}
local infix `⊓` := inf
local infix `⊔` := sup
lemma inf_le_left (a b : A) : a ⊓ b ≤ a :=
Inf_le !mem_insert
lemma inf_le_right (a b : A) : a ⊓ b ≤ b :=
Inf_le (!mem_insert_of_mem !mem_insert)
lemma le_inf {a b c : A} : c ≤ a → c ≤ b → c ≤ a ⊓ b :=
assume h₁ h₂,
le_Inf (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(suppose x = a, begin subst x, exact h₁ end)
(suppose x ∈ '{b},
have x = b, from !eq_of_mem_singleton this,
begin subst x, exact h₂ end))
lemma le_sup_left (a b : A) : a ≤ a ⊔ b :=
le_Sup !mem_insert
lemma le_sup_right (a b : A) : b ≤ a ⊔ b :=
le_Sup (!mem_insert_of_mem !mem_insert)
lemma sup_le {a b c : A} : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
assume h₁ h₂,
Sup_le (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(suppose x = a, by subst x; assumption)
(suppose x ∈ '{b},
have x = b, from !eq_of_mem_singleton this,
by subst x; assumption))
end complete_lattice_Inf
-- Every complete_lattice_Inf is a complete_lattice_Sup
definition complete_lattice_Inf_to_complete_lattice_Sup [C : complete_lattice_Inf A] :
complete_lattice_Sup A :=
⦃ complete_lattice_Sup, C ⦄
-- Every complete_lattice_Inf is a complete_lattice
definition complete_lattice_Inf_to_complete_lattice [trans_instance] [C : complete_lattice_Inf A] :
complete_lattice A :=
⦃ complete_lattice, C ⦄
namespace complete_lattice_Sup
variable [C : complete_lattice_Sup A]
include C
definition Inf (s : set A) : A :=
Sup {b | ∀ a, a ∈ s → b ≤ a}
lemma Inf_le {a : A} {s : set A} : a ∈ s → Inf s ≤ a :=
suppose a ∈ s, Sup_le
(show ∀ (b : A), (∀ (a : A), a ∈ s → b ≤ a) → b ≤ a, from
take b, assume h, h a `a ∈ s`)
lemma le_Inf {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → b ≤ a) : b ≤ Inf s :=
le_Sup h
local prefix `⨅`:70 := Inf
local prefix `⨆`:65 := Sup
definition inf (a b : A) := ⨅ '{a, b}
definition sup (a b : A) := ⨆ '{a, b}
local infix `⊓` := inf
local infix `⊔` := sup
lemma inf_le_left (a b : A) : a ⊓ b ≤ a :=
Inf_le !mem_insert
lemma inf_le_right (a b : A) : a ⊓ b ≤ b :=
Inf_le (!mem_insert_of_mem !mem_insert)
lemma le_inf {a b c : A} : c ≤ a → c ≤ b → c ≤ a ⊓ b :=
assume h₁ h₂,
le_Inf (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(suppose x = a, begin subst x, exact h₁ end)
(suppose x ∈ '{b},
have x = b, from !eq_of_mem_singleton this,
begin subst x, exact h₂ end))
lemma le_sup_left (a b : A) : a ≤ a ⊔ b :=
le_Sup !mem_insert
lemma le_sup_right (a b : A) : b ≤ a ⊔ b :=
le_Sup (!mem_insert_of_mem !mem_insert)
lemma sup_le {a b c : A} : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
assume h₁ h₂,
Sup_le (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(assume H : x = a, by subst x; exact h₁)
(suppose x ∈ '{b},
have x = b, from !eq_of_mem_singleton this,
by subst x; exact h₂))
end complete_lattice_Sup
-- Every complete_lattice_Sup is a complete_lattice_Inf
definition complete_lattice_Sup_to_complete_lattice_Inf [C : complete_lattice_Sup A] :
complete_lattice_Inf A :=
⦃ complete_lattice_Inf, C ⦄
-- Every complete_lattice_Sup is a complete_lattice
section
definition complete_lattice_Sup_to_complete_lattice [trans_instance] [C : complete_lattice_Sup A] :
complete_lattice A :=
⦃ complete_lattice, C ⦄
end
section complete_lattice
variable [C : complete_lattice A]
include C
variable {f : A → A}
premise (mono : nondecreasing f)
theorem knaster_tarski : ∃ a, f a = a ∧ ∀ b, f b = b → a ≤ b :=
let a := ⨅ {u | f u ≤ u} in
have h₁ : f a = a, from
have ge : f a ≤ a, from
have ∀ b, b ∈ {u | f u ≤ u} → f a ≤ b, from
take b, suppose f b ≤ b,
have a ≤ b, from Inf_le this,
have f a ≤ f b, from mono this,
le.trans `f a ≤ f b` `f b ≤ b`,
le_Inf this,
have le : a ≤ f a, from
have f (f a) ≤ f a, from !mono ge,
have f a ∈ {u | f u ≤ u}, from this,
Inf_le this,
le.antisymm ge le,
have h₂ : ∀ b, f b = b → a ≤ b, from
take b,
suppose f b = b,
have b ∈ {u | f u ≤ u}, from
show f b ≤ b, by rewrite this,
Inf_le this,
exists.intro a (and.intro h₁ h₂)
theorem knaster_tarski_dual : ∃ a, f a = a ∧ ∀ b, f b = b → b ≤ a :=
let a := ⨆ {u | u ≤ f u} in
have h₁ : f a = a, from
have le : a ≤ f a, from
have ∀ b, b ∈ {u | u ≤ f u} → b ≤ f a, from
take b, suppose b ≤ f b,
have b ≤ a, from le_Sup this,
have f b ≤ f a, from mono this,
le.trans `b ≤ f b` `f b ≤ f a`,
Sup_le this,
have ge : f a ≤ a, from
have f a ≤ f (f a), from !mono le,
have f a ∈ {u | u ≤ f u}, from this,
le_Sup this,
le.antisymm ge le,
have h₂ : ∀ b, f b = b → b ≤ a, from
take b,
suppose f b = b,
have b ≤ f b, by rewrite this,
le_Sup this,
exists.intro a (and.intro h₁ h₂)
/- top and bot -/
definition bot : A := ⨅ univ
definition top : A := ⨆ univ
notation `⊥` := bot
notation `⊤` := top
lemma bot_le (a : A) : ⊥ ≤ a :=
Inf_le !mem_univ
lemma eq_bot {a : A} : (∀ b, a ≤ b) → a = ⊥ :=
assume h,
have a ≤ ⊥, from le_Inf (take b bin, h b),
le.antisymm this !bot_le
lemma le_top (a : A) : a ≤ ⊤ :=
le_Sup !mem_univ
lemma eq_top {a : A} : (∀ b, b ≤ a) → a = ⊤ :=
assume h,
have ⊤ ≤ a, from Sup_le (take b bin, h b),
le.antisymm !le_top this
/- general facts about complete lattices -/
lemma Inf_singleton {a : A} : ⨅'{a} = a :=
have ⨅'{a} ≤ a, from
Inf_le !mem_insert,
have a ≤ ⨅'{a}, from
le_Inf (take b, suppose b ∈ '{a}, have b = a, from eq_of_mem_singleton this, by rewrite this),
le.antisymm `⨅'{a} ≤ a` `a ≤ ⨅'{a}`
lemma Sup_singleton {a : A} : ⨆'{a} = a :=
have ⨆'{a} ≤ a, from
Sup_le (take b, suppose b ∈ '{a}, have b = a, from eq_of_mem_singleton this, by rewrite this),
have a ≤ ⨆'{a}, from
le_Sup !mem_insert,
le.antisymm `⨆'{a} ≤ a` `a ≤ ⨆'{a}`
lemma Inf_antimono {s₁ s₂ : set A} : s₁ ⊆ s₂ → ⨅ s₂ ≤ ⨅ s₁ :=
suppose s₁ ⊆ s₂, le_Inf (take a : A, suppose a ∈ s₁, Inf_le (mem_of_subset_of_mem `s₁ ⊆ s₂` `a ∈ s₁`))
lemma Sup_mono {s₁ s₂ : set A} : s₁ ⊆ s₂ → ⨆ s₁ ≤ ⨆ s₂ :=
suppose s₁ ⊆ s₂, Sup_le (take a : A, suppose a ∈ s₁, le_Sup (mem_of_subset_of_mem `s₁ ⊆ s₂` `a ∈ s₁`))
lemma Inf_union (s₁ s₂ : set A) : ⨅ (s₁ ∪ s₂) = (⨅s₁) ⊓ (⨅s₂) :=
have le₁ : ⨅ (s₁ ∪ s₂) ≤ (⨅s₁) ⊓ (⨅s₂), from
!le_inf
(le_Inf (take a : A, suppose a ∈ s₁, Inf_le (mem_unionl `a ∈ s₁`)))
(le_Inf (take a : A, suppose a ∈ s₂, Inf_le (mem_unionr `a ∈ s₂`))),
have le₂ : (⨅s₁) ⊓ (⨅s₂) ≤ ⨅ (s₁ ∪ s₂), from
le_Inf (take a : A, suppose a ∈ s₁ ∪ s₂,
or.elim this
(suppose a ∈ s₁,
have (⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₁, from !inf_le_left,
have ⨅s₁ ≤ a, from Inf_le `a ∈ s₁`,
le.trans `(⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₁` `⨅s₁ ≤ a`)
(suppose a ∈ s₂,
have (⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₂, from !inf_le_right,
have ⨅s₂ ≤ a, from Inf_le `a ∈ s₂`,
le.trans `(⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₂` `⨅s₂ ≤ a`)),
le.antisymm le₁ le₂
lemma Sup_union (s₁ s₂ : set A) : ⨆ (s₁ ∪ s₂) = (⨆s₁) ⊔ (⨆s₂) :=
have le₁ : ⨆ (s₁ ∪ s₂) ≤ (⨆s₁) ⊔ (⨆s₂), from
Sup_le (take a : A, suppose a ∈ s₁ ∪ s₂,
or.elim this
(suppose a ∈ s₁,
have a ≤ ⨆s₁, from le_Sup `a ∈ s₁`,
have ⨆s₁ ≤ (⨆s₁) ⊔ (⨆s₂), from !le_sup_left,
le.trans `a ≤ ⨆s₁` `⨆s₁ ≤ (⨆s₁) ⊔ (⨆s₂)`)
(suppose a ∈ s₂,
have a ≤ ⨆s₂, from le_Sup `a ∈ s₂`,
have ⨆s₂ ≤ (⨆s₁) ⊔ (⨆s₂), from !le_sup_right,
le.trans `a ≤ ⨆s₂` `⨆s₂ ≤ (⨆s₁) ⊔ (⨆s₂)`)),
have le₂ : (⨆s₁) ⊔ (⨆s₂) ≤ ⨆ (s₁ ∪ s₂), from
!sup_le
(Sup_le (take a : A, suppose a ∈ s₁, le_Sup (mem_unionl `a ∈ s₁`)))
(Sup_le (take a : A, suppose a ∈ s₂, le_Sup (mem_unionr `a ∈ s₂`))),
le.antisymm le₁ le₂
lemma Inf_empty_eq_Sup_univ : ⨅ (∅ : set A) = ⨆ univ :=
have le₁ : ⨅ (∅ : set A) ≤ ⨆ univ, from
le_Sup !mem_univ,
have le₂ : ⨆ univ ≤ ⨅ ∅, from
le_Inf (take a : A, suppose a ∈ ∅, absurd this !not_mem_empty),
le.antisymm le₁ le₂
lemma Sup_empty_eq_Inf_univ : ⨆ (∅ : set A) = ⨅ univ :=
have le₁ : ⨆ (∅ : set A) ≤ ⨅ univ, from
Sup_le (take a, suppose a ∈ ∅, absurd this !not_mem_empty),
have le₂ : ⨅ univ ≤ ⨆ (∅ : set A), from
Inf_le !mem_univ,
le.antisymm le₁ le₂
lemma Sup_pair (a b : A) : Sup '{a, b} = sup a b :=
by rewrite [insert_eq, Sup_union, *Sup_singleton]
lemma Inf_pair (a b : A) : Inf '{a, b} = inf a b :=
by rewrite [insert_eq, Inf_union, *Inf_singleton]
end complete_lattice
/- complete lattice instances -/
section
open eq.ops complete_lattice
definition complete_lattice_fun [instance] (A B : Type) [complete_lattice B] :
complete_lattice (A → B) :=
⦃ complete_lattice, lattice_fun A B,
Inf := λS x, Inf ((λf, f x) ' S),
le_Inf := take f S H x,
le_Inf (take y Hy, obtain g `g ∈ S` `g x = y`, from Hy, `g x = y` ▸ H g `g ∈ S` x),
Inf_le := take f S `f ∈ S` x,
Inf_le (exists.intro f (and.intro `f ∈ S` rfl)),
Sup := λS x, Sup ((λf, f x) ' S),
le_Sup := take f S `f ∈ S` x,
le_Sup (exists.intro f (and.intro `f ∈ S` rfl)),
Sup_le := take f S H x,
Sup_le (take y Hy, obtain g `g ∈ S` `g x = y`, from Hy, `g x = y` ▸ H g `g ∈ S` x)
⦄
section
open classical -- Prop and set are only in the classical setting a complete lattice
definition complete_lattice_Prop [instance] : complete_lattice Prop :=
⦃ complete_lattice, lattice_Prop,
Inf := λS, false ∉ S,
le_Inf := take x S H Hx Hf,
H _ Hf Hx,
Inf_le := take x S Hx Hf,
(classical.cases_on x (take x, true.intro) Hf) Hx,
Sup := λS, true ∈ S,
le_Sup := take x S Hx H,
iff_subst (iff.intro (take H, true.intro) (take H', H)) Hx,
Sup_le := take x S H Ht,
H _ Ht true.intro
⦄
lemma sInter_eq_Inf_fun {A : Type} (S : set (set A)) : ⋂₀ S = @Inf (A → Prop) _ S :=
funext (take x,
calc
(⋂₀ S) x = ∀₀ P ∈ S, P x : rfl
... = ¬ (∃₀ P ∈ S, P x = false) :
begin
rewrite not_bounded_exists,
apply bounded_forall_congr,
intros,
rewrite eq_false,
rewrite not_not_iff
end
... = @Inf (A → Prop) _ S x : rfl)
lemma sUnion_eq_Sup_fun {A : Type} (S : set (set A)) : ⋃₀ S = @Sup (A → Prop) _ S :=
funext (take x,
calc
(⋃₀ S) x = ∃₀ P ∈ S, P x : rfl
... = (∃₀ P ∈ S, P x = true) :
begin
apply bounded_exists_congr,
intros,
rewrite eq_true
end
... = @Sup (A → Prop) _ S x : rfl)
definition complete_lattice_set [instance] (A : Type) : complete_lattice (set A) :=
⦃ complete_lattice,
le := subset,
le_refl := @le_refl (A → Prop) _,
le_trans := @le_trans (A → Prop) _,
le_antisymm := @le_antisymm (A → Prop) _,
inf := inter,
sup := union,
inf_le_left := @inf_le_left (A → Prop) _,
inf_le_right := @inf_le_right (A → Prop) _,
le_inf := @le_inf (A → Prop) _,
le_sup_left := @le_sup_left (A → Prop) _,
le_sup_right := @le_sup_right (A → Prop) _,
sup_le := @sup_le (A → Prop) _,
Inf := sInter,
Sup := sUnion,
le_Inf := begin intros X S H, rewrite sInter_eq_Inf_fun, apply (@le_Inf (A → Prop) _), exact H end,
Inf_le := begin intros X S H, rewrite sInter_eq_Inf_fun, apply (@Inf_le (A → Prop) _), exact H end,
le_Sup := begin intros X S H, rewrite sUnion_eq_Sup_fun, apply (@le_Sup (A → Prop) _), exact H end,
Sup_le := begin intros X S H, rewrite sUnion_eq_Sup_fun, apply (@Sup_le (A → Prop) _), exact H end
⦄
end
end
|
aec68c392635799b43b787d39dabf27fac583d51 | 856e2e1615a12f95b551ed48fa5b03b245abba44 | /src/measure_theory/measure_space.lean | a0e818be3444f84b54292c6bf94fdfc34f339f68 | [
"Apache-2.0"
] | permissive | pimsp/mathlib | 8b77e1ccfab21703ba8fbe65988c7de7765aa0e5 | 913318ca9d6979686996e8d9b5ebf7e74aae1c63 | refs/heads/master | 1,669,812,465,182 | 1,597,133,610,000 | 1,597,133,610,000 | 281,890,685 | 1 | 0 | null | 1,595,491,577,000 | 1,595,491,576,000 | null | UTF-8 | Lean | false | false | 54,401 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import measure_theory.outer_measure
import order.filter.countable_Inter
/-!
# Measure spaces
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
In the first part of the file we define operations on arbitrary functions defined on measurable
sets.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open classical set filter finset function
open_locale classical topological_space big_operators filter
universes u v w x
namespace measure_theory
/- We first consider operations on arbitrary functions defined on measurable sets. -/
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- We can trivially extend a function defined on measurable sets to all sets by defining it to be
`∞` on the non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑'i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- Given an arbitrary function on measurable sets, we can define the outer measure corresponding to
it (this is the unique maximal outer measure that is at most `m` on measurable sets). -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑'i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑'i, measure' (f i)) :=
begin
rw [← encodable.Union_decode2, ← tsum_Union_decode2],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (encodable.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
/-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider
`m.trim`, the unique maximal outer measure less than that function. -/
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
@[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp only [trim_eq_infi', add_apply],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
lemma exists_is_measurable_superset_of_trim_eq_zero
{m : outer_measure α} {s : set α} (h : m.trim s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ m t = 0 :=
begin
erw [trim_eq_infi, infi_eq_bot] at h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ m t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ := (ennreal.inv_pos.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa only [infi_lt_iff, exists_prop] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine le_antisymm _ (zero_le _),
refine le_of_tendsto_of_tendsto tendsto_const_nhds
ennreal.tendsto_inv_nat_nhds_zero (eventually_of_forall $ assume n, _),
exact le_trans (m.mono' $ Inter_subset _ _) (le_of_lt (ht n).2.2)
end
theorem trim_smul (c : ennreal) (m : outer_measure α) :
(c • m).trim = c • m.trim :=
begin
ext1 s,
simp only [trim_eq_infi', smul_apply],
haveI : nonempty {t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ _, is_measurable.univ⟩⟩,
refine ennreal.infi_mul_left (assume hc hs, _),
rw ← trim_eq_infi' at hs,
simpa [and_assoc] using exists_is_measurable_superset_of_trim_eq_zero hs
end
end outer_measure
/-- A measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure. -/
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑'i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
/-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑' i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
lemma to_outer_measure_injective {α} [measurable_space α] :
injective (to_outer_measure : measure α → outer_measure α) :=
λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h }
@[ext] lemma ext {α} [measurable_space α] {μ₁ μ₂ : measure α}
(h : ∀s, is_measurable s → μ₁ s = μ₂ s) :
μ₁ = μ₂ :=
to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed]
end measure
section
variables {α : Type*} {β : Type*} {ι : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α}
{s s₁ s₂ : set α}
@[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl
lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty :=
ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h])
lemma exists_is_measurable_superset_iff_measure_eq_zero {s : set α} :
(∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 :=
⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union],
apply measure_Union_le
end
lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion_le s.countable_to_set f
end
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑'i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.ext_val ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑' s:S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f))
(hm : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion s.countable_to_set hd hm
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
(∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf,
finset.bUnion_preimage_singleton]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i))
(H : pairwise_on ↑s (disjoint on t)) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i))
(H : pairwise (disjoint on s)) :
(∑' i, μ (s i)) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij))
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α}
(hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
exact λ i j hij x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι}
{t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
have : ∀ t : finset ℕ, ∃ n, t ⊆ finset.range (n + 1),
from λ t, (finset.exists_nat_subset_range t).imp (λ n hn, finset.subset.trans hn $
finset.range_mono $ (le_add_iff_nonneg_right _).2 (zero_le 1)),
rw [← Union_disjointed, measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_sum' _ this],
congr' 1, ext1 n,
rw [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _)
(λ n _, is_measurable.disjointed h n)],
convert congr_arg μ (Union_disjointed_of_mono hs n),
ext, simp
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
@[simp] lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma le_to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α]
(h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.trim_ge s
@[simp] lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl
lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 :=
ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty]
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply (μ₁ μ₂ : measure α) (s) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure
instance : has_scalar ennreal (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left],
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
instance : semimodule ennreal (measure α) :=
injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
cases t.eq_empty_or_nonempty with ht ht, by simp [ht],
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
coe_to_outer_measure, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : complete_lattice (measure α) :=
{ bot := 0,
bot_le := assume a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, Inf_le, λ _, le_Inf⟩) }
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected lemma add_le_add_left {μ₁ μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) :
ν + μ₁ ≤ ν + μ₂ :=
λ s hs, add_le_add_left (hμ s hs) _
protected lemma add_le_add_right {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) :
μ₁ + ν ≤ μ₂ + ν :=
λ s hs, add_le_add_right (hμ s hs) _
protected lemma add_le_add {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) {ν₁ ν₂ : measure α} (hν : ν₁ ≤ ν₂) :
μ₁ + ν₁ ≤ μ₂ + ν₂ :=
λ s hs, add_le_add (hμ s hs) (hν s hs)
protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le
protected lemma le_add_left {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
end
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ennreal] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} {s : set β} (hs : is_measurable s) :
lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map (f : α → β) : measure α →ₗ[ennreal] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
map f μ s = μ (f ⁻¹' s) :=
by simp [map, dif_pos hf, hs]
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap (f : α → β) : measure β →ₗ[ennreal] measure α :=
if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comap_apply (f : α → β) (hfi : injective f)
(hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β)
{s : set α} (hs : is_measurable s) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/
def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
@[simp] lemma restrict_apply {s t : set α} (ht : is_measurable t) :
μ.restrict s t = μ (t ∩ s) :=
by simp [← restrictₗ_apply, restrictₗ, ht]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp }
@[simp] lemma restrict_add (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
lemma restrict_apply_eq_zero {s t : set α} (ht : is_measurable t) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma restrict_apply_eq_zero' {s t : set α} (hs : is_measurable s) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
begin
refine ⟨λ h, le_zero_iff_eq.1 (h ▸ le_restrict_apply _ _), λ h, _⟩,
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩,
apply measure_mono_null ((inter_subset _ _ _).1 htt'),
rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self,
set.empty_union],
exact measure_mono_null (inter_subset_left _ _) ht'0
end
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs]
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_union_apply {s s' t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s)
(hs' : is_measurable s') (ht : is_measurable t) :
μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t :=
begin
simp only [restrict_apply, ht, set.inter_union_distrib_left],
exact measure_union h (ht.inter hs) (ht.inter hs'),
end
lemma restrict_union {s t : set α} (h : disjoint s t) (hs : is_measurable s)
(ht : is_measurable t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht'
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right)
(λ i, ht.inter (hm i))
end
lemma map_comap_subtype_coe {s : set α} (hs : is_measurable s) :
(map (coe : s → α)).comp (comap coe) = restrictₗ s :=
linear_map.ext $ λ μ, ext $ λ t ht,
by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply,
map_apply measurable_subtype_coe ht,
comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _
(measurable_subtype_coe ht), subtype.image_preimage_coe]
/-- Restriction of a measure to a subset is monotone
both in set and in measure. -/
@[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
lemma dirac_apply' (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = s.indicator 1 a :=
(dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] }
lemma dirac_apply_of_mem {a : α} {s : set α} (h : a ∈ s) :
dirac a s = 1 :=
begin
rw [measure_eq_infi, infi_subtype', infi_subtype'],
convert infi_const,
{ ext1 ⟨⟨t, hst⟩, ht⟩,
dsimp only [subtype.coe_mk] at *,
simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] },
{ exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ }
end
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
@[simp] lemma sum_apply {ι : Type*} (f : ι → measure α) {s : set α} (hs : is_measurable s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma restrict_Union {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht]
lemma restrict_Union_le {ι} [encodable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
ext $ λ s hs, by simp [hs, tsum_fintype]
@[simp] lemma restrict_sum {ι : Type*} (μ : ι → measure α) {s : set α} (hs : is_measurable s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma count_apply {s : set α} (hs : is_measurable s) :
count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def ae (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ = 0},
univ_sets := by simp,
inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq];
exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ⊤},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite {s : set α} : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl
end measure
variables {α : Type*} {β : Type*} [measurable_space α] {μ : measure α}
notation `∀ᵐ` binders `∂` μ `, ` r:(scoped P, μ.ae.eventually P) := r
notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[μ.ae] g
notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[μ.ae] g
lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl
lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl
lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s :=
by simp only [ae_iff, not_not, set_of_mem_eq]
lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀a, p a) → ∀ᵐ a ∂ μ, p a :=
eventually_of_forall
instance : countable_Inter_filter μ.ae :=
⟨begin
intros S hSc hS,
simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢,
haveI := hSc.to_encodable,
exact measure_Union_null (subtype.forall.2 hS)
end⟩
lemma ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ᵐ a ∂ μ, ∀i, p a i) ↔ (∀i, ∀ᵐ a ∂ μ, p a i) :=
eventually_countable_forall
lemma ae_ball_iff {ι} {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} :
(∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› :=
eventually_countable_ball hS
lemma ae_eq_refl (f : α → β) : f =ᵐ[μ] f := eventually_eq.refl _ _
lemma ae_eq_symm {f g : α → β} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f :=
h.symm
lemma ae_eq_trans {f g h: α → β} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) :
f =ᵐ[μ] h :=
h₁.trans h₂
lemma mem_ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
s ∈ (measure.map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, measure.map_apply hf hs.compl, preimage_compl]
lemma ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{p : β → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ y ∂ (measure.map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
@[simp] lemma ae_restrict_eq {s : set α} (hs : is_measurable s):
(μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, measure.restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
lemma mem_dirac_ae_iff {a : α} {s : set α} (hs : is_measurable s) :
s ∈ (measure.dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, measure.dirac_apply, hs.compl, indicator_apply, *]
lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(measure.dirac a), p x) ↔ p a :=
mem_dirac_ae_iff hp
lemma eventually_eq_dirac [measurable_space β] [measurable_singleton_class β] {a : α} {f : α → β}
(hf : measurable f) :
f =ᵐ[measure.dirac a] const α (f a) :=
(eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl
lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (measure.dirac a).ae = pure a :=
begin
ext s,
simp only [mem_ae_iff, mem_pure_sets],
by_cases ha : a ∈ s,
{ simp only [ha, iff_true],
rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha,
refine measure_mono_null ha _,
simp [measure.dirac_apply a (is_measurable_singleton a).compl] },
{ simp only [ha, iff_false, measure.dirac_apply_of_mem (mem_compl ha)],
exact one_ne_zero }
end
lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → β) :
f =ᵐ[measure.dirac a] const α (f a) :=
by { rw [dirac_ae_eq], show f a = f a, refl }
lemma measure_diff_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) :
μ (s \ t) = 0 :=
flip measure_mono_null H $ λ x hx H, hx.2 (H hx.1)
/-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/
lemma measure_le_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) :
μ s ≤ μ t :=
calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t
... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm]
... ≤ μ t + μ (s \ t) : measure_union_le _ _
... = μ t : by rw [measure_diff_of_ae_imp H, add_zero]
/-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/
lemma measure_congr {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s ↔ x ∈ t) : μ s = μ t :=
le_antisymm (measure_le_of_ae_imp $ H.mono $ λ x, iff.mp)
(measure_le_of_ae_imp $ H.mono $ λ x, iff.mpr)
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ sᶜ :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
/-- The measurable space of all null measurable sets. -/
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp,
clear _inst,
resetI,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(volume : measure α)
end prio
export measure_space (volume)
/-- `volume` is the canonical measure on `α`. -/
add_decl_doc volume
section measure_space
variables {α : Type*} {ι : Type*} [measure_space α] {s₁ s₂ : set α}
notation `∀ᵐ` binders `, ` r:(scoped P, volume.ae.eventually P) := r
end measure_space
end measure_theory
|
47e7fb77269f1896727cdb87fae20c0d680dc8c5 | 693339a8c7c9c4b3a7ef726ed5df540f77a2ee84 | /02-lean.lean | ac95c23fd217db0db9e48b53edd8a82ffb721443 | [
"MIT"
] | permissive | Jerrycaster/lean | d02d5f39131461758310b6dac20570ebdcb46913 | c2f7e07ad8415e0618bba2e7497f360117d238bc | refs/heads/master | 1,592,160,820,153 | 1,562,540,316,000 | 1,562,540,316,000 | 195,093,506 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,155 | lean | #check λ x : ℕ, x + 5
#reduce (λ x : ℕ, x + 5) 5
#reduce (λ x : ℕ, x / 5) 5
#reduce (λ x : ℕ, x - 10) 5
#reduce (λ x : ℤ, x - 10) 5
constants α β γ : Type
constant f : α → β
constant g : β → γ
constant h : α → α
constant H : γ → α
constants (a : α) (b : β) (c : γ)
#check λ x : α, b -- λ (x : α), b : α → β
#check (λ x : α, b) a -- (λ (x : α), b) a : β
#check (λ x : α, x) a -- (λ (x : α), x) a : α
#check (λ x : α, b) (h a) -- (λ (x : α), b) (h a) : β
#check (λ x : α, b) (H c) -- (λ (x : α), b) (H c) : β, 14 and 15 are the same
#check (λ x : α, g (f x)) (h (h (h a))) -- (λ (x : α), g (f x)) (h (h (h a))) : γ
#check λ /-(α β γ : Type)-/ (g : β → γ) (f : α → β) (x : α), g (f x) /- returns the composition of
g with f, : (β → γ) → (α → β) → α → γ -/
#check (λ (v : β → γ) (u : α → β) (x : α), v (u x)) g f a
#check g (f a)
#check (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q), v (u x)) α β γ g f a
#reduce (λ x : α, x) a -- identity function, f(x)=x
#reduce (λ x : α, b) a -- constant function, f(x)=b
#reduce (λ x : α, b) (h (h a))
#check c
#check (λ x : α, g (f x)) a -- (λ (x : α), g (f x)) a : γ,
#reduce (λ x : α, g (f x)) a -- g (f a)
#reduce (λ (v : β → γ) (u : α → β) (x : α), v (u x)) g f a -- g (f a)
#reduce (λ (φ ϕ ψ : Type) (v : ϕ → ψ) (u : φ → ϕ) (x : φ), v (u x)) α β γ g f a -- g (f a)
-- above expression assigns (φ ϕ ψ) to (α β γ) respectively, the functions v, u to g, f respectively,
-- and x in φ to a
constants m n : ℕ
constant b' : bool
#reduce (m, n).fst -- m
#reduce (m, n).snd -- n
#reduce tt && ff -- ff
#reduce tt && tt -- tt
#reduce ff && ff -- ff
#reduce ff && tt -- ff
#reduce ff && b' -- ff
#reduce b' && ff -- b' && ff
#print "lean can compute as well"
#eval 3 + 4
#reduce (λ (ψ : Type) (u : ψ → ψ) (x : ψ), u (u x)) α h a
#reduce λ (u : α → α) (x : α), h (h a)
#reduce λ (ψ : Type) (y : ψ) (u : ψ → ψ), h (h a) |
c0463939f2d72b42944a99ba07d9528f7844abe0 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch5/ex0217.lean | 4912599e858a9d9f5b8854983bd46bd2d1cf50d7 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 88 | lean | example : 3 = 3 :=
begin
generalize : 3 = x,
revert x,
intro y,
reflexivity
end
|
0299fa3fa9d8f0846be8c878863c89379eb45757 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/direct_sum_auto.lean | 630ded420ae32ea38997bea1d0f9a506cc8e034f | [] | 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,946 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.dfinsupp
import Mathlib.PostPort
universes v w u₁ u_1
namespace Mathlib
/-!
# 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
-/
/-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`.
Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/
def direct_sum (ι : Type v) (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] :=
dfinsupp fun (i : ι) => β i
namespace direct_sum
protected instance add_comm_group {ι : Type v} (β : ι → Type w) [(i : ι) → add_comm_group (β i)] :
add_comm_group (direct_sum ι β) :=
dfinsupp.add_comm_group
@[simp] theorem sub_apply {ι : Type v} {β : ι → Type w} [(i : ι) → add_comm_group (β i)]
(g₁ : direct_sum ι fun (i : ι) => β i) (g₂ : direct_sum ι fun (i : ι) => β i) (i : ι) :
coe_fn (g₁ - g₂) i = coe_fn g₁ i - coe_fn g₂ i :=
dfinsupp.sub_apply g₁ g₂ i
@[simp] theorem zero_apply {ι : Type v} (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] (i : ι) :
coe_fn 0 i = 0 :=
rfl
@[simp] theorem add_apply {ι : Type v} {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)]
(g₁ : direct_sum ι fun (i : ι) => β i) (g₂ : direct_sum ι fun (i : ι) => β i) (i : ι) :
coe_fn (g₁ + g₂) i = coe_fn g₁ i + coe_fn g₂ i :=
dfinsupp.add_apply g₁ g₂ i
/-- `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 {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)]
(s : finset ι) : ((i : ↥↑s) → β (subtype.val i)) →+ direct_sum ι fun (i : ι) => β i :=
add_monoid_hom.mk (dfinsupp.mk s) sorry sorry
/-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/
def of {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)]
(i : ι) : β i →+ direct_sum ι fun (i : ι) => β i :=
dfinsupp.single_add_hom β i
theorem mk_injective {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] (s : finset ι) : function.injective ⇑(mk β s) :=
dfinsupp.mk_injective s
theorem of_injective {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] (i : ι) : function.injective ⇑(of β i) :=
dfinsupp.single_injective
protected theorem induction_on {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {C : (direct_sum ι fun (i : ι) => β i) → Prop}
(x : direct_sum ι fun (i : ι) => β i) (H_zero : C 0)
(H_basic : ∀ (i : ι) (x : β i), C (coe_fn (of β i) x))
(H_plus : ∀ (x y : direct_sum ι fun (i : ι) => β i), C x → C y → C (x + y)) : C x :=
dfinsupp.induction x H_zero
fun (i : ι) (b : β i) (f : dfinsupp fun (i : ι) => (fun (i : ι) => (fun (i : ι) => β i) i) i)
(h1 : coe_fn f i = 0) (h2 : b ≠ 0) (ih : C f) =>
H_plus (dfinsupp.single i b) f (H_basic i b) ih
/-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ`
induced by a family `φ` of homomorphisms `β i → γ`. -/
def to_add_monoid {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (φ : (i : ι) → β i →+ γ) :
(direct_sum ι fun (i : ι) => β i) →+ γ :=
coe_fn dfinsupp.lift_add_hom φ
@[simp] theorem to_add_monoid_of {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (φ : (i : ι) → β i →+ γ)
(i : ι) (x : β i) : coe_fn (to_add_monoid φ) (coe_fn (of β i) x) = coe_fn (φ i) x :=
dfinsupp.lift_add_hom_apply_single φ i x
theorem to_add_monoid.unique {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ]
(ψ : (direct_sum ι fun (i : ι) => β i) →+ γ) (f : direct_sum ι fun (i : ι) => β i) :
coe_fn ψ f = coe_fn (to_add_monoid fun (i : ι) => add_monoid_hom.comp ψ (of β i)) f :=
sorry
/-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i`
induced by a family `φ` of homomorphisms `γ → β i`.
Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/
def from_add_monoid {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] :
(direct_sum ι fun (i : ι) => γ →+ β i) →+ γ →+ direct_sum ι fun (i : ι) => β i :=
to_add_monoid fun (i : ι) => coe_fn add_monoid_hom.comp_hom (of β i)
@[simp] theorem from_add_monoid_of {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (i : ι) (f : γ →+ β i) :
coe_fn from_add_monoid (coe_fn (of (fun (i : ι) => γ →+ β i) i) f) =
add_monoid_hom.comp (of (fun (i : ι) => β i) i) f :=
sorry
theorem from_add_monoid_of_apply {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w}
[(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (i : ι) (f : γ →+ β i)
(x : γ) :
coe_fn (coe_fn from_add_monoid (coe_fn (of (fun (i : ι) => γ →+ β i) i) f)) x =
coe_fn (of (fun (i : ι) => β i) i) (coe_fn f x) :=
sorry
/-- `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 {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w)
[(i : ι) → add_comm_monoid (β i)] (S : set ι) (T : set ι) (H : S ⊆ T) :
(direct_sum ↥S fun (i : ↥S) => β ↑i) →+ direct_sum ↥T fun (i : ↥T) => β ↑i :=
to_add_monoid fun (i : ↥S) => of (fun (i : Subtype T) => β ↑i) { val := ↑i, property := sorry }
/-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/
protected def id (M : Type v) (ι : optParam (Type u_1) PUnit) [add_comm_monoid M] [unique ι] :
(direct_sum ι fun (_x : ι) => M) ≃+ M :=
add_equiv.mk ⇑(to_add_monoid fun (_x : ι) => add_monoid_hom.id M)
⇑(of (fun (_x : ι) => M) Inhabited.default) sorry sorry sorry
end Mathlib |
70b2d1a5f083cd5f891e55948a24d6272a126f0a | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/relations/partition_challenge.lean | a522af5a416c4f6722ec96a5ce1fd6e469977fb8 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 7,638 | lean | import tactic
/-!
# The partition challenge!
Prove that equivalence relations on α are the same as partitions of α.
Three sections:
1) partitions
2) equivalence classes
3) the challenge
## Overview
Say `α` is a type, and `R` is a binary relation on `α`.
The following things are already in Lean:
reflexive R := ∀ (x : α), R x x
symmetric R := ∀ ⦃x y : α⦄, R x y → R y x
transitive R := ∀ ⦃x y z : α⦄, R x y → R y z → R x z
equivalence R := reflexive R ∧ symmetric R ∧ transitive R
In the file below, we will define partitions of `α` and "build some
interface" (i.e. prove some propositions). We will define
equivalence classes and do the same thing.
Finally, we will prove that there's a bijection between
equivalence relations on `α` and partitions of `α`.
-/
/-
# 1) Partitions
We define a partition, and prove some easy lemmas.
-/
/-
## Definition of a partition
Let `α` be a type. A *partition* on `α` is defined to be
the following data:
1) A set C of subsets of α, called "blocks".
2) A hypothesis (i.e. a proof!) that all the blocks are non-empty.
3) A hypothesis that every term of type α is in one of the blocks.
4) A hypothesis that two blocks with non-empty intersection are equal.
-/
/-- The structure of a partition on a Type α. -/
@[ext] structure partition (α : Type) :=
(C : set (set α))
(Hnonempty : ∀ X ∈ C, (X : set α).nonempty)
(Hcover : ∀ a, ∃ X ∈ C, a ∈ X)
(Hdisjoint : ∀ X Y ∈ C, (X ∩ Y : set α).nonempty → X = Y)
-- docstrings
/-- The set of blocks. -/
add_decl_doc partition.C
/-- Every element of a block is nonempty. -/
add_decl_doc partition.Hnonempty
/-- The blocks cover the type they partition -/
add_decl_doc partition.Hcover
/-- Two blocks which share an element are equal -/
add_decl_doc partition.Hdisjoint
/-
## Basic interface for partitions
-/
namespace partition
-- let α be a type, and fix a partition P on α. Let X and Y be subsets of α.
variables {α : Type} {P : partition α} {X Y : set α}
/-- If X and Y are blocks, and a is in X and Y, then X = Y. -/
theorem eq_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a : α} (haX : a ∈ X)
(haY : a ∈ Y) : X = Y :=
-- Proof: follows immediately from the disjointness hypothesis.
P.Hdisjoint _ hX _ hY ⟨a, haX, haY⟩
/-- If a is in two blocks X and Y, and if b is in X,
then b is in Y (as X=Y) -/
theorem mem_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a b : α}
(haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y :=
begin
sorry,
end
/-- Every term of type `α` is in one of the blocks for a partition `P`. -/
theorem mem_block (a : α) : ∃ X : set α, X ∈ P.C ∧ a ∈ X :=
begin
sorry,
end
end partition
/-
# 2) Equivalence classes.
We define equivalence classes and prove a few basic results about them.
-/
section equivalence_classes
/-!
## Definition of equivalence classes
-/
-- Notation and variables for the equivalence class section:
-- let α be a type, and let R be a binary relation on R.
variables {α : Type} (R : α → α → Prop)
/-- The equivalence class of `a` is the set of `b` related to `a`. -/
def cl (a : α) :=
{b : α | R b a}
/-!
## Basic lemmas about equivalence classes
-/
/-- Useful for rewriting -- `b` is in the equivalence class of `a` iff
`b` is related to `a`. True by definition. -/
theorem cl_def {a b : α} : b ∈ cl R a ↔ R b a := iff.rfl
-- Assume now that R is an equivalence relation.
variables {R} (hR : equivalence R)
include hR
/-- x is in cl(x) -/
lemma mem_cl_self (a : α) :
a ∈ cl R a :=
begin
sorry,
end
lemma cl_sub_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a ⊆ cl R b :=
begin
sorry,
end
lemma cl_eq_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a = cl R b :=
begin
sorry
end
end equivalence_classes -- section
/-!
# 3) The challenge!
Let `α` be a type (i.e. a collection of stucff).
There is a bijection between equivalence relations on `α` and
partitions of `α`.
We prove this by writing down constructions in each direction
and proving that the constructions are two-sided inverses of one another.
-/
open partition
example (α : Type) : {R : α → α → Prop // equivalence R} ≃ partition α :=
-- We define constructions (functions!) in both directions and prove that
-- one is a two-sided inverse of the other
{ -- Here is the first construction, from equivalence
-- relations to partitions.
-- Let R be an equivalence relation.
to_fun := λ R, {
-- Let C be the set of equivalence classes for R.
C := { B : set α | ∃ x : α, B = cl R.1 x},
-- I claim that C is a partition. We need to check the three
-- hypotheses for a partition (`Hnonempty`, `Hcover` and `Hdisjoint`),
-- so we need to supply three proofs.
Hnonempty := begin
cases R with R hR,
-- If X is an equivalence class then X is nonempty.
show ∀ (X : set α), (∃ (a : α), X = cl R a) → X.nonempty,
sorry,
end,
Hcover := begin
cases R with R hR,
-- The equivalence classes cover α
show ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X,
sorry,
end,
Hdisjoint := begin
cases R with R hR,
-- If two equivalence classes overlap, they are equal.
show ∀ (X : set α), (∃ (a : α), X = cl R a) →
∀ (Y : set α), (∃ (b : α), Y = cl _ b) → (X ∩ Y).nonempty → X = Y,
sorry,
end },
-- Conversely, say P is an partition.
inv_fun := λ P,
-- Let's define a binary relation `R` thus:
-- `R a b` iff *every* block containing `a` also contains `b`.
-- Because only one block contains a, this will work,
-- and it turns out to be a nice way of thinking about it.
⟨λ a b, ∀ X ∈ P.C, a ∈ X → b ∈ X, begin
-- I claim this is an equivalence relation.
split,
{ -- It's reflexive
show ∀ (a : α)
(X : set α), X ∈ P.C → a ∈ X → a ∈ X,
sorry,
},
split,
{ -- it's symmetric
show ∀ (a b : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
∀ (X : set α), X ∈ P.C → b ∈ X → a ∈ X,
sorry,
},
{ -- it's transitive
unfold transitive,
show ∀ (a b c : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
(∀ (X : set α), X ∈ P.C → b ∈ X → c ∈ X) →
∀ (X : set α), X ∈ P.C → a ∈ X → c ∈ X,
sorry,
}
end⟩,
-- If you start with the equivalence relation, and then make the partition
-- and a new equivalence relation, you get back to where you started.
left_inv := begin
rintro ⟨R, hR⟩,
-- Tidying up the mess...
suffices : (λ (a b : α), ∀ (c : α), a ∈ cl R c → b ∈ cl R c) = R,
simpa,
-- ... you have to prove two binary relations are equal.
ext a b,
-- so you have to prove an if and only if.
show (∀ (c : α), a ∈ cl R c → b ∈ cl R c) ↔ R a b,
sorry,
end,
-- Similarly, if you start with the partition, and then make the
-- equivalence relation, and then construct the corresponding partition
-- into equivalence classes, you have the same partition you started with.
right_inv := begin
-- Let P be a partition
intro P,
-- It suffices to prove that a subset X is in the original partition
-- if and only if it's in the one made from the equivalence relation.
ext X,
show (∃ (a : α), X = cl _ a) ↔ X ∈ P.C,
dsimp only,
sorry,
end }
/-
-- get these files with
leanproject get ImperialCollegeLondon/M40001_lean
-/ |
f1eb7d5c1671814af9e6eddec46aa094d04557c6 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/inductive_pred.lean | 7f21caf0d244e57358c024fec15278bb690ff519 | [
"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 | 5,117 | lean | import Lean
open Lean
def checkGetBelowIndices (ctorName : Name) (indices : Array Nat) : MetaM Unit := do
let actualIndices ← Meta.IndPredBelow.getBelowIndices ctorName
if actualIndices != indices then
throwError "wrong indices for {ctorName}: {actualIndices} ≟ {indices}"
namespace Ex
inductive LE : Nat → Nat → Prop
| refl : LE n n
| succ : LE n m → LE n m.succ
#eval checkGetBelowIndices ``LE.refl #[1]
#eval checkGetBelowIndices ``LE.succ #[1, 2, 3]
def typeOf {α : Sort u} (a : α) := α
theorem LE_brecOn : typeOf @LE.brecOn =
∀ {motive : (a a_1 : Nat) → LE a a_1 → Prop} {a a_1 : Nat} (x : LE a a_1),
(∀ (a a_2 : Nat) (x : LE a a_2), @LE.below motive a a_2 x → motive a a_2 x) → motive a a_1 x := rfl
theorem LE.trans : LE m n → LE n o → LE m o := by
intro h1 h2
induction h2 with
| refl => assumption
| succ h2 ih => exact succ (ih h1)
theorem LE.trans' : LE m n → LE n o → LE m o
| h1, refl => h1
| h1, succ h2 => succ (trans' h1 h2) -- the structural recursion in being performed on the implicit `Nat` parameter
inductive Even : Nat → Prop
| zero : Even 0
| ss : Even n → Even n.succ.succ
#eval checkGetBelowIndices ``Even.zero #[]
#eval checkGetBelowIndices ``Even.ss #[1, 2]
theorem Even_brecOn : typeOf @Even.brecOn = ∀ {motive : (a : Nat) → Even a → Prop} {a : Nat} (x : Even a),
(∀ (a : Nat) (x : Even a), @Even.below motive a x → motive a x) → motive a x := rfl
theorem Even.add : Even n → Even m → Even (n+m) := by
intro h1 h2
induction h2 with
| zero => exact h1
| ss h2 ih => exact ss ih
theorem Even.add' : Even n → Even m → Even (n+m)
| h1, zero => h1
| h1, ss h2 => ss (add' h1 h2) -- the structural recursion in being performed on the implicit `Nat` parameter
theorem mul_left_comm (n m o : Nat) : n * (m * o) = m * (n * o) := by
rw [← Nat.mul_assoc, Nat.mul_comm n m, Nat.mul_assoc]
inductive Power2 : Nat → Prop
| base : Power2 1
| ind : Power2 n → Power2 (2*n) -- Note that index here is not a constructor
#eval checkGetBelowIndices ``Power2.base #[]
#eval checkGetBelowIndices ``Power2.ind #[1, 2]
theorem Power2_brecOn : typeOf @Power2.brecOn = ∀ {motive : (a : Nat) → Power2 a → Prop} {a : Nat} (x : Power2 a),
(∀ (a : Nat) (x : Power2 a), @Power2.below motive a x → motive a x) → motive a x := rfl
theorem Power2.mul : Power2 n → Power2 m → Power2 (n*m) := by
intro h1 h2
induction h2 with
| base => simp_all
| ind h2 ih => exact mul_left_comm .. ▸ ind ih
/- The following example fails because the structural recursion cannot be performed on the `Nat`s and
the `brecOn` construction doesn't work for inductive predicates -/
set_option trace.Elab.definition.structural true in
set_option trace.Meta.IndPredBelow.match true in
set_option pp.explicit true in
theorem Power2.mul' : Power2 n → Power2 m → Power2 (n*m)
| h1, base => by simp_all
| h1, ind h2 => mul_left_comm .. ▸ ind (mul' h1 h2)
inductive tm : Type :=
| C : Nat → tm
| P : tm → tm → tm
open tm
set_option hygiene false in
infixl:40 " ==> " => step
inductive step : tm → tm → Prop :=
| ST_PlusConstConst : ∀ n1 n2,
P (C n1) (C n2) ==> C (n1 + n2)
| ST_Plus1 : ∀ t1 t1' t2,
t1 ==> t1' →
P t1 t2 ==> P t1' t2
| ST_Plus2 : ∀ n1 t2 t2',
t2 ==> t2' →
P (C n1) t2 ==> P (C n1) t2'
#eval checkGetBelowIndices ``step.ST_PlusConstConst #[1, 2]
#eval checkGetBelowIndices ``step.ST_Plus1 #[1, 2, 3, 4]
#eval checkGetBelowIndices ``step.ST_Plus2 #[1, 2, 3, 4]
def deterministic {X : Type} (R : X → X → Prop) :=
∀ x y1 y2 : X, R x y1 → R x y2 → y1 = y2
theorem step_deterministic' : deterministic step := λ x y₁ y₂ hy₁ hy₂ =>
@step.brecOn (λ s t st => ∀ y₂, s ==> y₂ → t = y₂) _ _ hy₁ (λ s t st hy₁ y₂ hy₂ =>
match hy₁, hy₂ with
| step.below.ST_PlusConstConst _ _, step.ST_PlusConstConst _ _ => rfl
| step.below.ST_Plus1 _ _ _ hy₁ ih, step.ST_Plus1 _ t₁' _ _ => by rw [←ih t₁']; assumption
| step.below.ST_Plus1 _ _ _ hy₁ ih, step.ST_Plus2 _ _ _ _ => by cases hy₁
| step.below.ST_Plus2 _ _ _ _ ih, step.ST_Plus2 _ _ t₂ _ => by rw [←ih t₂]; assumption
| step.below.ST_Plus2 _ _ _ hy₁ _, step.ST_PlusConstConst _ _ => by cases hy₁
) y₂ hy₂
section NestedRecursion
axiom f : Nat → Nat
inductive is_nat : Nat -> Prop
| Z : is_nat 0
| S {n} : is_nat n → is_nat (f n)
#eval checkGetBelowIndices ``is_nat.Z #[]
#eval checkGetBelowIndices ``is_nat.S #[1, 2]
axiom P : Nat → Prop
axiom F0 : P 0
axiom F1 : P (f 0)
axiom FS {n : Nat} : P n → P (f (f n))
-- we would like to write this
theorem foo : ∀ {n}, is_nat n → P n
| _, is_nat.Z => F0
| _, is_nat.S is_nat.Z => F1
| _, is_nat.S (is_nat.S h) => FS (foo h)
theorem foo' : ∀ {n}, is_nat n → P n := fun h =>
@is_nat.brecOn (fun n hn => P n) _ h fun n h ih =>
match ih with
| is_nat.below.Z => F0
| is_nat.below.S is_nat.below.Z _ => F1
| is_nat.below.S (is_nat.below.S b hx) h₂ => FS hx
end NestedRecursion
end Ex
|
f6888e798cb4089ae94fb0117e23a00d6dfd4cb2 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/ring_theory/localization.lean | 84d80701c54290b48cd9bd5334d96207e32d8dd7 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 64,629 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston
-/
import data.equiv.ring
import group_theory.monoid_localization
import ring_theory.algebraic
import ring_theory.integral_closure
import ring_theory.non_zero_divisors
/-!
# Localizations of commutative rings
We characterize the localization of a commutative ring `R` at a submonoid `M` up to
isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a
ring homomorphism `f : R →+* S` satisfying 3 properties:
1. For all `y ∈ M`, `f y` is a unit;
2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`;
3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`.
Given such a localization map `f : R →+* S`, we can define the surjection
`localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and
`localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps
elements of `M` to invertible elements of the codomain. Similarly, given commutative rings
`P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism
`g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations,
`localization_map.map`, from `S` to `Q`.
We treat the special case of localizing away from an element in the sections `away_map` and `away`.
We show the localization as a quotient type, defined in `group_theory.monoid_localization` as
`submonoid.localization`, is a `comm_ring` and that the natural ring hom
`of : R →+* localization M` is a localization map.
We show that a localization at the complement of a prime ideal is a local ring.
We prove some lemmas about the `R`-algebra structure of `S`.
When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for
`localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions.
We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is
a field.
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a
`submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a
`localization_map` `f` in this file we invoke the corresponding proof for the underlying
`comm_monoid` localization map `f.to_localization_map`, which can be found in
`group_theory.monoid_localization` and the namespace `submonoid.localization_map`.
To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for
this structure.
To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas.
These show the quotient map `mk : R → M → localization M` equals the surjection
`localization_map.mk'` induced by the map `of : localization_map M (localization M)`
(where `of` establishes the localization as a quotient type satisfies the characteristic
predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file,
which are about the `localization_map.mk'` induced by any localization map.
We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that
instances on `S` induced by `f` can 'know' the map needed to induce the instance.
The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field" is a `def` rather than an `instance`, so if you want to reason about a field of
fractions `K`, assume `[field K]` instead of just `[comm_ring K]`.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
{P : Type*} [comm_ring P]
open function
set_option old_structure_cmd true
/-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S`
satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`.
We later define an instance coercing a localization map `f` to its codomain `S` so
that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/
@[nolint has_inhabited_instance] structure localization_map
extends ring_hom R S, submonoid.localization_map M S
/-- The ring hom underlying a `localization_map`. -/
add_decl_doc localization_map.to_ring_hom
/-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`.
See `group_theory.monoid_localization` for its definition. -/
add_decl_doc localization_map.to_localization_map
variables {M S}
namespace ring_hom
/-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/
def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y))
(H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) :
localization_map M S :=
{ map_units' := H1,
surj' := H2,
eq_iff_exists' := H3,
.. f }
end ring_hom
/-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of
`comm_ring`s. -/
def submonoid.localization_map.to_ring_localization
(f : submonoid.localization_map M S)
(h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) :
localization_map M S :=
{ ..ring_hom.mk' f.to_monoid_hom h, ..f }
namespace localization_map
variables (f : localization_map M S)
/-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that
instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/
@[nolint unused_arguments has_inhabited_instance]
def codomain (f : localization_map M S) := S
instance : comm_ring f.codomain := by assumption
instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption
/-- Short for `to_ring_hom`; used for applying a localization map as a function. -/
abbreviation to_map := f.to_ring_hom
lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y
lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z
lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y
@[ext] lemma ext {f g : localization_map M S}
(h : ∀ x, f.to_map x = g.to_map x) : f = g :=
begin
cases f, cases g,
simp only at *,
exact funext h
end
lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) :=
λ _ _ h, ext $ ring_hom.ext_iff.1 h
/-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ set.range f.to_map
variables {f}
lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a + b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' + b',
rw [f.to_map.map_add, ha, hb]
end
lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a * b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' * b',
rw [f.to_map.map_mul, ha, hb]
end
lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) :
f.is_integer (f.to_map a * b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, f.to_map.map_mul]
end
variables (f)
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the right, matching the argument order in `localization_map.surj`.
-/
lemma exists_integer_multiple' (a : S) :
∃ (b : M), is_integer f (a * f.to_map b) :=
let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance.
-/
lemma exists_integer_multiple (a : S) :
∃ (b : M), is_integer f (f.to_map b * a) :=
by { simp_rw mul_comm _ a, apply exists_integer_multiple' }
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x` (so this lemma is true by definition). -/
lemma sec_spec {f : localization_map M S} (z : S) :
z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 :=
classical.some_spec $ f.surj z
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/
lemma sec_spec' {f : localization_map M S} (z : S) :
f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z :=
by rw [mul_comm, sec_spec]
open_locale big_operators
/-- We can clear the denominators of a finite set of fractions. -/
lemma exist_integer_multiples_of_finset (s : finset S) :
∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) :=
begin
haveI := classical.prop_decidable,
use ∏ a in s, (f.to_localization_map.sec a).2,
intros a ha,
use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1,
rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul],
congr' 2,
refine trans _ ((submonoid.subtype M).map_prod _ _).symm,
rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha],
refl,
end
lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_right_cancel h
lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_left_cancel h
lemma eq_zero_of_fst_eq_zero {z x} {y : M}
(h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 :=
by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h
/-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to
`f x * (f y)⁻¹`. -/
noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S :=
f.to_localization_map.mk' x y
@[simp] lemma mk'_sec (z : S) :
f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z :=
f.to_localization_map.mk'_sec _
lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ :=
f.to_localization_map.mk'_mul _ _ _ _
lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x :=
f.to_localization_map.mk'_one _
@[simp]
lemma mk'_spec (x) (y : M) :
f.mk' x y * f.to_map y = f.to_map x :=
f.to_localization_map.mk'_spec _ _
@[simp]
lemma mk'_spec' (x) (y : M) :
f.to_map y * f.mk' x y = f.to_map x :=
f.to_localization_map.mk'_spec' _ _
theorem eq_mk'_iff_mul_eq {x} {y : M} {z} :
z = f.mk' x y ↔ z * f.to_map y = f.to_map x :=
f.to_localization_map.eq_mk'_iff_mul_eq
theorem mk'_eq_iff_eq_mul {x} {y : M} {z} :
f.mk' x y = z ↔ f.to_map x = z * f.to_map y :=
f.to_localization_map.mk'_eq_iff_eq_mul
lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z :=
let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩
lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} :
f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) :=
f.to_localization_map.mk'_eq_iff_eq
lemma mk'_mem_iff {x} {y : M} {I : ideal S} : f.mk' x y ∈ I ↔ f.to_map x ∈ I :=
begin
split;
intro h,
{ rw [← mk'_spec f x y, mul_comm],
exact I.smul_mem (f.to_map y) h },
{ rw ← mk'_spec f x y at h,
obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units f y),
have := I.smul_mem b h,
rwa [smul_eq_mul, mul_comm, mul_assoc, hb, mul_one] at this }
end
protected lemma eq {a₁ b₁} {a₂ b₂ : M} :
f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c :=
f.to_localization_map.eq
lemma eq_iff_eq (g : localization_map M P) {x y} :
f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y :=
f.to_localization_map.eq_iff_eq g.to_localization_map
lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂}
{y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ :=
f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map
lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) :
f.mk' a₁ a₂ = f.mk' b₁ b₂ :=
f.to_localization_map.mk'_eq_of_eq H
@[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 :=
f.to_localization_map.mk'_self _ hx
@[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 :=
f.to_localization_map.mk'_self' _
lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 :=
f.mk'_self'
lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) :
f.to_map x * f.mk' y z = f.mk' (x * y) z :=
f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _
lemma mk'_eq_mul_mk'_one (x : R) (y : M) :
f.mk' x y = f.to_map x * f.mk' 1 y :=
(f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm
@[simp] lemma mk'_mul_cancel_left (x : R) (y : M) :
f.mk' (y * x) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_left _ _
lemma mk'_mul_cancel_right (x : R) (y : M) :
f.mk' (x * y) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_right _ _
@[simp] lemma mk'_mul_mk'_eq_one (x y : M) :
f.mk' x y * f.mk' y x = 1 :=
by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _
lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) :
f.mk' x y * f.mk' y ⟨x, h⟩ = 1 :=
f.mk'_mul_mk'_eq_one ⟨x, h⟩ _
lemma is_unit_comp (j : S →+* P) (y : M) :
is_unit (j.comp f.to_map y) :=
f.to_localization_map.is_unit_comp j.to_monoid_hom _
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/
lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) :
g x = g y :=
@submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg _ _ h
lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ :=
f.mk'_eq_iff_eq_mul.2 $ eq.symm
begin
rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul,
mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc,
←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul],
simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul],
ring_exp,
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that
`z = f x * (f y)⁻¹`. -/
noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P :=
ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg) $
begin
intros x y,
rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm,
f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq',
←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul],
show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _),
repeat {rw ←g.map_mul},
rw [←g.map_sub, ←g.map_mul],
apply f.eq_of_eq hg,
erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub],
simp only [f.to_map.map_mul, sec_spec'],
ring_exp,
end
variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y))
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/
lemma lift_mk' (x y) :
f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ :=
f.to_localization_map.lift_mk' _ _ _
lemma lift_mk'_spec (x v) (y : M) :
f.lift hg (f.mk' x y) = v ↔ g x = g y * v :=
f.to_localization_map.lift_mk'_spec _ _ _ _
@[simp] lemma lift_eq (x : R) :
f.lift hg (f.to_map x) = g x :=
f.to_localization_map.lift_eq _ _
lemma lift_eq_iff {x y : R × M} :
f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) :=
f.to_localization_map.lift_eq_iff _
@[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _
@[simp] lemma lift_of_comp (j : S →+* P) :
f.lift (f.is_unit_comp j) = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom
lemma epic_of_localization_map {j k : S →+* P}
(h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map
_ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h
lemma lift_unique {j : S →+* P}
(hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique
_ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj
@[simp] lemma lift_id (x) : f.lift f.map_units x = x :=
f.to_localization_map.lift_id _
/-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`,
the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P`
induced by `k`. -/
@[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) :
k.lift f.map_units (f.lift k.map_units z) = z :=
f.to_localization_map.lift_left_inverse _
lemma lift_surjective_iff :
surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 :=
f.to_localization_map.lift_surjective_iff hg
lemma lift_injective_iff :
injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y :=
f.to_localization_map.lift_injective_iff hg
variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q]
(k : localization_map T Q)
/-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have
`g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the
localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M`
and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map : S →+* Q :=
@lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩
variables {k}
lemma map_eq (x) :
f.map hy k (f.to_map x) = k.to_map (g x) :=
f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x
@[simp] lemma map_comp :
(f.map hy k).comp f.to_map = k.to_map.comp g :=
f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩
lemma map_mk' (x) (y : M) :
f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ :=
@submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map
g.to_monoid_hom _ hy _ _ k.to_localization_map _ _
@[simp] lemma map_id (z : S) :
f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z :=
f.lift_id _
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) :
(k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map
_ _ _ _ _ j.to_localization_map l.to_monoid_hom hl
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) :
k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x :=
by rw ←f.map_comp_map hy j hl; refl
/-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an
isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations
`S ≃+* Q`. -/
noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P)
(H : M.map h.to_monoid_hom = T) :
S ≃+* Q :=
(f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $
(@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom)
(λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add
@[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P}
(H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H x =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl
lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) :
(f.ring_equiv_of_ring_equiv k j H).to_monoid_hom =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl
@[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) :=
f.to_localization_map.mul_equiv_of_mul_equiv_eq H _
lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) :
f.ring_equiv_of_ring_equiv k j H (f.mk' x y) =
k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ :=
f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _
section away_map
variables (x : R)
/-- Given `x : R`, the type of homomorphisms `f : R →* S` such that `S`
is isomorphic to the localization of `R` at the submonoid generated by `x`. -/
@[reducible]
def away_map (S' : Type*) [comm_ring S'] :=
localization_map (submonoid.powers x) S'
variables (F : away_map x S)
/-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/
noncomputable def away_map.inv_self : S :=
F.mk' 1 ⟨x, submonoid.mem_powers _⟩
/-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s
`g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending
`z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/
noncomputable def away_map.lift (hg : is_unit (g x)) : S →+* P :=
localization_map.lift F $ λ y, show is_unit (g y.1),
begin
obtain ⟨n, hn⟩ := y.2,
rw [←hn, g.map_pow],
exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg,
end
@[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) :
F.lift x hg (F.to_map a) = g a := lift_eq _ _ _
@[simp] lemma away_map.lift_comp (hg : is_unit (g x)) :
(F.lift x hg).comp F.to_map = g := lift_comp _ _
/-- Given `x y : R` and localization maps `F : R →+* S, G : R →+* P` away from `x` and `x * y`
respectively, the homomorphism induced from `S` to `P`. -/
noncomputable def away_to_away_right (y : R) (G : away_map (x * y) P) : S →* P :=
F.lift x $ show is_unit (G.to_map x), from
is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, submonoid.mem_powers _⟩) $
by rw [mul_mk'_eq_mk'_of_mul, mk'_self]
end away_map
end localization_map
namespace localization
variables {M}
instance : has_add (localization M) :=
⟨λ z w, con.lift_on₂ z w
(λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $
λ r1 r2 r3 r4 h1 h2, (con.eq _).2
begin
rw r_eq_r' at h1 h2 ⊢,
cases h1 with t₅ ht₅,
cases h2 with t₆ ht₆,
use t₆ * t₅,
calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) =
(r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring
... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring
end⟩
instance : has_neg (localization M) :=
⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $
λ r1 r2 h, (con.eq _).2
begin
rw r_eq_r' at h ⊢,
cases h with t ht,
use t,
rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht],
ring,
end⟩
instance : has_zero (localization M) :=
⟨mk 0 1⟩
private meta def tac := `[{
intros,
refine quotient.sound' (r_of_eq _),
simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul],
ring }]
instance : comm_ring (localization M) :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac),
zero_add := λ y, quotient.induction_on' y (by tac),
add_zero := λ y, quotient.induction_on' y (by tac),
neg := has_neg.neg,
add_left_neg := λ y, quotient.induction_on' y (by tac),
add_comm := λ y z, quotient.induction_on₂' z y (by tac),
left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
..localization.comm_monoid M }
variables (M)
/-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of
`(x, 1)` in the localization of `R` at a submonoid. -/
def of : localization_map M (localization M) :=
(localization.monoid_of M).to_ring_localization $
λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm]
variables {M}
lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl
lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl
lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y :=
mk_eq_monoid_of_mk'_apply _ _
@[simp] lemma mk_eq_mk' : mk = (of M).mk' :=
mk_eq_monoid_of_mk'
variables (f : localization_map M S)
/-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism
between the localization of `R` at `M` as a quotient type and `S`. -/
noncomputable def ring_equiv_of_quotient :
localization M ≃+* S :=
(mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $
((of M).lift f.map_units).map_add
variables {f}
@[simp] lemma ring_equiv_of_quotient_apply (x) :
ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl
@[simp] lemma ring_equiv_of_quotient_mk' (x y) :
ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y :=
mul_equiv_of_quotient_mk' _ _
lemma ring_equiv_of_quotient_mk (x y) :
ring_equiv_of_quotient f (mk x y) = f.mk' x y :=
mul_equiv_of_quotient_mk _ _
@[simp] lemma ring_equiv_of_quotient_of (x) :
ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x :=
mul_equiv_of_quotient_monoid_of _
@[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) :
(ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y :=
mul_equiv_of_quotient_symm_mk' _ _
lemma ring_equiv_of_quotient_symm_mk (x y) :
(ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y :=
mul_equiv_of_quotient_symm_mk _ _
@[simp] lemma ring_equiv_of_quotient_symm_of (x) :
(ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x :=
mul_equiv_of_quotient_symm_monoid_of _
section away
variables (x : R)
/-- Given `x : R`, the natural hom sending `y : R`, `R` a `comm_ring`, to the equivalence class
of `(y, 1)` in the localization of `R` at the submonoid generated by `x`. -/
@[reducible] def away.of : localization_map.away_map x (away x) := of (submonoid.powers x)
@[simp] lemma away.mk_eq_mk' : mk = (away.of x).mk' :=
mk_eq_mk'
/-- Given `x : R` and a localization map `f : R →+* S` away from `x`, we get an isomorphism between
the localization of `R` at the submonoid generated by `x` as a quotient type and `S`. -/
noncomputable def away.ring_equiv_of_quotient (f : localization_map.away_map x S) :
away x ≃+* S :=
ring_equiv_of_quotient f
end away
end localization
variables {M}
section at_prime
variables (I : ideal R) [hp : I.is_prime]
include hp
namespace ideal
/-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/
def prime_compl :
submonoid R :=
{ carrier := (Iᶜ : set R),
one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl,
mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny }
end ideal
namespace localization_map
variables (S)
/-- A localization map from `R` to `S` where the submonoid is the complement of a prime
ideal of `R`. -/
@[reducible] def at_prime :=
localization_map I.prime_compl S
end localization_map
namespace localization
/-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/
@[reducible] def at_prime :=
localization I.prime_compl
end localization
namespace localization_map
variables {I}
/-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a
copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring`
instance on `S` can 'know' the map needed to induce the instance. -/
instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain :=
local_of_nonunits_ideal
(λ hze, begin
rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze,
obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze,
exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm,
htz.symm ▸ I.zero_mem))
end)
(begin
intros x y hx hy hu,
cases is_unit_iff_exists_inv.1 hu with z hxyz,
have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from
λ r s, not_imp_comm.1
(λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩),
rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩,
rcases f.mk'_surjective y with ⟨ry, sy, hry⟩,
rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩,
rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul,
←f.mk'_self I.prime_compl.one_mem] at hxyz,
rw ←hrx at hx, rw ←hry at hy,
cases f.eq.1 hxyz with t ht,
simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht,
rw [←sub_eq_zero, ←sub_mul] at ht,
have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2,
have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr),
{ exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)},
{ exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))}
end)
end localization_map
namespace localization
/-- The localization of `R` at the complement of a prime ideal is a local ring. -/
instance at_prime.local_ring : local_ring (localization I.prime_compl) :=
localization_map.at_prime.local_ring (of I.prime_compl)
end localization
end at_prime
namespace localization_map
variables (f : localization_map M S)
section ideals
/-- Explicit characterization of the ideal given by `ideal.map f.to_map I`.
In practice, this ideal differs only in that the carrier set is defined explicitly.
This definition is only meant to be used in proving `mem_map_to_map_iff`,
and any proof that needs to refer to the explicit carrier set should use that theorem. -/
private def to_map_ideal (I : ideal R) : ideal S :=
{ carrier := { z : S | ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1},
zero_mem' := ⟨⟨0, 1⟩, by simp⟩,
add_mem' := begin
rintros a b ⟨a', ha⟩ ⟨b', hb⟩,
use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.smul_mem _ b'.1.2) (I.smul_mem _ a'.1.2)⟩,
use a'.2 * b'.2,
simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul],
rw [add_mul, ← mul_assoc a, ha, mul_comm (f.to_map a'.2) (f.to_map b'.2), ← mul_assoc b, hb],
ring
end,
smul_mem' := begin
rintros c x ⟨x', hx⟩,
obtain ⟨c', hc⟩ := localization_map.surj f c,
use ⟨c'.1 * x'.1, I.smul_mem c'.1 x'.1.2⟩,
use c'.2 * x'.2,
simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul],
ring
end }
theorem mem_map_to_map_iff {I : ideal R} {z} :
z ∈ ideal.map f.to_map I ↔ ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1 :=
begin
split,
{ show _ → z ∈ to_map_ideal f I,
refine λ h, ideal.mem_Inf.1 h (λ z hz, _),
obtain ⟨y, hy⟩ := hz,
use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ },
{ rintros ⟨⟨a, s⟩, h⟩,
rw [← ideal.unit_mul_mem_iff_mem _ (map_units f s), mul_comm],
exact h.symm ▸ ideal.mem_map_of_mem a.2 }
end
theorem map_comap (J : ideal S) :
ideal.map f.to_map (ideal.comap f.to_map J) = J :=
le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ,
begin
obtain ⟨r, s, hx⟩ := f.mk'_surjective x,
rw ←hx at ⊢ hJ,
exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from
f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)),
end
theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime)
(hM : disjoint (M : set R) I) : ideal.comap f.to_map (ideal.map f.to_map I) = I :=
begin
refine le_antisymm (λ a ha, _) ideal.le_comap_map,
rw [ideal.mem_comap, mem_map_to_map_iff] at ha,
obtain ⟨⟨b, s⟩, h⟩ := ha,
have : f.to_map (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h,
rw [← f.to_map.map_zero, eq_iff_exists] at this,
obtain ⟨c, hc⟩ := this,
have : a * s ∈ I,
{ rw zero_mul at hc,
let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem,
cases hI.right this with h1 h2,
{ simpa using I.add_mem h1 b.2 },
{ exfalso,
refine hM ⟨c.2, h2⟩ } },
cases hI.right this with h1 h2,
{ exact h1 },
{ exfalso,
refine hM ⟨s.2, h2⟩ }
end
/-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is
embedded in the ordering of ideals of `R`. -/
def order_embedding :
ideal S ↪o ideal R :=
{ to_fun := λ J, ideal.comap f.to_map J,
inj' := function.left_inverse.injective f.map_comap,
map_rel_iff' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ,
f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ }
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M`.
This lemma gives the particular case for an ideal and its comap,
see `le_rel_iso_of_prime` for the more general relation isomorphism -/
lemma is_prime_iff_is_prime_disjoint (J : ideal S) :
J.is_prime ↔ (ideal.comap f.to_map J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap f.to_map J) :=
begin
split,
{ refine λ h, ⟨⟨_, _⟩, λ m hm, h.1 (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units f ⟨m, hm.left⟩))⟩,
{ refine λ hJ, h.left _,
rw [eq_top_iff, (order_embedding f).map_rel_iff],
exact le_of_eq hJ.symm },
{ intros x y hxy,
rw [ideal.mem_comap, ring_hom.map_mul] at hxy,
exact h.right hxy } },
{ refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), _⟩,
{ rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ },
{ intros x y hxy,
obtain ⟨a, s, ha⟩ := mk'_surjective f x,
obtain ⟨b, t, hb⟩ := mk'_surjective f y,
have : f.mk' (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb],
rw [mk'_mem_iff, ← ideal.mem_comap] at this,
replace this := h.left.right this,
rw [ideal.mem_comap, ideal.mem_comap] at this,
rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } }
end
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M`.
This lemma gives the particular case for an ideal and its map,
see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/
lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime)
(hd : disjoint (M : set R) ↑I) : (ideal.map f.to_map I).is_prime :=
begin
rw [is_prime_iff_is_prime_disjoint f, comap_map_of_is_prime_disjoint f I hp hd],
exact ⟨hp, hd⟩
end
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M` -/
def order_iso_of_prime (f : localization_map M S) :
{p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} :=
{ to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_prime_iff_is_prime_disjoint f p.1).1 p.2⟩,
inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_prime_of_is_prime_disjoint f p.1 p.2.1 p.2.2⟩,
left_inv := λ J, subtype.eq (map_comap f J),
right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 I.2.1 I.2.2),
map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val,
from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ }
end ideals
/-!
### `algebra` section
Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map
`f` needed to induce the `R`-algebra structure. -/
/-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/
instance : algebra R f.codomain := f.to_map.to_algebra
end localization_map
namespace localization
instance : algebra R (localization M) := localization_map.algebra (of M)
end localization
namespace localization_map
variables (f : localization_map M S)
@[simp] lemma of_id (a : R) :
(algebra.of_id R f.codomain) a = f.to_map a :=
rfl
@[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl
variables (f)
/-- Localization map `f` from `R` to `S` as an `R`-linear map. -/
def lin_coe : R →ₗ[R] f.codomain :=
{ to_fun := f.to_map,
map_add' := f.to_map.map_add,
map_smul' := f.to_map.map_mul }
/-- Map from ideals of `R` to submodules of `S` induced by `f`. -/
-- This was previously a `has_coe` instance, but if `f.codomain = R` then this will loop.
-- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down
-- the rest of the library.
def coe_submodule (I : ideal R) : submodule R f.codomain := submodule.map f.lin_coe I
variables {f}
lemma mem_coe_submodule (I : ideal R) {x : S} :
x ∈ f.coe_submodule I ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x :=
iff.rfl
@[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl
variables {g : R →+* P}
variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q]
(k : localization_map T Q)
lemma map_smul (x : f.codomain) (z : R) :
f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) :=
show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x,
by rw [ring_hom.map_mul, map_eq]
end localization_map
namespace localization
variables (f : localization_map M S)
/-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an `R`-preserving
isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/
noncomputable def alg_equiv_of_quotient : localization M ≃ₐ[R] f.codomain :=
{ commutes' := ring_equiv_of_quotient_of,
..ring_equiv_of_quotient f }
lemma alg_equiv_of_quotient_apply (x : localization M) :
alg_equiv_of_quotient f x = ring_equiv_of_quotient f x := rfl
lemma alg_equiv_of_quotient_symm_apply (x : f.codomain) :
(alg_equiv_of_quotient f).symm x = (ring_equiv_of_quotient f).symm x := rfl
end localization
namespace localization_map
section integer_normalization
variables {f : localization_map M S}
open finsupp polynomial
open_locale classical
/-- `coeff_integer_normalization p` gives the coefficients of the polynomial
`integer_normalization p` -/
noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R :=
if hi : i ∈ p.support
then classical.some (classical.some_spec
(f.exist_integer_multiples_of_finset (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩))
else 0
lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ)
(h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support :=
begin
contrapose h,
rw [ne.def, not_not, coeff_integer_normalization, dif_neg h]
end
/-- `integer_normalization g` normalizes `g` to have integer coefficients
by clearing the denominators -/
noncomputable def integer_normalization : polynomial f.codomain → polynomial R :=
λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p)
@[simp]
lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) :
(integer_normalization p).coeff i = coeff_integer_normalization p i := rfl
lemma integer_normalization_spec (p : polynomial f.codomain) :
∃ (b : M), ∀ i, f.to_map ((integer_normalization p).coeff i) = f.to_map b * p.coeff i :=
begin
use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)),
intro i,
rw [integer_normalization_coeff, coeff_integer_normalization],
split_ifs with hi,
{ exact classical.some_spec (classical.some_spec
(f.exist_integer_multiples_of_finset (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩)) },
{ convert (_root_.mul_zero (f.to_map _)).symm,
{ exact f.to_ring_hom.map_zero },
{ exact finsupp.not_mem_support_iff.mp hi } }
end
lemma integer_normalization_map_to_map (p : polynomial f.codomain) :
∃ (b : M), (integer_normalization p).map f.to_map = f.to_map b • p :=
let ⟨b, hb⟩ := integer_normalization_spec p in
⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩
variables {R' : Type*} [comm_ring R']
lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain)
{x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (integer_normalization p) = 0 :=
let ⟨b, hb⟩ := integer_normalization_map_to_map p in
trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero])
lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R']
[is_scalar_tower R f.codomain R'] (p : polynomial f.codomain)
{x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization p) = 0 :=
by rw [aeval_def, is_scalar_tower.algebra_map_eq R f.codomain R', algebra_map_eq,
integer_normalization_eval₂_eq_zero _ _ hx]
end integer_normalization
variables {R} {A K : Type*} [integral_domain A]
lemma to_map_eq_zero_iff (f : localization_map M S) {x : R} (hM : M ≤ non_zero_divisors R) :
f.to_map x = 0 ↔ x = 0 :=
begin
rw ← f.to_map.map_zero,
split; intro h,
{ cases f.eq_iff_exists.mp h with c hc,
rw zero_mul at hc,
exact hM c.2 x hc },
{ rw h },
end
lemma injective (f : localization_map M S) (hM : M ≤ non_zero_divisors R) :
injective f.to_map :=
begin
rw ring_hom.injective_iff f.to_map,
intros a ha,
rw [← f.to_map.map_zero, f.eq_iff_exists] at ha,
cases ha with c hc,
rw zero_mul at hc,
exact hM c.2 a hc,
end
protected lemma to_map_ne_zero_of_mem_non_zero_divisors {M : submonoid A} (f : localization_map M S)
(hM : M ≤ non_zero_divisors A) (x : non_zero_divisors A) : f.to_map x ≠ 0 :=
map_ne_zero_of_mem_non_zero_divisors (f.injective hM)
/-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of
non-zero elements is an integral domain. -/
def integral_domain_of_le_non_zero_divisors {M : submonoid A} (f : localization_map M S)
(hM : M ≤ non_zero_divisors A) : integral_domain S :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros z w h,
cases f.surj z with x hx,
cases f.surj w with y hy,
have : z * w * f.to_map y.2 * f.to_map x.2 = f.to_map x.1 * f.to_map y.1,
by rw [mul_assoc z, hy, ←hx]; ac_refl,
rw [h, zero_mul, zero_mul, ← f.to_map.map_mul] at this,
cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff f hM).mp this.symm) with H H,
{ exact or.inl (f.eq_zero_of_fst_eq_zero hx H) },
{ exact or.inr (f.eq_zero_of_fst_eq_zero hy H) },
end,
exists_pair_ne := ⟨f.to_map 0, f.to_map 1, λ h, zero_ne_one (f.injective hM h)⟩,
..(infer_instance : comm_ring S) }
/-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/
def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) :
integral_domain (localization M) :=
(localization.of M).integral_domain_of_le_non_zero_divisors hM
/--
The localization of an integral domain at the complement of a prime ideal is an integral domain.
-/
instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) :
integral_domain (localization.at_prime P) :=
integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem))
end localization_map
section at_prime
namespace localization
local attribute [instance] classical.prop_decidable
/-- The image of `P` in the localization at `P.prime_compl` is a maximal ideal, and in particular
it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/
lemma at_prime.map_eq_maximal_ideal {P : ideal R} [hP : ideal.is_prime P] :
ideal.map (localization.of P.prime_compl).to_map P =
(local_ring.maximal_ideal (localization P.prime_compl)) :=
begin
let f := localization.of P.prime_compl,
ext x,
split; simp only [local_ring.mem_maximal_ideal, mem_nonunits_iff]; intro hx,
{ exact λ h, (localization_map.is_prime_of_is_prime_disjoint f P hP
(set.disjoint_compl_left P.carrier)).1 (ideal.eq_top_of_is_unit_mem _ hx h) },
{ obtain ⟨⟨a, b⟩, hab⟩ := localization_map.surj f x,
contrapose! hx,
rw is_unit_iff_exists_inv,
rw localization_map.mem_map_to_map_iff at hx,
obtain ⟨a', ha'⟩ := is_unit_iff_exists_inv.1
(localization_map.map_units f ⟨a, λ ha, hx ⟨⟨⟨a, ha⟩, b⟩, hab⟩⟩),
exact ⟨f.to_map b * a', by rwa [← mul_assoc, hab]⟩ }
end
/-- The unique maximal ideal of the localization at `P.prime_compl` lies over the ideal `P`. -/
lemma at_prime.comap_maximal_ideal {P : ideal R} [ideal.is_prime P] :
ideal.comap (localization.of P.prime_compl).to_map (local_ring.maximal_ideal (localization P.prime_compl)) = P :=
begin
let Pₚ := local_ring.maximal_ideal (localization P.prime_compl),
refine le_antisymm (λ x hx, _)
(le_trans ideal.le_comap_map (ideal.comap_mono (le_of_eq at_prime.map_eq_maximal_ideal))),
by_cases h0 : x = 0,
{ exact h0.symm ▸ P.zero_mem },
{ have : Pₚ.is_prime := ideal.is_maximal.is_prime (local_ring.maximal_ideal.is_maximal _),
rw localization_map.is_prime_iff_is_prime_disjoint (localization.of P.prime_compl) at this,
contrapose! h0 with hx',
simpa using this.2 ⟨hx', hx⟩ }
end
end localization
end at_prime
variables (R) {A : Type*} [integral_domain A]
variables (K : Type*)
/-- Localization map from an integral domain `R` to its field of fractions. -/
@[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K
namespace fraction_map
open localization_map
variables {R K}
lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} :
φ.to_map x = 0 ↔ x = 0 :=
φ.to_map_eq_zero_iff (le_of_eq rfl)
protected theorem injective [comm_ring K] (φ : fraction_map R K) :
function.injective φ.to_map :=
φ.injective (le_of_eq rfl)
protected lemma to_map_ne_zero_of_mem_non_zero_divisors [comm_ring K] (φ : fraction_map A K)
(x : non_zero_divisors A) : φ.to_map x ≠ 0 :=
φ.to_map_ne_zero_of_mem_non_zero_divisors (le_of_eq rfl) x
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an
integral domain. -/
def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K :=
φ.integral_domain_of_le_non_zero_divisors (le_of_eq rfl)
local attribute [instance] classical.dec_eq
/-- The inverse of an element in the field of fractions of an integral domain. -/
protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K :=
if h : z = 0 then 0 else
φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩
protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) :
x * φ.inv x = 1 :=
show x * dite _ _ _ = 1, by rw [dif_neg hx,
←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩),
one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a
field. -/
noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K :=
{ inv := φ.inv,
mul_inv_cancel := φ.mul_inv_cancel,
inv_zero := dif_pos rfl, ..φ.to_integral_domain }
variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L]
(f : fraction_map A K) {g : A →+* L}
lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s :=
f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _
(f.to_map_ne_zero_of_mem_non_zero_divisors _)).symm
lemma is_unit_map_of_injective (hg : function.injective g)
(y : non_zero_divisors A) : is_unit (g y) :=
is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg
/-- Given an integral domain `A`, a localization map to its fields of fractions
`f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a
field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def lift (hg : injective g) : K →+* L :=
f.lift $ is_unit_map_of_injective hg
/-- Given an integral domain `A`, a localization map to its fields of fractions
`f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field,
field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all
`x : A, y ∈ non_zero_divisors A`. -/
@[simp] lemma lift_mk' (hg : injective g) (x y) :
f.lift hg (f.mk' x y) = g x / g y :=
begin
erw f.lift_mk' (is_unit_map_of_injective hg),
erw submonoid.localization_map.mul_inv_left
(λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from
is_unit_map_of_injective hg y),
exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm,
end
/-- Given integral domains `A, B` and localization maps to their fields of fractions
`f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom
sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) :
K →+* L :=
f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $
map_ne_zero_of_mem_non_zero_divisors hj) g
/-- Given integral domains `A, B` and localization maps to their fields of fractions
`f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of
fields of fractions `K ≃+* L`. -/
noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) :
K ≃+* L :=
f.ring_equiv_of_ring_equiv g h
begin
ext b,
show b ∈ h.to_equiv '' _ ↔ _,
erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq,
mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero],
exact h.symm.map_ne_zero_iff
end
/-- The cast from `int` to `rat` as a `fraction_map`. -/
def int.fraction_map : fraction_map ℤ ℚ :=
{ to_fun := coe,
map_units' :=
begin
rintro ⟨x, hx⟩,
rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx,
simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx,
end,
surj' :=
begin
rintro ⟨n, d, hd, h⟩,
refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩,
rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos]
end,
eq_iff_exists' :=
begin
intros x y,
rw [int.cast_inj],
refine ⟨by { rintro rfl, use 1 }, _⟩,
rintro ⟨⟨c, hc⟩, h⟩,
apply int.eq_of_mul_eq_mul_right _ h,
rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc,
end,
..int.cast_ring_hom ℚ }
lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} :
integer_normalization p = 0 ↔ p = 0 :=
begin
refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm),
obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p,
split; intros h i,
{ apply f.to_map_eq_zero_iff.mp,
rw [hb i, h i],
exact _root_.mul_zero _ },
{ have hi := h i,
rw [polynomial.coeff_zero, ← f.to_map_eq_zero_iff, hb i] at hi,
apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi),
intro h,
apply mem_non_zero_divisors_iff_ne_zero.mp nonzero,
exact f.to_map_eq_zero_iff.mp h }
end
/-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/
lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] :
algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L :=
begin
split; intros h x; obtain ⟨p, hp, px⟩ := h x,
{ refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩,
{ have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]),
exact f.to_map_eq_zero_iff.mp this },
{ rwa [is_scalar_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } },
{ exact ⟨integer_normalization p,
mt f.integer_normalization_eq_zero_iff.mp hp,
integer_normalization_aeval_eq_zero p px⟩ },
end
section num_denom
variables [unique_factorization_monoid A] (φ : fraction_map A K)
lemma exists_reduced_fraction (x : φ.codomain) :
∃ (a : A) (b : non_zero_divisors A),
(∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x :=
begin
obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x,
obtain ⟨a', b', c', no_factor, rfl, rfl⟩ :=
unique_factorization_monoid.exists_reduced_factors' a b
(mem_non_zero_divisors_iff_ne_zero.mp b_nonzero),
obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero,
refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩,
apply mul_left_cancel' (φ.to_map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩),
simp only [subtype.coe_mk, φ.to_map.map_mul] at *,
erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩],
end
/-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/
noncomputable def num (x : φ.codomain) : A :=
classical.some (φ.exists_reduced_fraction x)
/-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/
noncomputable def denom (x : φ.codomain) : non_zero_divisors A :=
classical.some (classical.some_spec (φ.exists_reduced_fraction x))
lemma num_denom_reduced (x : φ.codomain) :
∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d :=
(classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1
@[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x :=
(classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2
lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} :
x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y :=
⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h,
λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩
lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} :
y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y :=
⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h,
λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩
lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} :
φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y :=
⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h,
λ h, by rw h ⟩
lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 :=
φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero])
lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x :=
begin
cases h with d hd,
have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 :=
φ.to_map_ne_zero_of_mem_non_zero_divisors (φ.denom x),
use ↑d⁻¹ * φ.num x,
refine trans _ (φ.mk'_num_denom x),
rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd],
apply mul_left_cancel' d_ne_zero,
rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec']
end
lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) :=
φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _)
end num_denom
end fraction_map
section algebra
section is_integral
variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R S]
/-- Definition of the natural algebra induced by the localization of an algebra.
Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`,
let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`.
Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes,
where `localization_map.map_comp` gives the commutativity of the underlying maps -/
noncomputable def localization_algebra (M : submonoid R) (f : localization_map M Rₘ)
(g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) : algebra Rₘ Sₘ :=
(f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).to_algebra
variables (f : localization_map M Rₘ)
variables (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ)
lemma algebra_map_mk' (r : R) (m : M) :
(@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) (f.mk' r m) =
g.mk' (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ :=
localization_map.map_mk' f _ r m
/-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization -/
lemma localization_algebra_injective (hRS : function.injective (algebra_map R S))
(hM : algebra.algebra_map_submonoid S M ≤ non_zero_divisors S) :
function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) :=
begin
rintros x y hxy,
obtain ⟨a, b, rfl⟩ := localization_map.mk'_surjective f x,
obtain ⟨c, d, rfl⟩ := localization_map.mk'_surjective f y,
rw [algebra_map_mk' f g a b, algebra_map_mk' f g c d, localization_map.mk'_eq_iff_eq] at hxy,
refine (localization_map.mk'_eq_iff_eq f).2 (congr_arg f.to_map (hRS _)),
convert g.injective hM hxy; simp,
end
open polynomial
/-- Given a particular witness to an element being algebraic over an algebra `R → S`,
We can localize to a submonoid containing the leading coefficient to make it integral -/
theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R)
(hp : aeval x p = 0) (hM' : p.leading_coeff ∈ M) :
@is_integral Rₘ _ _ _ (localization_algebra M f g) (g.to_map x) :=
begin
by_cases triv : (1 : Rₘ) = 0,
{ exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ },
haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv,
obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp
(localization_map.map_units f ⟨p.leading_coeff, hM'⟩),
refine ⟨(p.map f.to_map) * C b, ⟨_, _⟩⟩,
{ refine monic_mul_C_of_leading_coeff_mul_eq_one _,
rwa leading_coeff_map_of_leading_coeff_ne_zero f.to_map,
refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) },
{ refine eval₂_mul_eq_zero_of_left _ _ _ _,
erw [eval₂_map, localization_map.map_comp, ← hom_eval₂ _ (algebra_map R S) g.to_map x],
exact trans (congr_arg g.to_map hp) g.to_map.map_zero }
end
/-- If `R → S` is an integral extension, `M` is a submonoid of `R`,
`Rₘ` is the localization of `R` at `M`,
and `Sₘ` is the localization of `S` at the image of `M` under the extension map,
then the induced map `Rₘ → Sₘ` is also an integral extension -/
theorem is_integral_localization (H : ∀ x : S, is_integral R x)
(x : Sₘ) : @is_integral Rₘ _ _ _ (localization_algebra M f g) x :=
begin
by_cases triv : (1 : R) = 0,
{ have : (1 : Rₘ) = 0 := by convert congr_arg f.to_map triv; simp,
exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ },
{ haveI : nontrivial R := nontrivial_of_ne 1 0 triv,
obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := g.surj x,
obtain ⟨v, hv⟩ := hu,
obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (f.map_units ⟨v, hv.1⟩),
refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _
(localization_algebra M f g) x (g.to_map u) v' _ _,
{ replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) hv',
rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ f.to_map] at hv',
erw localization_map.map_comp at hv',
exact hv.2 ▸ hv' },
{ obtain ⟨p, hp⟩ := H s,
exact hx.symm ▸ is_integral_localization_at_leading_coeff
f g p hp.2 (hp.1.symm ▸ M.one_mem) } }
end
end is_integral
namespace integral_closure
variables {L : Type*} [field K] [field L] {f : fraction_map A K}
open algebra
/-- If the field `L` is an algebraic extension of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L)
(inj : ∀ x, algebra_map A L x = 0 → x = 0) :
fraction_map (integral_closure A L) L :=
(algebra_map (integral_closure A L) L).to_localization_map
(λ ⟨⟨y, integral⟩, nonzero⟩,
have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h),
show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩)
(λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in
⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩)
(λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩,
λ ⟨c, hc⟩, congr_arg (algebra_map _ L)
(mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩)
/-- If the field `L` is a finite extension of the fraction field of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L]
[is_scalar_tower A f.codomain L] [finite_dimensional f.codomain L] :
fraction_map (integral_closure A L) L :=
fraction_map_of_algebraic
(f.comap_is_algebraic_iff.mpr is_algebraic_of_finite)
(λ x hx, f.to_map_eq_zero_iff.mp ((algebra_map f.codomain L).map_eq_zero.mp $
(is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx))
end integral_closure
end algebra
variables (A)
/-- The fraction field of an integral domain as a quotient type. -/
@[reducible] def fraction_ring := localization (non_zero_divisors A)
namespace fraction_ring
/-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of
`(x, 1)` in the field of fractions of `A`. -/
def of : fraction_map A (localization (non_zero_divisors A)) :=
localization.of (non_zero_divisors A)
variables {A}
noncomputable instance : field (fraction_ring A) :=
(of A).to_field
@[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) =
((of A).to_map r / (of A).to_map s : fraction_ring A) :=
by erw [localization.mk_eq_mk', (of A).mk'_eq_div]
/-- Given an integral domain `A` and a localization map to a field of fractions
`f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient
type and `K`. -/
noncomputable def alg_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) :
fraction_ring A ≃ₐ[A] f.codomain :=
localization.alg_equiv_of_quotient f
end fraction_ring
|
a6e723b565995995f0b7099116973e4ae2af9de4 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/category/Group/Z_Module_equivalence.lean | 219b668008d2a1fc20257c4f03a7e05e6733d068 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 1,338 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Module.basic
/-!
The forgetful functor from ℤ-modules to additive commutative groups is
an equivalence of categories.
TODO:
either use this equivalence to transport the monoidal structure from `Module ℤ` to `Ab`,
or, having constructed that monoidal structure directly, show this functor is monoidal.
-/
open category_theory
open category_theory.equivalence
universes u
/-- The forgetful functor from `ℤ` modules to `AddCommGroup` is full. -/
instance : full (forget₂ (Module ℤ) AddCommGroup.{u}) :=
{ preimage := λ A B f,
-- TODO: why `add_monoid_hom.to_int_linear_map` doesn't work here?
{ to_fun := f,
map_add' := add_monoid_hom.map_add f,
map_smul' := λ n x, by convert add_monoid_hom.map_int_module_smul f n x } }
/-- The forgetful functor from `ℤ` modules to `AddCommGroup` is essentially surjective. -/
instance : ess_surj (forget₂ (Module ℤ) AddCommGroup.{u}) :=
{ mem_ess_image := λ A, ⟨Module.of ℤ A, ⟨{ hom := 𝟙 A, inv := 𝟙 A }⟩⟩}
noncomputable instance : is_equivalence (forget₂ (Module ℤ) AddCommGroup.{u}) :=
equivalence_of_fully_faithfully_ess_surj (forget₂ (Module ℤ) AddCommGroup)
|
a0088c32a2b9c2891af4c324071402b0eaf2d23b | ad3e8f15221a986da27c99f371922c0b3f5792b6 | /src/week-02/solutions/e03-relations.lean | 868893d1227cfd0556cb2aae75ac3d8387d2074a | [] | 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 | 11,840 | lean | import tactic
/-
Упражнения в этом файле взяты из курса Formalising Mathematics:
https://github.com/ImperialCollegeLondon/formalising-mathematics/blob/master/src/week_1/Part_D_relations.lean
Рассмотрим тип `α` и бинарные отношения над `α`: `R : α → α → Prop`.
Для бинарных отношений в Lean определены понятия рефлексивности, симметричности и транзитивности:
`reflexive R := ∀ (x : α), R x x`
`symmetric R := ∀ ⦃x y : α⦄, R x y → R y x`
`transitive R := ∀ ⦃x y z : α⦄, R x y → R y z → R x z`
Отношение `R` является отношением эквивалентности, если оно удовлетворяет всем трем определенным выше утверждениям:
`equivalence R := reflexive R ∧ symmetric R ∧ transitive R`
В этом файле мы докажем, что существует биекция между отношениями эквивалентности на типе `α` и разбиениями элементов `α` на подмножества (чтобы не путаться, будем называть их блоками).
Определим тип разбиений элементов типа `α`. Разбиение состоит из четырех элементов:
1) `C : set (set α)` - множество блоков.
2) `Hnonempty` - доказательство того, что все блоки непусты.
3) `Hcover` - доказательство того, что любой элемент `a : α` лежит в каком-то блоке.
4) `Hdisjoint` - доказательство того, что разные блоки не пересекаются.
Ключевое слово `structure` задает тип с одним конструктором (он сгенерируется с названием `partition.mk`) и именными "полями". Если `P : partition α`, то можно писать `P.C`, `P.Hnonempty` и остальные.
-/
@[ext] structure partition (α : Type) :=
(C : set (set α))
(Hnonempty : ∀ X ∈ C, (X : set α).nonempty)
(Hcover : ∀ a, ∃ X ∈ C, a ∈ X)
(Hdisjoint : ∀ X Y ∈ C, (X ∩ Y : set α).nonempty → X = Y)
namespace partition
variables {α : Type} {P : partition α} {X Y : set α}
-- `X.nonempty` (или `set.nonempty X`) означает, что существует элемент, принадлежащий множеству `X`
lemma nonempty_def : X.nonempty ↔ ∃ a, a ∈ X :=
begin
refl,
end
/-- Если `a` содержится в двух блоках `X` и `Y` -/
theorem eq_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a : α} (haX : a ∈ X)
(haY : a ∈ Y) : X = Y :=
begin
apply P.Hdisjoint X Y hX hY,
use [a, haX, haY],
end
theorem mem_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a b : α}
(haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y :=
begin
have heq := eq_of_mem hX hY haX haY,
rwa heq at hbX,
end
end partition
section equivalence_classes
variables {α : Type} (R : α → α → Prop) (hR : equivalence R)
-- Классом эквивалентности `a` назовем множество таких `b`, что `R b a`
def cl (a : α) := {b : α | R b a}
-- По определению, `b` лежит в классе эквивалентности `a`, если `R b a`
lemma mem_cl_iff {a b : α} : b ∈ cl R a ↔ R b a :=
begin
refl
end
-- `a` принадлежит классу эквивалентности `a`
lemma mem_cl_self (hR : equivalence R) (a : α) : a ∈ cl R a :=
begin
-- Чтобы использовать рефлексивность `R`, нужно распаковать `hR`
-- Это можно сделать с помощью `rcases`: `rcases hR with ⟨hrefl, hsymm, htrans⟩`, или
-- `obtain ⟨hrefl, hsymm, htrans⟩ := hR`
rcases hR with ⟨hrefl, hsymm, htrans⟩,
exact hrefl a,
end
-- Если `a` лежит в классе `b`, то весь класс `a` - подмножество класса `b`
lemma cl_sub_cl_of_mem_cl {a b : α} (hR : equivalence R) : a ∈ cl R b → cl R a ⊆ cl R b :=
begin
rcases hR with ⟨hrefl, hsymm, htrans⟩,
rintro h x Rxa,
exact htrans Rxa h,
end
-- Напоминание: `set.subset.antisymm : X ⊆ Y → Y ⊆ X → X = Y`
lemma cl_eq_cl_of_mem_cl {a b : α} (hR : equivalence R) : a ∈ cl R b → cl R a = cl R b :=
begin
intro h,
apply set.subset.antisymm,
refine cl_sub_cl_of_mem_cl R hR h,
refine cl_sub_cl_of_mem_cl R hR _,
exact hR.2.1 h,
end
end equivalence_classes
open partition
-- Чтобы доказать эквивалентность двух типов `X ≃ Y`, нужно построить преобразование `X → Y`, обратное преобразование `Y → X`, а также доказать, что эти два преобразования взаимнообратны
-- Далее внутри будут огромные и страшные цели, но мы их будем менять на эквивалентные с помощью тактик `change` и `show`
--
example (α : Type) : {R : α → α → Prop // equivalence R} ≃ partition α :=
{ -- Преобразуем отношение эквивалентности `R`в разбиение:
to_fun := λ R, {
-- Возьмем за `C` множество классов эквивалентности всех элементов типа `α` по отношению R
C := { B : set α | ∃ x : α, B = cl R.1 x},
-- Докажем, что такое множество блоков является разбиением. Для этого нужно доказать три свойства разбиений: `Hnonempty`, `Hcover` и `Hdisjoint`. Докажем их:
Hnonempty := begin
-- Любый класс эквивалентности непуст.
cases R with R hR,
change ∀ (X : set α), (∃ (a : α), X = cl R a) → X.nonempty,
rintro X ⟨a, rfl⟩,
-- Крутой хак: вместо того, чтобы гипотезу вида `A = B` сохранять в переменную, можно в `rintro` и `rcases` написать `rfl` вместо названия, и (если это корректно), во всех местах `A` заменится на `B` и уйдет из контекста
use a,
apply mem_cl_self R hR,
end,
Hcover := begin
-- Каждый элемент типа `α` содержится хотя бы в одном классе эквивалентности.
cases R with R hR,
change ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X,
intro a,
use [cl R a],
refine ⟨⟨a, rfl⟩, mem_cl_self R hR _⟩,
end,
Hdisjoint := begin
-- Если два класса эквивалентности пересекаются, то они равны.
cases R with R hR,
change ∀ (X Y : set α), (∃ (a : α), X = cl R a) →
(∃ (b : α), Y = cl _ b) → (X ∩ Y).nonempty → X = Y,
rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩ ⟨c, ⟨Rac, Rbc⟩⟩,
apply cl_eq_cl_of_mem_cl R hR,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
refine htrans _ Rbc,
refine hsymm Rac,
end },
-- Теперь построим отношение эквивалентности по разбиению
inv_fun := λ P,
-- Определим бинарное отношение `R`:
-- `R a b` если любой блок, содержащий `a`, также содержит `b`.
⟨λ a b, ∀ X ∈ P.C, a ∈ X → b ∈ X, begin
-- Докажем, что это отношение эквивалентности
split,
{ -- Оно рефлексивно
unfold reflexive,
rintro x A hA xA,
exact xA,
},
split,
{ -- Оно симметрично
unfold symmetric,
rintro x y hxy X hX yX,
obtain ⟨Y, hY, xY⟩ := P.Hcover x,
specialize hxy Y hY xY,
have h := eq_of_mem hX hY yX hxy,
rwa h,
},
{ -- Оно транзитивно
unfold transitive,
show ∀ (a b c : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
(∀ (X : set α), X ∈ P.C → b ∈ X → c ∈ X) →
∀ (X : set α), X ∈ P.C → a ∈ X → c ∈ X,
rintro a b c hab hbc X hX aX,
apply hbc X hX,
apply hab X hX,
exact aX,
}
end⟩,
-- Если начать с отношения `R` и сделать оба преобразования, снова получится `R`
left_inv := begin
rintro ⟨R, hR⟩,
-- Страшная цель, но она эквивалентна следующей:
suffices h : (λ (a b : α), ∀ (c : α), a ∈ cl R c → b ∈ cl R c) = R,
simpa using h,
-- ... и теперь докажем, что два отношения совпадают, тактика `ext` превратит цель в равенство для конкретных `a` и `b`
ext a b,
split, {
intro h,
specialize h a (mem_cl_self _ hR _),
apply hR.2.1, -- симметричность
exact h,
}, {
rintro hab c Rac,
-- упростим всё до вида R _ _
rw [cl, set.mem_set_of_eq] at *,
-- hR.2.2 - транзитивность
apply hR.2.2 (hR.2.1 hab) Rac,
}
end,
-- Аналогично, если начать с разбиения и сделать два преобразования, получится то же разбиение
right_inv := begin
intro P,
ext X,
show (∃ (a : α), X = cl _ a) ↔ X ∈ P.C,
dsimp only,
split, {
rintro ⟨a, ha⟩,
obtain ⟨Y, hY, aY⟩ := P.Hcover a,
-- Достаточно показать, что `X` это то же самое, что блок `Y`, покрывающий `a`
suffices hXY : X = Y, {
rwa hXY,
},
subst ha,
ext t, split, {
intro ht,
-- Теперь, когда есть элемент типа t ∈ <страшное выражение>, его можно упростить
-- `squeeze_simp` покажет минимальное множество использованных лемм и предложит заменить на `simp only [...]`
-- такое применение предпочтительно, потому что в будущем множество лемм для `simp` может измениться, и старые доказательства сломаются
-- также часто нетерминальные (те, что не закрывают цель) `simp` не слишком одобряются, поэтому предпочитают `simp only`
squeeze_simp [cl] at ht,
obtain ⟨Z, hZ, tZ⟩ := P.Hcover t,
have aZ := ht Z hZ tZ,
-- a ∈ Y ∧ a ∈ Z → Y = Z
have hYZ := eq_of_mem hY hZ aY aZ,
rwa hYZ,
}, {
simp [cl],
rintro tY Z hZ tZ,
refine mem_of_mem hY hZ tY tZ aY,
}
}, {
intro hX,
obtain ⟨a, aX⟩ := P.Hnonempty X hX,
use a,
ext t, split, {
simp [cl],
rintro tX Y hY tY,
refine mem_of_mem hX hY tX tY aX,
}, {
simp [cl],
intro h,
obtain ⟨Y, hY, tY⟩ := P.Hcover t,
refine mem_of_mem hY hX _ aX tY,
-- осталось ⊢ a ∈ Y
apply h Y hY tY,
}
}
end }
|
f305135b4e4efebfe137eea78a66cc7b0143b80d | 4484372104c20d5ccb4c725f0a5708632be2bfaa | /Maths_Challenges/solutions/solution3.lean | 0657d3d8d2ace0381e2146380ae2c10bb0a633ba | [] | no_license | robertylewis/xena | 45eecd4a06b4248683e84f32fdd496f7a5ebb0ec | 8c7e9fc2662171fdaacfde871bdc032693df83ce | refs/heads/master | 1,606,353,192,576 | 1,576,659,298,000 | 1,576,659,298,000 | 228,918,214 | 0 | 0 | null | 1,576,701,677,000 | 1,576,701,677,000 | null | UTF-8 | Lean | false | false | 89 | lean | import data.real.basic
theorem challenge2 :
(2 : ℝ) + 2 ≠ 5 :=
begin
norm_num
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.