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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16911c04684fbc82ed35886a9ee9e4495093405f | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /algebra/group_power.lean | 18a5f65da93aaef2da776409c4db95fa9e21decd | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 16,371 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
The power operation on monoids and groups. We separate this from group, because it depends on
nat, which in turn depends on other parts of algebra.
We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation
a^n is used for the first, but users can locally redefine it to gpow when needed.
Note: power adopts the convention that 0^0=1.
-/
import algebra.char_zero data.int.basic algebra.group algebra.ordered_field data.list.basic
universes u v
variable {α : Type u}
@[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one]
@[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a :=
by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div]; simp [div_one]
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow [monoid α] (a : α) : ℕ → α
| 0 := 1
| (n+1) := a * monoid.pow n
def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α :=
@monoid.pow (multiplicative α) _ a n
precedence `•`:70
local infix ` • ` := add_monoid.smul
@[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩
/- monoid -/
section monoid
variables [monoid α] {β : Type u} [add_monoid β]
@[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl
@[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl
attribute [to_additive add_monoid.zero_smul] pow_zero
theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl
theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl
attribute [to_additive succ_smul] pow_succ
@[simp] theorem pow_one (a : α) : a^1 = a := mul_one _
@[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _
attribute [to_additive add_monoid.one_smul] pow_one
theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n :=
by induction n with n ih; simp [*, pow_succ, mul_assoc]
theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a :=
@pow_mul_comm' (multiplicative β) _
theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a :=
by simp [pow_succ, pow_mul_comm']
theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a :=
by simp [succ_smul, smul_add_comm']
attribute [to_additive succ_smul'] pow_succ'
theorem pow_two (a : α) : a^2 = a * a :=
by simp [pow_succ]
theorem two_smul (a : β) : 2•a = a + a :=
by simp [succ_smul]
attribute [to_additive two_smul] pow_two
theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n; simp [*, pow_succ', nat.add_succ, mul_assoc]
theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a :=
@pow_add (multiplicative β) _
attribute [to_additive add_monoid.add_smul] pow_add
@[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) :=
by induction n; simp [*, pow_succ]
@[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) :=
by induction n; simp [*, succ_smul]
attribute [to_additive add_monoid.smul_zero] one_pow
theorem pow_mul (a : α) (m : ℕ) : ∀ n, a^(m * n) = (a^m)^n
| 0 := by simp
| (n+1) := by rw [nat.mul_succ, pow_add, pow_succ', pow_mul]
theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) :=
@pow_mul (multiplicative β) _
attribute [to_additive add_monoid.mul_smul'] pow_mul
theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [mul_comm, pow_mul]
theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) :=
by rw [mul_comm, add_monoid.mul_smul']
attribute [to_additive add_monoid.mul_smul] pow_mul'
@[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n :=
nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _)
theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _
attribute [to_additive bit0_smul] pow_bit0
theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a :=
@pow_bit1 (multiplicative β) _
attribute [to_additive bit1_smul] pow_bit1
theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m :=
by rw [←pow_add, ←pow_add, add_comm]
theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a :=
@pow_mul_comm (multiplicative β) _
attribute [to_additive smul_add_comm] pow_mul_comm
@[simp] theorem list.prod_repeat (a : α) : ∀ (n : ℕ), (list.repeat a n).prod = a ^ n
| 0 := rfl
| (n+1) := by simp [pow_succ, list.prod_repeat n]
@[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a :=
@list.prod_repeat (multiplicative β) _
attribute [to_additive list.sum_repeat] list.prod_repeat
end monoid
@[simp] theorem nat.pow_eq_pow (p q : ℕ) :
@has_pow.pow _ _ monoid.has_pow p q = p ^ q :=
by induction q; [refl, simp [nat.pow_succ, pow_succ, mul_comm, *]]
@[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n :=
by rw mul_comm; induction m; simp [succ_smul', nat.mul_succ, *]
/- commutative monoid -/
section comm_monoid
variables [comm_monoid α] {β : Type*} [add_comm_monoid β]
theorem mul_pow (a b : α) : ∀ n:ℕ, (a * b)^n = a^n * b^n
| 0 := by simp
| (n+1) := by simp [pow_succ, mul_assoc, mul_left_comm]; rw mul_pow
theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b :=
@mul_pow (multiplicative β) _
attribute [to_additive add_monoid.add_smul] mul_pow
end comm_monoid
section group
variables [group α] {β : Type*} [add_group β]
section nat
@[simp] theorem inv_pow (a : α) : ∀n:ℕ, (a⁻¹)^n = (a^n)⁻¹
| 0 := by simp
| (n+1) := by rw [pow_succ', pow_succ, mul_inv_rev, inv_pow]
@[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) :=
@inv_pow (multiplicative β) _
attribute [to_additive add_monoid.neg_smul] inv_pow
theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : 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],
eq_mul_inv_of_mul_eq h2
theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, m ≥ n → (m - n)•a = m•a - n•a :=
@pow_sub (multiplicative β) _
attribute [to_additive add_monoid.smul_sub] inv_pow
theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _)
theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) :=
@pow_inv_comm (multiplicative β) _
attribute [to_additive add_monoid.smul_neg_comm] pow_inv_comm
end nat
open int
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow (a : α) : ℤ → α
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
def gsmul (n : ℤ) (a : β) : β :=
@gpow (multiplicative β) _ a n
@[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩
local infix ` • `:70 := gsmul
local infix ` •ℕ `:70 := add_monoid.smul
@[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
@[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl
attribute [to_additive gsmul_coe_nat] gpow_coe_nat
@[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
@[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl
attribute [to_additive gsmul_of_nat] gpow_of_nat
@[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
@[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl
attribute [to_additive gsmul_neg_succ] gpow_neg_succ
local attribute [ematch] le_of_lt
open nat
@[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl
attribute [to_additive zero_gsmul] gpow_zero
@[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _
attribute [to_additive one_gsmul] gpow_one
@[simp, to_additive zero_gsmul]
theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := by simp
@[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := one_inv.symm
| -[1+ n] := (inv_inv _).symm
@[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) :=
@gpow_neg (multiplicative β) _
attribute [to_additive neg_gsmul] gpow_neg
theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := by simp
theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := by simp
attribute [to_additive neg_one_gsmul] gpow_neg_one
@[to_additive neg_gsmul]
theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow a n
| -[1+ n] := by simp [inv_pow]
private lemma gpow_add_aux (a : α) (m n : nat) :
a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] :=
or.elim (nat.lt_or_ge m (nat.succ n))
(assume : m < succ n,
have m ≤ n, from le_of_lt_succ this,
suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by simp [*, of_nat_add_neg_succ_of_nat_of_lt],
suffices (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], from this,
suffices (a ^ (nat.succ n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw ←succ_sub; assumption,
by rw pow_sub; finish [gpow])
(assume : m ≥ succ n,
suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]),
by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption,
suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this,
by rw pow_sub; assumption)
theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j
| (of_nat m) (of_nat n) := pow_add _ _ _
| (of_nat m) -[1+n] := gpow_add_aux _ _ _
| -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux,
gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm]
| -[1+m] -[1+n] :=
suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this,
by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev]
theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a :=
@gpow_add (multiplicative β) _
theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a :=
@gpow_mul_comm (multiplicative β) _
attribute [to_additive gsmul_add_comm] gpow_mul_comm
theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $
show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by simp [pow_mul]
| -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ by simp
theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) :=
@gpow_mul (multiplicative β) _
attribute [to_additive gsmul_mul'] gpow_mul
theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) :=
by rw [mul_comm, gsmul_mul']
attribute [to_additive gsmul_mul] gpow_mul'
theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _
attribute [to_additive bit0_gsmul] gpow_bit0
theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add]; simp [gpow_bit0]
theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a :=
@gpow_bit1 (multiplicative β) _
attribute [to_additive bit1_gsmul] gpow_bit1
end group
local infix ` •ℤ `:70 := gsmul
theorem add_monoid.smul_eq_mul' [semiring α] (a : α) : ∀ n : ℕ, n • a = a * n
| 0 := by simp
| (n+1) := by simp [add_monoid.smul_eq_mul' n, mul_add, succ_smul']
theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a :=
by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm]
theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) :=
by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc]
theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b :=
by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc]
theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := by simp [add_monoid.smul_eq_mul]
| -[1+ n] := by simp [add_monoid.smul_eq_mul, -add_comm, add_mul]
theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, int.mul_cast_comm]
theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
by induction n with n ih; simp [pow_succ, mul_eq_zero, *]
@[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) : ∀ n : ℕ, (1 / a) ^ n = 1 / a ^ n
| 0 := by simp
| (n+1) := by rw [pow_succ', pow_succ,
← division_ring.one_div_mul_one_div (pow_ne_zero n ha) ha, one_div_pow]
@[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ :=
by simp [inv_eq_one_div, -one_div_eq_inv, ha]
@[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div]
theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a
| 0 := le_refl _
| (n+1) := add_nonneg' H (add_monoid.smul_nonneg n)
lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) :=
by induction n; simp [*, pow_succ, abs_mul]
lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n
| 0 ha := by simp [pow_zero]
| (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha]
section linear_ordered_semiring
variable [linear_ordered_semiring α]
theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := by simp [zero_lt_one]
| (n+1) := by simpa [pow_succ] using mul_pos H (pow_pos _)
theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := by simp [zero_le_one]
| (n+1) := by simpa [pow_succ] using mul_nonneg H (pow_nonneg _)
theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := by simp; apply le_refl
| (n+1) :=
begin
simp [pow_succ], rw ← one_mul (1 : α),
apply mul_le_mul,
assumption,
apply one_le_pow_of_one_le,
apply zero_le_one,
transitivity, apply zero_le_one, assumption
end
theorem pow_ge_one_add_mul {a : α} (H : a ≥ 0) :
∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n
| 0 := by simp
| (n+1) := begin
rw [pow_succ', succ_smul'],
refine le_trans _ (mul_le_mul_of_nonneg_right
(pow_ge_one_add_mul n) (add_nonneg zero_le_one H)),
rw [mul_add, mul_one, ← add_assoc, add_le_add_iff_left],
simpa using mul_le_mul_of_nonneg_right
((le_add_iff_nonneg_right 1).2 (add_monoid.smul_nonneg H n)) H
end
theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
let ⟨k, hk⟩ := nat.le.dest h in
calc a ^ n = a ^ n * 1 : by simp
... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left
(one_le_pow_of_one_le ha _)
(pow_nonneg (le_trans zero_le_one ha) _)
... = a ^ m : by rw [←hk, pow_add]
end linear_ordered_semiring
theorem pow_ge_one_add_sub_mul [linear_ordered_ring α]
{a : α} (H : a ≥ 1) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n :=
by simpa using pow_ge_one_add_mul (sub_nonneg.2 H) n
|
7a04ec5a7fc1a7c3d373910dba8a672f5de6fcc4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Module/projective.lean | 4ae2bb3bf189842a73e239fdc3a6907c912f9152 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 2,162 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Scott Morrison
-/
import algebra.category.Module.epi_mono
import algebra.module.projective
import category_theory.preadditive.projective
import linear_algebra.finsupp_vector_space
/-!
# The category of `R`-modules has enough projectives.
-/
universes v u
open category_theory
open category_theory.limits
open linear_map
open_locale Module
/-- The categorical notion of projective object agrees with the explicit module-theoretic notion. -/
theorem is_projective.iff_projective {R : Type u} [ring R]
{P : Type (max u v)} [add_comm_group P] [module R P] :
module.projective R P ↔ projective (Module.of R P) :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ letI : module.projective R ↥(Module.of R P) := h,
exact ⟨λ E X f e epi, module.projective_lifting_property _ _
((Module.epi_iff_surjective _).mp epi)⟩ },
{ refine module.projective_of_lifting_property _,
introsI E X mE mX sE sX f g s,
haveI : epi ↟f := (Module.epi_iff_surjective ↟f).mpr s,
letI : projective (Module.of R P) := h,
exact ⟨projective.factor_thru ↟g ↟f, projective.factor_thru_comp ↟g ↟f⟩ }
end
namespace Module
variables {R : Type u} [ring R] {M : Module.{max u v} R}
/-- Modules that have a basis are projective. -/
-- We transport the corresponding result from `module.projective`.
lemma projective_of_free {ι : Type*} (b : basis ι R M) : projective M :=
projective.of_iso (Module.of_self_iso _)
((is_projective.iff_projective).mp (module.projective_of_basis b))
/-- The category of modules has enough projectives, since every module is a quotient of a free
module. -/
instance Module_enough_projectives : enough_projectives (Module.{max u v} R) :=
{ presentation :=
λ M,
⟨{ P := Module.of R (M →₀ R),
projective := projective_of_free finsupp.basis_single_one,
f := finsupp.basis_single_one.constr ℕ id,
epi := (epi_iff_range_eq_top _).mpr
(range_eq_top.2 (λ m, ⟨finsupp.single m (1 : R), by simp [basis.constr]⟩)) }⟩, }
end Module
|
a69d6f13edd8048d4ffeedd401468165e3118a32 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Lean/Attributes.lean | d43cb89a0b5de2564e4c802c766a925b5820aab6 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,398 | 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.Syntax
import Lean.CoreM
import Lean.ResolveName
namespace Lean
inductive AttributeApplicationTime
| afterTypeChecking | afterCompilation | beforeElaboration
def AttributeApplicationTime.beq : AttributeApplicationTime → AttributeApplicationTime → Bool
| AttributeApplicationTime.afterTypeChecking, AttributeApplicationTime.afterTypeChecking => true
| AttributeApplicationTime.afterCompilation, AttributeApplicationTime.afterCompilation => true
| AttributeApplicationTime.beforeElaboration, AttributeApplicationTime.beforeElaboration => true
| _, _ => false
instance : BEq AttributeApplicationTime := ⟨AttributeApplicationTime.beq⟩
structure Attr.Context :=
(currNamespace : Name)
(openDecls : List OpenDecl)
abbrev AttrM := ReaderT Attr.Context CoreM
instance : MonadResolveName AttrM := {
getCurrNamespace := do pure (← read).currNamespace,
getOpenDecls := do pure (← read).openDecls
}
structure AttributeImplCore :=
(name : Name)
(descr : String)
(applicationTime := AttributeApplicationTime.afterTypeChecking)
structure AttributeImpl extends AttributeImplCore :=
(add (decl : Name) (args : Syntax) (persistent : Bool) : AttrM Unit)
instance : Inhabited AttributeImpl :=
⟨{ name := arbitrary _, descr := arbitrary _, add := fun env _ _ _ => pure () }⟩
open Std (PersistentHashMap)
builtin_initialize attributeMapRef : IO.Ref (PersistentHashMap Name AttributeImpl) ← IO.mkRef {}
/- Low level attribute registration function. -/
def registerBuiltinAttribute (attr : AttributeImpl) : IO Unit := do
let m ← attributeMapRef.get
if m.contains attr.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attr.name ++ "' has already been used"))
unless (← IO.initializing) do throw (IO.userError "failed to register attribute, attributes can only be registered during initialization")
attributeMapRef.modify fun m => m.insert attr.name attr
abbrev AttributeImplBuilder := List DataValue → Except String AttributeImpl
abbrev AttributeImplBuilderTable := Std.HashMap Name AttributeImplBuilder
builtin_initialize attributeImplBuilderTableRef : IO.Ref AttributeImplBuilderTable ← IO.mkRef {}
def registerAttributeImplBuilder (builderId : Name) (builder : AttributeImplBuilder) : IO Unit := do
let table ← attributeImplBuilderTableRef.get
if table.contains builderId then throw (IO.userError ("attribute implementation builder '" ++ toString builderId ++ "' has already been declared"))
attributeImplBuilderTableRef.modify fun table => table.insert builderId builder
def mkAttributeImplOfBuilder (builderId : Name) (args : List DataValue) : IO AttributeImpl := do
let table ← attributeImplBuilderTableRef.get
match table.find? builderId with
| none => throw (IO.userError ("unknown attribute implementation builder '" ++ toString builderId ++ "'"))
| some builder => IO.ofExcept $ builder args
inductive AttributeExtensionOLeanEntry
| decl (declName : Name) -- `declName` has type `AttributeImpl`
| builder (builderId : Name) (args : List DataValue)
structure AttributeExtensionState :=
(newEntries : List AttributeExtensionOLeanEntry := [])
(map : PersistentHashMap Name AttributeImpl)
abbrev AttributeExtension := PersistentEnvExtension AttributeExtensionOLeanEntry (AttributeExtensionOLeanEntry × AttributeImpl) AttributeExtensionState
instance : Inhabited AttributeExtensionState := ⟨{ map := {} }⟩
private def AttributeExtension.mkInitial : IO AttributeExtensionState := do
let map ← attributeMapRef.get
pure { map := map }
unsafe def mkAttributeImplOfConstantUnsafe (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl :=
match env.find? declName with
| none => throw ("unknow constant '" ++ toString declName ++ "'")
| some info =>
match info.type with
| Expr.const `Lean.AttributeImpl _ _ => env.evalConst AttributeImpl opts declName
| _ => throw ("unexpected attribute implementation type at '" ++ toString declName ++ "' (`AttributeImpl` expected")
@[implementedBy mkAttributeImplOfConstantUnsafe]
constant mkAttributeImplOfConstant (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl
def mkAttributeImplOfEntry (env : Environment) (opts : Options) (e : AttributeExtensionOLeanEntry) : IO AttributeImpl :=
match e with
| AttributeExtensionOLeanEntry.decl declName => IO.ofExcept $ mkAttributeImplOfConstant env opts declName
| AttributeExtensionOLeanEntry.builder builderId args => mkAttributeImplOfBuilder builderId args
private def AttributeExtension.addImported (es : Array (Array AttributeExtensionOLeanEntry)) : ImportM AttributeExtensionState := do
let ctx ← read
let map ← attributeMapRef.get
let map ← es.foldlM
(fun map entries =>
entries.foldlM
(fun (map : PersistentHashMap Name AttributeImpl) entry => do
let attrImpl ← liftM $ mkAttributeImplOfEntry ctx.env ctx.opts entry
pure $ map.insert attrImpl.name attrImpl)
map)
map
pure { map := map }
private def addAttrEntry (s : AttributeExtensionState) (e : AttributeExtensionOLeanEntry × AttributeImpl) : AttributeExtensionState :=
{ s with map := s.map.insert e.2.name e.2, newEntries := e.1 :: s.newEntries }
builtin_initialize attributeExtension : AttributeExtension ←
registerPersistentEnvExtension {
name := `attrExt,
mkInitial := AttributeExtension.mkInitial,
addImportedFn := AttributeExtension.addImported,
addEntryFn := addAttrEntry,
exportEntriesFn := fun s => s.newEntries.reverse.toArray,
statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length
}
/- Return true iff `n` is the name of a registered attribute. -/
@[export lean_is_attribute]
def isBuiltinAttribute (n : Name) : IO Bool := do
let m ← attributeMapRef.get; pure (m.contains n)
/- Return the name of all registered attributes. -/
def getBuiltinAttributeNames : IO (List Name) := do
let m ← attributeMapRef.get; pure $ m.foldl (fun r n _ => n::r) []
def getBuiltinAttributeImpl (attrName : Name) : IO AttributeImpl := do
let m ← attributeMapRef.get
match m.find? attrName with
| some attr => pure attr
| none => throw (IO.userError ("unknown attribute '" ++ toString attrName ++ "'"))
@[export lean_attribute_application_time]
def getBuiltinAttributeApplicationTime (n : Name) : IO AttributeApplicationTime := do
let attr ← getBuiltinAttributeImpl n
pure attr.applicationTime
def isAttribute (env : Environment) (attrName : Name) : Bool :=
(attributeExtension.getState env).map.contains attrName
def getAttributeNames (env : Environment) : List Name :=
let m := (attributeExtension.getState env).map
m.foldl (fun r n _ => n::r) []
def getAttributeImpl (env : Environment) (attrName : Name) : Except String AttributeImpl :=
let m := (attributeExtension.getState env).map
match m.find? attrName with
| some attr => pure attr
| none => throw ("unknown attribute '" ++ toString attrName ++ "'")
def registerAttributeOfDecl (env : Environment) (opts : Options) (attrDeclName : Name) : Except String Environment := do
let attrImpl ← mkAttributeImplOfConstant env opts attrDeclName
if isAttribute env attrImpl.name then
throw ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used")
else
pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.decl attrDeclName, attrImpl)
def registerAttributeOfBuilder (env : Environment) (builderId : Name) (args : List DataValue) : IO Environment := do
let attrImpl ← mkAttributeImplOfBuilder builderId args
if isAttribute env attrImpl.name then
throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used"))
else
pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.builder builderId args, attrImpl)
def addAttribute (decl : Name) (attrName : Name) (args : Syntax) (persistent : Bool := true) : AttrM Unit := do
let env ← getEnv
let attr ← ofExcept $ getAttributeImpl env attrName
attr.add decl args persistent
/--
Tag attributes are simple and efficient. They are useful for marking declarations in the modules where
they were defined.
The startup cost for this kind of attribute is very small since `addImportedFn` is a constant function.
They provide the predicate `tagAttr.hasTag env decl` which returns true iff declaration `decl`
is tagged in the environment `env`. -/
structure TagAttribute :=
(attr : AttributeImpl)
(ext : PersistentEnvExtension Name Name NameSet)
def registerTagAttribute (name : Name) (descr : String) (validate : Name → AttrM Unit := fun _ => pure ()) : IO TagAttribute := do
let ext : PersistentEnvExtension Name Name NameSet ← registerPersistentEnvExtension {
name := name,
mkInitial := pure {},
addImportedFn := fun _ _ => pure {},
addEntryFn := fun (s : NameSet) n => s.insert n,
exportEntriesFn := fun es =>
let r : Array Name := es.fold (fun a e => a.push e) #[]
r.qsort Name.quickLt,
statsFn := fun s => "tag attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrImpl : AttributeImpl := {
name := name,
descr := descr,
add := fun decl args persistent => do
if args.hasArgs then throwError! "invalid attribute '{name}', unexpected argument"
unless persistent do throwError! "invalid attribute '{name}', must be persistent"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError! "invalid attribute '{name}', declaration is in an imported module"
validate decl
let env ← getEnv
setEnv $ ext.addEntry env decl
}
registerBuiltinAttribute attrImpl
pure { attr := attrImpl, ext := ext }
namespace TagAttribute
instance : Inhabited TagAttribute := ⟨{attr := arbitrary _, ext := arbitrary _}⟩
def hasTag (attr : TagAttribute) (env : Environment) (decl : Name) : Bool :=
match env.getModuleIdxFor? decl with
| some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt
| none => (attr.ext.getState env).contains decl
end TagAttribute
/--
A `TagAttribute` variant where we can attach parameters to attributes.
It is slightly more expensive and consumes a little bit more memory than `TagAttribute`.
They provide the function `pAttr.getParam env decl` which returns `some p` iff declaration `decl`
contains the attribute `pAttr` with parameter `p`. -/
structure ParametricAttribute (α : Type) :=
(attr : AttributeImpl)
(ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α))
structure ParametricAttributeImpl (α : Type) extends AttributeImplCore :=
(getParam : Name → Syntax → AttrM α)
(afterSet : Name → α → AttrM Unit := fun env _ _ => pure ())
(afterImport : Array (Array (Name × α)) → ImportM Unit := fun _ => pure ())
def registerParametricAttribute {α : Type} [Inhabited α] (impl : ParametricAttributeImpl α) : IO (ParametricAttribute α) := do
let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := impl.name,
mkInitial := pure {},
addImportedFn := fun s => impl.afterImport s *> pure {},
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2,
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[]
r.qsort (fun a b => Name.quickLt a.1 b.1),
statsFn := fun s => "parametric attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrImpl : AttributeImpl := { impl with
add := fun decl args persistent => do
unless persistent do throwError! "invalid attribute '{impl.name}', must be persistent"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError! "invalid attribute '{impl.name}', declaration is in an imported module"
let val ← impl.getParam decl args
let env' := ext.addEntry env (decl, val)
setEnv env'
try impl.afterSet decl val catch _ => setEnv env
}
registerBuiltinAttribute attrImpl
pure { attr := attrImpl, ext := ext }
namespace ParametricAttribute
instance {α : Type} : Inhabited (ParametricAttribute α) := ⟨{attr := arbitrary _, ext := arbitrary _}⟩
def getParam {α : Type} [Inhabited α] (attr : ParametricAttribute α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setParam {α : Type} (attr : ParametricAttribute α) (env : Environment) (decl : Name) (param : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, declaration is in an imported module")
else if ((attr.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, attribute has already been set")
else
Except.ok (attr.ext.addEntry env (decl, param))
end ParametricAttribute
/-
Given a list `[a₁, ..., a_n]` of elements of type `α`, `EnumAttributes` provides an attribute `Attr_i` for
associating a value `a_i` with an declaration. `α` is usually an enumeration type.
Note that whenever we register an `EnumAttributes`, we create `n` attributes, but only one environment extension. -/
structure EnumAttributes (α : Type) :=
(attrs : List AttributeImpl)
(ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α))
def registerEnumAttributes {α : Type} [Inhabited α] (extName : Name) (attrDescrs : List (Name × String × α))
(validate : Name → α → AttrM Unit := fun _ _ => pure ())
(applicationTime := AttributeApplicationTime.afterTypeChecking) : IO (EnumAttributes α) := do
let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := extName,
mkInitial := pure {},
addImportedFn := fun _ _ => pure {},
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2,
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[]
r.qsort (fun a b => Name.quickLt a.1 b.1),
statsFn := fun s => "enumeration attribute extension" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrs := attrDescrs.map fun (name, descr, val) => {
name := name,
descr := descr,
add := fun decl args persistent => do
unless persistent do throwError! "invalid attribute '{name}', must be persistent"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError! "invalid attribute '{name}', declaration is in an imported module"
validate decl val
setEnv $ ext.addEntry env (decl, val),
applicationTime := applicationTime
: AttributeImpl
}
attrs.forM registerBuiltinAttribute
pure { ext := ext, attrs := attrs }
namespace EnumAttributes
instance {α : Type} : Inhabited (EnumAttributes α) := ⟨{attrs := [], ext := arbitrary _}⟩
def getValue {α : Type} [Inhabited α] (attr : EnumAttributes α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setValue {α : Type} (attrs : EnumAttributes α) (env : Environment) (decl : Name) (val : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, declaration is in an imported module")
else if ((attrs.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, attribute has already been set")
else
Except.ok (attrs.ext.addEntry env (decl, val))
end EnumAttributes
/--
Helper function for converting a Syntax object representing attribute parameters into an identifier.
It returns `none` if the parameter is not a simple identifier.
Remark: in the future, attributes should define their own parsers, and we should use `match_syntax` to
decode the Syntax object. -/
def attrParamSyntaxToIdentifier (s : Syntax) : Option Name :=
match s with
| Syntax.node k args =>
if k == nullKind && args.size == 1 then match args.get! 0 with
| Syntax.ident _ _ id _ => some id
| _ => none
else
none
| _ => none
end Lean
|
ee89c276ef4e51af0472f6954efb8ffc1db9f9a3 | b522075d31b564daeb3347a10eb9bb777ee93943 | /map.lean | da94f3174b1a4eccdfd9f85d77cb95321183e4ae | [] | no_license | truonghoangle/manifolds | e6c2534dd46579f56ba99a48e2eb7ce51640e7c0 | 9c0d731a480e88758180b31ce7c3b371771d426b | refs/heads/master | 1,638,501,090,139 | 1,557,991,948,000 | 1,557,991,948,000 | 185,779,631 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,051 | lean | /-
Copyright (c) 2019 Joe Cool. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Hoang Le Truong.
-/
import algebra.module data.pfun
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
local attribute [instance] classical.prop_decidable
namespace map
protected def has_zero [has_zero β] : has_zero (α → β) := ⟨λ x, 0⟩
lemma zero_def [has_zero β] (x:α) : @has_zero.zero _ map.has_zero x = 0 := rfl
protected def has_one [has_one β] : has_one (α → β ) := ⟨λ x, (1:β) ⟩
lemma one_def [has_one β] (x:α) : @has_one.one _ map.has_one x = 1 := rfl
protected def has_mul [has_mul β] : has_mul (α → β ) := ⟨λ x y, λ z, x z * y z⟩
lemma mul_def [has_mul β] (x y : α→ β) (z:α) : @has_mul.mul _ map.has_mul x y z= (x z) * (y z) := rfl
protected def has_add [has_add β] : has_add(α → β ) := ⟨λ f g, λ z, f z + g z⟩
lemma add_def [has_add β] (x y : α→ β) (z:α) : @has_add.add _ map.has_add x y z = x z + y z := rfl
protected def has_inv [has_inv β] : has_inv (α → β ) := ⟨λ x, λ y, (x y )⁻¹⟩
lemma inv_def [has_inv β] (x : α → β ) (y: α) : @has_inv.inv _ map.has_inv x y = (x y)⁻¹ := rfl
protected def has_neg [has_neg β] : has_neg (α → β ) := ⟨λ x, λ y, -x y⟩
lemma neg_def [has_neg β] (x : α → β ) (y:α) : @has_neg.neg _ map.has_neg x y = - x y := rfl
protected def has_scalar [has_scalar γ β] : has_scalar γ (α → β ) := ⟨λ a x , λ y, a • x y⟩
lemma smul_def [has_scalar γ β] (a:γ) (x : α → β ) (y:α) : @has_scalar.smul _ _ map.has_scalar a x y = a • x y := rfl
protected def semigroup [semigroup β] : semigroup (α → β) :=
{ mul_assoc := by simp [mul_def, mul_assoc],
..map.has_mul }
protected def comm_semigroup [comm_semigroup β] : comm_semigroup (α → β ) :=
{ mul_comm := by { repeat{intro}, ext1, simp [mul_def, mul_comm]}
..map.semigroup }
protected def monoid [monoid β] : monoid (α → β ) :=
{ monoid.
mul := map.has_mul.mul,
mul_assoc := by simp [mul_def, mul_assoc],
one := λ x:α, (1:β),
one_mul := by {intro, ext1, simp [mul_def, map.one_def]},
mul_one := by {intro, ext1, simp [mul_def, map.one_def]}
}
protected def comm_monoid [comm_monoid β] : comm_monoid (α→ β) :=
{ ..map.comm_semigroup,
..map.monoid }
protected def group [group β] : group (α→ β ) :=
{ group.
mul := map.has_mul.mul,
mul_assoc := by simp [mul_def, mul_assoc],
one := λ x:α, (1:β),
one_mul := by {intro, ext1, simp [mul_def, map.one_def]},
mul_one := by {intro, ext1, simp [mul_def, map.one_def]},
mul_left_inv := by {intro, ext1, simp [mul_def, inv_def,map.one_def]},
..map.has_inv }
protected def comm_group [comm_group β] : comm_group (α→ β ) :=
{ ..map.group,
..map.comm_semigroup }
protected def add_semigroup [add_semigroup β] : add_semigroup (α → β ) :=
@additive.add_semigroup _ (@map.semigroup _ _ multiplicative.semigroup)
protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup (α → β ) :=
@additive.add_comm_semigroup _ (@map.comm_semigroup _ _ multiplicative.comm_semigroup)
protected def add_monoid [add_monoid β] : add_monoid (α → β ) :=
@additive.add_monoid _ (@map.monoid _ _ multiplicative.monoid)
protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α → β) :=
@additive.add_comm_monoid _ (@map.comm_monoid _ _ multiplicative.comm_monoid)
protected def add_group [add_group β] : add_group (α → β ) :=
@additive.add_group _ (@map.group _ _ multiplicative.group)
protected def add_comm_group [add_comm_group β] : add_comm_group (α → β ) :=
@additive.add_comm_group _ (@map.comm_group _ _ multiplicative.comm_group)
protected def semiring [semiring β] : semiring (α → β) :=
{ mul := map.has_mul.mul,
mul_assoc := by simp [mul_def, mul_assoc],
one := λ x:α, (1:β),
zero := λ x:α, (0:β),
one_mul := by {intro, ext1, simp [mul_def, map.one_def]},
mul_one := by {intro, ext1, simp [mul_def, map.one_def]},
right_distrib := by {repeat{intro}, ext1, simp [mul_def, add_def, add_mul]},
left_distrib := by {repeat{intro}, ext1, simp [mul_def, add_def, mul_add]},
zero_mul := by {repeat{intro}, ext1, simp [mul_def, zero_def]},
mul_zero := by {repeat{intro}, ext1, simp [mul_def, zero_def]},
..map.has_mul ,
..map.has_add ,
..map.add_comm_monoid }
protected def comm_semiring [comm_semiring β] : comm_semiring (α → β ) :=
{ ..map.semiring,
..map.comm_monoid }
protected def ring [ring β] : ring (α → β ) :=
{ ..map.semiring,
..map.add_comm_group }
protected def comm_ring [comm_ring β] : comm_ring (α→ β ) :=
{ ..map.comm_monoid ,
..map.ring }
protected def mul_action [monoid γ][mul_action γ β] :mul_action γ (α →β ):=
{ one_smul := by {repeat{intro}, simp[smul_def] },
mul_smul := by {repeat{intro},ext1, simp[smul_def,mul_smul] },
..map.has_scalar
}
instance add_monoid'[add_monoid β] : add_monoid (α → β) := map.add_monoid
protected def distrib_mul_action [monoid γ] [add_monoid β] [distrib_mul_action γ β] : distrib_mul_action γ (α → β):=
{ smul_add := by {repeat{intro}, ext1,simp[smul_def,add_def,smul_add ]},
smul_zero := by {repeat{intro}, ext1,simp only [smul_def], by library_search
},
..map.mul_action
}
instance add_comm_monoid'[add_comm_monoid β] : add_comm_monoid(α → β) := map.add_comm_monoid
protected def semimodule [semiring γ] [add_comm_monoid β] [semimodule γ β ]: semimodule γ (α → β):=
{ add_smul := by {repeat{intro}, ext1,simp[smul_def,add_def,add_smul ]},
zero_smul := by {repeat{intro}, ext1,simp only [smul_def], by library_search},
..map.distrib_mul_action}
instance add_comm_group'[add_comm_group β] : add_comm_group(α → β) := map.add_comm_group
protected def module [ring γ][add_comm_group β ] [module γ β] : module γ (α→ β ) :=
{..map.semimodule}
protected def vector_space [discrete_field γ][add_comm_group β ] [vector_space γ β] : vector_space γ (α→ β ) :=
{..map.semimodule}
end map
section const
noncomputable theory
variable [has_zero α]
def ext_by_zero (f : β →. α ) (z:β ): α := if h:z ∈ f.dom then f.fn z h else 0
def const_fun (c:α) : β →. α := pfun.lift (λ x, c)
lemma const_def (c:α) (y:β ) : const_fun c y = some c:= rfl
lemma ext_const (c:α):ext_by_zero (@const_fun α β _ c)= (λ x, c):=
by{ ext1,
have h:= @const_def α β _ c x,
rw[ext_by_zero],
simp[pfun.mem_dom,pfun.fn,h]
}
def zero_fun : β →. α := pfun.lift (λ x, 0)
lemma ext_zero:ext_by_zero (@zero_fun α β _ )= (λ x, 0):=
ext_const 0
def one_fun [has_one α]: β →. α := pfun.lift (λ x, 1)
lemma ext_one [has_one α]:ext_by_zero (@one_fun α β _ _)= (λ x, 1):=
ext_const 1
lemma const_incl_dom (c:α) (z:β ): z ∈ (pfun.dom (@const_fun α β _ c )) :=
by{ rw[pfun.dom_eq],simp[ const_def],}
end const
|
058dd6b3f450072a3dff2f1aa95a6011b66dc235 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/module/dedekind_domain.lean | c7e533928a18dcfccf021509a3e3d4575381a5a4 | [
"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,219 | lean | /-
Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pierre-Alexandre Bazin
-/
import algebra.module.torsion
import ring_theory.dedekind_domain.ideal
/-!
# Modules over a Dedekind domain
Over a Dedekind domain, a `I`-torsion module is the internal direct sum of its `p i ^ e i`-torsion
submodules, where `I = ∏ i, p i ^ e i` is its unique decomposition in prime ideals.
Therefore, as any finitely generated torsion module is `I`-torsion for some `I`, it is an internal
direct sum of its `p i ^ e i`-torsion submodules for some prime ideals `p i` and numbers `e i`.
-/
universes u v
open_locale big_operators
variables {R : Type u} [comm_ring R] [is_domain R] {M : Type v} [add_comm_group M] [module R M]
open_locale direct_sum
namespace submodule
variables [is_dedekind_domain R]
open unique_factorization_monoid
/--Over a Dedekind domain, a `I`-torsion module is the internal direct sum of its `p i ^ e i`-
torsion submodules, where `I = ∏ i, p i ^ e i` is its unique decomposition in prime ideals.-/
lemma is_internal_prime_power_torsion_of_is_torsion_by_ideal {I : ideal R} (hI : I ≠ ⊥)
(hM : module.is_torsion_by_set R M I) :
∃ (P : finset $ ideal R) [decidable_eq P] [∀ p ∈ P, prime p] (e : P → ℕ),
by exactI direct_sum.is_internal (λ p : P, torsion_by_set R M (p ^ e p : ideal R)) :=
begin
classical,
let P := factors I,
have prime_of_mem := λ p (hp : p ∈ P.to_finset), prime_of_factor p (multiset.mem_to_finset.mp hp),
refine ⟨P.to_finset, infer_instance, prime_of_mem, λ i, P.count i, _⟩,
apply @torsion_by_set_is_internal _ _ _ _ _ _ _ _ (λ p, p ^ P.count p) _,
{ convert hM,
rw [← finset.inf_eq_infi, is_dedekind_domain.inf_prime_pow_eq_prod,
← finset.prod_multiset_count, ← associated_iff_eq],
{ exact factors_prod hI },
{ exact prime_of_mem }, { exact λ _ _ _ _ ij, ij } },
{ intros p hp q hq pq, dsimp,
rw irreducible_pow_sup,
{ suffices : (normalized_factors _).count p = 0,
{ rw [this, zero_min, pow_zero, ideal.one_eq_top] },
{ rw [multiset.count_eq_zero, normalized_factors_of_irreducible_pow
(prime_of_mem q hq).irreducible, multiset.mem_repeat],
exact λ H, pq $ H.2.trans $ normalize_eq q } },
{ rw ← ideal.zero_eq_bot, apply pow_ne_zero, exact (prime_of_mem q hq).ne_zero },
{ exact (prime_of_mem p hp).irreducible } }
end
/--A finitely generated torsion module over a Dedekind domain is an internal direct sum of its
`p i ^ e i`-torsion submodules for some prime ideals `p i` and numbers `e i`.-/
theorem is_internal_prime_power_torsion [module.finite R M] (hM : module.is_torsion R M) :
∃ (P : finset $ ideal R) [decidable_eq P] [∀ p ∈ P, prime p] (e : P → ℕ),
by exactI direct_sum.is_internal (λ p : P, torsion_by_set R M (p ^ e p : ideal R)) :=
begin
obtain ⟨I, hI, hM'⟩ := is_torsion_by_ideal_of_finite_of_is_torsion hM,
refine is_internal_prime_power_torsion_of_is_torsion_by_ideal _ hM',
rw set.ne_empty_iff_nonempty at hI, rw submodule.ne_bot_iff,
obtain ⟨x, H, hx⟩ := hI, exact ⟨x, H, non_zero_divisors.ne_zero hx⟩
end
end submodule
|
0304bbdc70d7abad33145b3181af8b0f677c1dc3 | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /src/data/zmod/basic.lean | d03116ada506116dd990d2dce767123a606bf9c4 | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 18,607 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
# zmod and zmodp
Definition of the integers mod n, and the field structure on the integers mod p.
There are two types defined, `zmod n`, which is for integers modulo a positive nat `n : ℕ+`.
`zmodp` is the type of integers modulo a prime number, for which a field structure is defined.
## Definitions
`val` is inherited from `fin` and returns the least natural number in the equivalence class
`val_min_abs` returns the integer closest to zero in the equivalence class.
A coercion `cast` is defined from `zmod n` into any semiring. This is a semiring hom if the ring has
characteristic dividing `n`
## Implentation notes
`zmod` and `zmodp` are implemented as different types so that the field instance for `zmodp` can be
synthesized. This leads to a lot of code duplication and most of the functions and theorems for
`zmod` are restated for `zmodp`
-/
import data.int.modeq data.int.gcd data.fintype data.pnat.basic tactic.ring
open nat nat.modeq int
def zmod (n : ℕ+) := fin n
namespace zmod
instance (n : ℕ+) : has_neg (zmod n) :=
⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n,
have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 n.pos,
have h₁ : ((n : ℕ) : ℤ) = abs n := (abs_of_nonneg (int.coe_nat_nonneg n)).symm,
by rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h), h₁];
exact int.mod_lt _ h⟩⟩
instance (n : ℕ+) : add_comm_semigroup (zmod n) :=
{ add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n],
from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl
... ≡ a + (b + c) [MOD n] : by rw add_assoc
... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm),
add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm),
..fin.has_add }
instance (n : ℕ+) : comm_semigroup (zmod n) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl
... ≡ a * (b * c) [MOD n] : by rw mul_assoc
... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm),
..fin.has_mul }
instance (n : ℕ+) : has_one (zmod n) := ⟨⟨(1 % n), nat.mod_lt _ n.pos⟩⟩
instance (n : ℕ+) : has_zero (zmod n) := ⟨⟨0, n.pos⟩⟩
instance zmod_one.subsingleton : subsingleton (zmod 1) :=
⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2),
eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩
lemma add_val {n : ℕ+} : ∀ a b : zmod n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val {n : ℕ+} : ∀ a b : zmod n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma one_val {n : ℕ+} : (1 : zmod n).val = 1 % n := rfl
@[simp] lemma zero_val (n : ℕ+) : (0 : zmod n).val = 0 := rfl
private lemma one_mul_aux (n : ℕ+) (a : zmod n) : (1 : zmod n) * a = a :=
begin
cases n with n hn,
cases n with n,
{ exact (lt_irrefl _ hn).elim },
{ cases n with n,
{ exact @subsingleton.elim (zmod 1) _ _ _ },
{ have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2,
have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial,
refine fin.eq_of_veq _,
simp [mul_val, one_val, h₁, h₂] } }
end
private lemma left_distrib_aux (n : ℕ+) : ∀ a b c : zmod n, a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _)
... ≡ a * b + a * c [MOD n] : by rw mul_add
... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm)
instance (n : ℕ+) : comm_ring (zmod n) :=
{ zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha),
add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha),
add_left_neg :=
λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0,
from int.coe_nat_inj
begin
have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 n.pos)).symm,
rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm],
simp,
end),
one_mul := one_mul_aux n,
mul_one := λ a, by rw mul_comm; exact one_mul_aux n a,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..zmod.has_zero n,
..zmod.has_one n,
..zmod.has_neg n,
..zmod.add_comm_semigroup n,
..zmod.comm_semigroup n }
lemma val_cast_nat {n : ℕ+} (a : ℕ) : (a : zmod n).val = a % n :=
begin
induction a with a ih,
{ rw [nat.zero_mod]; refl },
{ rw [succ_eq_add_one, nat.cast_add, add_val, ih],
show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n,
rw [zero_add, nat.mod_mod],
exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) }
end
lemma neg_val' {m : pnat} (n : zmod m) : (-n).val = (m - n.val) % m :=
have ((-n).val + n.val) % m = (m - n.val + n.val) % m,
by { rw [←add_val, add_left_neg, nat.sub_add_cancel (le_of_lt n.is_lt), nat.mod_self], refl },
(nat.mod_eq_of_lt (fin.is_lt _)).symm.trans (nat.modeq.modeq_add_cancel_right rfl this)
lemma neg_val {m : pnat} (n : zmod m) : (-n).val = if n = 0 then 0 else m - n.val :=
begin
rw neg_val',
by_cases h : n = 0; simp [h],
cases n with n nlt; cases n; dsimp, { contradiction },
rw nat.mod_eq_of_lt,
apply nat.sub_lt m.2 (nat.succ_pos _),
end
lemma mk_eq_cast {n : ℕ+} {a : ℕ} (h : a < n) : (⟨a, h⟩ : zmod n) = (a : zmod n) :=
fin.eq_of_veq (by rw [val_cast_nat, nat.mod_eq_of_lt h])
@[simp] lemma cast_self_eq_zero {n : ℕ+} : ((n : ℕ) : zmod n) = 0 :=
fin.eq_of_veq (show (n : zmod n).val = 0, by simp [val_cast_nat])
lemma val_cast_of_lt {n : ℕ+} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_cast_nat, nat.mod_eq_of_lt h]
@[simp] lemma cast_mod_nat (n : ℕ+) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
@[simp] lemma cast_mod_nat' {n : ℕ} (hn : 0 < n) (a : ℕ) : ((a % n : ℕ) : zmod ⟨n, hn⟩) = a :=
cast_mod_nat _ _
@[simp] lemma cast_val {n : ℕ+} (a : zmod n) : (a.val : zmod n) = a :=
by cases a; simp [mk_eq_cast]
@[simp] lemma cast_mod_int (n : ℕ+) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod n) = a :=
by conv {to_rhs, rw ← int.mod_add_div a n}; simp
@[simp] lemma cast_mod_int' {n : ℕ} (hn : 0 < n) (a : ℤ) :
((a % (n : ℕ) : ℤ) : zmod ⟨n, hn⟩) = a := cast_mod_int _ _
lemma val_cast_int {n : ℕ+} (a : ℤ) : (a : zmod n).val = (a % (n : ℕ)).nat_abs :=
have h : nat_abs (a % (n : ℕ)) < n := int.coe_nat_lt.1 begin
rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))],
conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)},
exact int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)
end,
int.coe_nat_inj $
by conv {to_lhs, rw [← cast_mod_int n a,
← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
int.cast_coe_nat, val_cast_of_lt h] }
lemma coe_val_cast_int {n : ℕ+} (a : ℤ) : ((a : zmod n).val : ℤ) = a % (n : ℕ) :=
by rw [val_cast_int, int.nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))]
lemma eq_iff_modeq_nat {n : ℕ+} {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_nat, val_cast_nat] at this,
λ h, fin.eq_of_veq $ by rwa [val_cast_nat, val_cast_nat]⟩
lemma eq_iff_modeq_nat' {n : ℕ} (hn : 0 < n) {a b : ℕ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [MOD n] :=
eq_iff_modeq_nat
lemma eq_iff_modeq_int {n : ℕ+} {a b : ℤ} : (a : zmod n) = b ↔ a ≡ b [ZMOD (n : ℕ)] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_int, val_cast_int, ← int.coe_nat_eq_coe_nat_iff,
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] at this,
λ h : a % (n : ℕ) = b % (n : ℕ),
by rw [← cast_mod_int n a, ← cast_mod_int n b, h]⟩
lemma eq_iff_modeq_int' {n : ℕ} (hn : 0 < n) {a b : ℤ} :
(a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [ZMOD (n : ℕ)] := eq_iff_modeq_int
lemma eq_zero_iff_dvd_nat {n : ℕ+} {a : ℕ} : (a : zmod n) = 0 ↔ (n : ℕ) ∣ a :=
by rw [← @nat.cast_zero (zmod n), eq_iff_modeq_nat, nat.modeq.modeq_zero_iff]
lemma eq_zero_iff_dvd_int {n : ℕ+} {a : ℤ} : (a : zmod n) = 0 ↔ ((n : ℕ) : ℤ) ∣ a :=
by rw [← @int.cast_zero (zmod n), eq_iff_modeq_int, int.modeq.modeq_zero_iff]
instance (n : ℕ+) : fintype (zmod n) := fin.fintype _
instance decidable_eq (n : ℕ+) : decidable_eq (zmod n) := fin.decidable_eq _
instance (n : ℕ+) : has_repr (zmod n) := fin.has_repr _
lemma card_zmod (n : ℕ+) : fintype.card (zmod n) = n := fintype.card_fin n
lemma le_div_two_iff_lt_neg {n : ℕ+} (hn : (n : ℕ) % 2 = 1)
{x : zmod n} (hx0 : x ≠ 0) : x.1 ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).1 :=
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left n.pos).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
by conv {to_lhs, congr, rw [← succ_sub_one n, succ_sub n.pos]};
rw [← two_mul_odd_div_two hn, two_mul, ← succ_add, nat.add_sub_cancel],
have hxn : (n : ℕ) - x.val < n,
begin
rw [nat.sub_lt_iff (le_of_lt x.2) (le_refl _), nat.sub_self],
rw ← zmod.cast_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0)
end,
by conv {to_rhs, rw [← nat.succ_le_iff, succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self_eq_zero,
← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.2),
zmod.val_cast_nat, mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.2)] }
lemma ne_neg_self {n : ℕ+} (hn1 : (n : ℕ) % 2 = 1) {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg hn1 ha,
by rwa [← h, ← not_lt, not_iff_self] at this
@[simp] lemma cast_mul_right_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (m * n)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_right _ (nat.mod_mod _ _))
@[simp] lemma cast_mul_left_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (n * m)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_left _ (nat.mod_mod _ _))
lemma cast_val_cast_of_dvd {n m : ℕ+} (h : (m : ℕ) ∣ n) (a : ℕ) :
((a : zmod n).val : zmod m) = (a : zmod m) :=
let ⟨k , hk⟩ := h in
zmod.eq_iff_modeq_nat.2 (nat.modeq.modeq_of_modeq_mul_right k
(by rw [← hk, zmod.val_cast_nat]; exact nat.mod_mod _ _))
def units_equiv_coprime {n : ℕ+} : units (zmod n) ≃ {x : zmod n // nat.coprime x.1 n} :=
{ to_fun := λ x, ⟨x, nat.modeq.coprime_of_mul_modeq_one (x⁻¹).1.1 begin
have := units.ext_iff.1 (mul_right_inv x),
rwa [← zmod.cast_val ((1 : units (zmod n)) : zmod n), units.coe_one, zmod.one_val,
← zmod.cast_val ((x * x⁻¹ : units (zmod n)) : zmod n),
units.coe_mul, zmod.mul_val, zmod.cast_mod_nat, zmod.cast_mod_nat,
zmod.eq_iff_modeq_nat] at this
end⟩,
inv_fun := λ x,
have x.val * ↑(gcd_a ((x.val).val) ↑n) = 1,
by rw [← zmod.cast_val x.1, ← int.cast_coe_nat, ← int.cast_one, ← int.cast_mul,
zmod.eq_iff_modeq_int, ← int.coe_nat_one, ← (show nat.gcd _ _ = _, from x.2)];
simpa using int.modeq.gcd_a_modeq x.1.1 n,
⟨x.1, gcd_a x.1.1 n, this, by simpa [mul_comm] using this⟩,
left_inv := λ ⟨_, _, _, _⟩, units.ext rfl,
right_inv := λ ⟨_, _⟩, rfl }
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs {n : ℕ+} (x : zmod n) : ℤ :=
if x.val ≤ n / 2 then x.val else x.val - n
@[simp] lemma coe_val_min_abs {n : ℕ+} (x : zmod n) :
(x.val_min_abs : zmod n) = x :=
by simp [zmod.val_min_abs]; split_ifs; simp
lemma nat_abs_val_min_abs_le {n : ℕ+} (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
have (x.val - n : ℤ) ≤ 0, from sub_nonpos.2 $ int.coe_nat_le.2 $ le_of_lt x.2,
begin
rw zmod.val_min_abs,
split_ifs with h,
{ exact h },
{ rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [coe_coe, ← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
rw ← sub_nonneg,
suffices : (0 : ℤ) ≤ x.val - ((n % 2 : ℕ) + (n / 2 : ℕ)),
{ exact le_trans this (le_of_eq $ by ring) },
exact sub_nonneg.2 (by rw [← int.coe_nat_add, int.coe_nat_le];
exact calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
add_le_add (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) (le_refl _)
... ≤ x.val : by rw add_comm; exact nat.succ_le_of_lt (lt_of_not_ge h)) }
end
@[simp] lemma val_min_abs_zero {n : ℕ+} : (0 : zmod n).val_min_abs = 0 :=
by simp [zmod.val_min_abs]
@[simp] lemma val_min_abs_eq_zero {n : ℕ+} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
⟨λ h, begin
dsimp [zmod.val_min_abs] at h,
split_ifs at h,
{ exact fin.eq_of_veq (by simp * at *) },
{ exact absurd h (mt sub_eq_zero.1 (ne_of_lt $ int.coe_nat_lt.2 x.2)) }
end, λ hx0, hx0.symm ▸ zmod.val_min_abs_zero⟩
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] {n : ℕ+}
def cast : zmod n → α := nat.cast ∘ fin.val
end
end zmod
def zmodp (p : ℕ) (hp : prime p) : Type := zmod ⟨p, hp.pos⟩
namespace zmodp
variables {p : ℕ} (hp : prime p)
instance : comm_ring (zmodp p hp) := zmod.comm_ring ⟨p, hp.pos⟩
instance {p : ℕ} (hp : prime p) : has_inv (zmodp p hp) :=
⟨λ a, gcd_a a.1 p⟩
lemma add_val : ∀ a b : zmodp p hp, (a + b).val = (a.val + b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val : ∀ a b : zmodp p hp, (a * b).val = (a.val * b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma one_val : (1 : zmodp p hp).val = 1 :=
nat.mod_eq_of_lt hp.one_lt
@[simp] lemma zero_val : (0 : zmodp p hp).val = 0 := rfl
lemma val_cast_nat (a : ℕ) : (a : zmodp p hp).val = a % p :=
@zmod.val_cast_nat ⟨p, hp.pos⟩ _
lemma mk_eq_cast {a : ℕ} (h : a < p) : (⟨a, h⟩ : zmodp p hp) = (a : zmodp p hp) :=
@zmod.mk_eq_cast ⟨p, hp.pos⟩ _ _
@[simp] lemma cast_self_eq_zero: (p : zmodp p hp) = 0 :=
fin.eq_of_veq $ by simp [val_cast_nat]
lemma val_cast_of_lt {a : ℕ} (h : a < p) : (a : zmodp p hp).val = a :=
@zmod.val_cast_of_lt ⟨p, hp.pos⟩ _ h
@[simp] lemma cast_mod_nat (a : ℕ) : ((a % p : ℕ) : zmodp p hp) = a :=
@zmod.cast_mod_nat ⟨p, hp.pos⟩ _
@[simp] lemma cast_val (a : zmodp p hp) : (a.val : zmodp p hp) = a :=
@zmod.cast_val ⟨p, hp.pos⟩ _
@[simp] lemma cast_mod_int (a : ℤ) : ((a % p : ℤ) : zmodp p hp) = a :=
@zmod.cast_mod_int ⟨p, hp.pos⟩ _
lemma val_cast_int (a : ℤ) : (a : zmodp p hp).val = (a % p).nat_abs :=
@zmod.val_cast_int ⟨p, hp.pos⟩ _
lemma coe_val_cast_int (a : ℤ) : ((a : zmodp p hp).val : ℤ) = a % (p : ℕ) :=
@zmod.coe_val_cast_int ⟨p, hp.pos⟩ _
lemma eq_iff_modeq_nat {a b : ℕ} : (a : zmodp p hp) = b ↔ a ≡ b [MOD p] :=
@zmod.eq_iff_modeq_nat ⟨p, hp.pos⟩ _ _
lemma eq_iff_modeq_int {a b : ℤ} : (a : zmodp p hp) = b ↔ a ≡ b [ZMOD p] :=
@zmod.eq_iff_modeq_int ⟨p, hp.pos⟩ _ _
lemma eq_zero_iff_dvd_nat (a : ℕ) : (a : zmodp p hp) = 0 ↔ p ∣ a :=
@zmod.eq_zero_iff_dvd_nat ⟨p, hp.pos⟩ _
lemma eq_zero_iff_dvd_int (a : ℤ) : (a : zmodp p hp) = 0 ↔ (p : ℤ) ∣ a :=
@zmod.eq_zero_iff_dvd_int ⟨p, hp.pos⟩ _
instance : fintype (zmodp p hp) := @zmod.fintype ⟨p, hp.pos⟩
instance decidable_eq : decidable_eq (zmodp p hp) := fin.decidable_eq _
instance : has_repr (zmodp p hp) := fin.has_repr _
@[simp] lemma card_zmodp : fintype.card (zmodp p hp) = p :=
@zmod.card_zmod ⟨p, hp.pos⟩
lemma le_div_two_iff_lt_neg {p : ℕ} (hp : prime p) (hp1 : p % 2 = 1)
{x : zmodp p hp} (hx0 : x ≠ 0) : x.1 ≤ (p / 2 : ℕ) ↔ (p / 2 : ℕ) < (-x).1 :=
@zmod.le_div_two_iff_lt_neg ⟨p, hp.pos⟩ hp1 _ hx0
lemma ne_neg_self (hp1 : p % 2 = 1) {a : zmodp p hp} (ha : a ≠ 0) : a ≠ -a :=
@zmod.ne_neg_self ⟨p, hp.pos⟩ hp1 _ ha
variable {hp}
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs (x : zmodp p hp) : ℤ := zmod.val_min_abs x
@[simp] lemma coe_val_min_abs (x : zmodp p hp) :
(x.val_min_abs : zmodp p hp) = x :=
zmod.coe_val_min_abs x
lemma nat_abs_val_min_abs_le (x : zmodp p hp) : x.val_min_abs.nat_abs ≤ p / 2 :=
zmod.nat_abs_val_min_abs_le x
@[simp] lemma val_min_abs_zero : (0 : zmodp p hp).val_min_abs = 0 :=
zmod.val_min_abs_zero
@[simp] lemma val_min_abs_eq_zero (x : zmodp p hp) : x.val_min_abs = 0 ↔ x = 0 :=
zmod.val_min_abs_eq_zero x
variable (hp)
lemma prime_ne_zero {q : ℕ} (hq : prime q) (hpq : p ≠ q) : (q : zmodp p hp) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
← hp.coprime_iff_not_dvd, coprime_primes hp hq]
lemma mul_inv_eq_gcd (a : ℕ) : (a : zmodp p hp) * a⁻¹ = nat.gcd a p :=
by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← (eq_iff_modeq_int _).2 (int.modeq.gcd_a_modeq _ _)];
simp [has_inv.inv, val_cast_nat]
private lemma mul_inv_cancel_aux : ∀ a : zmodp p hp, a ≠ 0 → a * a⁻¹ = 1 :=
λ ⟨a, hap⟩ ha0, begin
rw [mk_eq_cast, ne.def, ← @nat.cast_zero (zmodp p hp), eq_iff_modeq_nat, modeq_zero_iff] at ha0,
have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0,
rw [mk_eq_cast _ hap, mul_inv_eq_gcd, nat.gcd_comm],
simpa [nat.gcd_comm, this]
end
instance : discrete_field (zmodp p hp) :=
{ zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p,
by rw nat.mod_eq_of_lt hp.one_lt;
exact zero_ne_one,
mul_inv_cancel := mul_inv_cancel_aux hp,
inv_mul_cancel := λ a, by rw mul_comm; exact mul_inv_cancel_aux hp _,
has_decidable_eq := by apply_instance,
inv_zero := show (gcd_a 0 p : zmodp p hp) = 0,
by unfold gcd_a xgcd xgcd_aux; refl,
..zmodp.comm_ring hp,
..zmodp.has_inv hp }
end zmodp
|
63e6fa6f1fae9ef16950b5f522396c756cc0b219 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /library/data/empty.lean | 96bd1495dfc7fb2dd8b89c32bc58e9efe6d2603d | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,385 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.empty
Author: Jeremy Avigad, Floris van Doorn
-/
import logic.cast logic.subsingleton
namespace empty
protected theorem elim (A : Type) (H : empty) : A :=
empty.rec (λe, A) H
protected theorem subsingleton [instance] : subsingleton empty :=
subsingleton.intro (λ a b, !elim a)
end empty
protected definition empty.has_decidable_eq [instance] : decidable_eq empty :=
take (a b : empty), decidable.inl (!empty.elim a)
definition tneg.tneg (A : Type) := A → empty
prefix `~` := tneg.tneg
namespace tneg
variables {A B : Type}
protected definition intro (H : A → empty) : ~A := H
protected definition elim (H1 : ~A) (H2 : A) : empty := H1 H2
protected definition empty : ~empty := λH : empty, H
definition tabsurd (H1 : A) (H2 : ~A) : B := !empty.elim (H2 H1)
definition tneg_tneg_intro (H : A) : ~~A := λH2 : ~A, tneg.elim H2 H
definition tmt (H1 : A → B) (H2 : ~B) : ~A := λHA : A, tabsurd (H1 HA) H2
definition tneg_pi_left {B : A → Type} (H : ~Πa, B a) : ~~A :=
λHnA : ~A, tneg.elim H (λHA : A, tabsurd HA HnA)
definition tneg_function_right (H : ~(A → B)) : ~B :=
λHB : B, tneg.elim H (λHA : A, HB)
end tneg
|
e0228ea3038faabdcfb6a51643944aec6ee2e5be | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/ind_cmd_bug.lean | fd3d94da3236318806831d364196a3af14649eab | [
"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 | 83 | lean | structure D (α : Type) :=
(a : α)
inductive S
| mk₁ (v : S)
| mk₂ (v : D S)
|
3e37561e05b673a439eb96fa6ba2987b119e063d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/ordering/default_auto.lean | 82cb57ffa835f92e43f9aba6aaedd916ab15e748 | [] | 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 | 317 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.ordering.basic
import Mathlib.Lean3Lib.init.data.ordering.lemmas
namespace Mathlib
end Mathlib |
6765d489c3d597d0e348865f3f5a8f419dfe5cc6 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/tactic/norm_num.lean | 42d5e146f6960f30b9d610948d77da9a1a9b1d2f | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 63,668 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
-/
import data.rat.cast
import data.rat.meta_defs
/-!
# `norm_num`
Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`.
-/
universes u v w
namespace tactic
/-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/
meta def refl_conv (e : expr) : tactic (expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a
proof by reflexivity. -/
meta def or_refl_conv (tac : expr → tactic (expr × expr))
(e : expr) : tactic (expr × expr) := tac e <|> refl_conv e
/-- Transitivity conversion: given two conversions (which take an
expression `e` and returns `(e', ⊢ e = e')`), produces another
conversion that combines them with transitivity, treating failures
as reflexivity conversions. -/
meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) :
tactic (expr × expr) :=
(do (e₁, p₁) ← t₁ e,
(do (e₂, p₂) ← t₂ e₁,
p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|>
return (e₁, p₁)) <|> t₂ e
namespace instance_cache
/-- Faster version of `mk_app ``bit0 [e]`. -/
meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])
/-- Faster version of `mk_app ``bit1 [e]`. -/
meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
end instance_cache
end tactic
open tactic
/-!
Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed)
the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure
should describe the shape of the generated lemma in its docstring.
-/
namespace norm_num
variable {α : Type u}
lemma subst_into_add {α} [has_add α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t :=
by rw [prl, prr, prt]
lemma subst_into_mul {α} [has_mul α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t :=
by rw [prl, prr, prt]
lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t :=
by simp [pra, prt]
/-- The result type of `match_numeral`, either `0`, `1`, or a top level
decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/
meta inductive match_numeral_result
| zero | one | bit0 (e : expr) | bit1 (e : expr) | other
/-- Unfold the top level constructor of the numeral expression. -/
meta def match_numeral : expr → match_numeral_result
| `(bit0 %%e) := match_numeral_result.bit0 e
| `(bit1 %%e) := match_numeral_result.bit1 e
| `(@has_zero.zero _ _) := match_numeral_result.zero
| `(@has_one.one _ _) := match_numeral_result.one
| _ := match_numeral_result.other
theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _
theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl
theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl
theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable.
(It may prove garbage instead of failing if `a + 1 = b` is false.) -/
meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr)
| c e r := match match_numeral e with
| zero := c.mk_app ``zero_succ []
| one := c.mk_app ``one_succ []
| bit0 e := c.mk_app ``bit0_succ [e]
| bit1 e := do
let r := r.app_arg,
(c, p) ← prove_succ c e r,
c.mk_app ``bit1_succ [e, r, p]
| _ := failed
end
end
/-- Given `a` natural numeral, returns `(b, ⊢ a + 1 = b)`. -/
meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) :=
do na ← a.to_nat,
(c, b) ← c.of_nat (na + 1),
(c, p) ← prove_succ c a b,
return (c, b, p)
theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add
theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero
theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm
theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_assoc]
theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl
theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit1 a + bit0 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit0 a + bit1 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit1 a + bit1 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
meta mutual def prove_add_nat, prove_adc_nat
with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := c.mk_app ``zero_add [b]
| _, zero := c.mk_app ``add_zero [a]
| _, one := prove_succ c a r
| one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p]
| _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p]
| one, one := c.mk_app ``adc_one_one []
| bit0 a, one :=
do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p]
| one, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p]
| bit1 a, one :=
do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p]
| one, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/
add_decl_doc prove_add_nat
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/
add_decl_doc prove_adc_nat
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/
meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) :=
do na ← a.to_nat,
nb ← b.to_nat,
(c, r) ← c.of_nat (na + nb),
(c, p) ← prove_add_nat c a b r,
return (c, r, p)
end
theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul]
theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) :
a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add]
theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h)
theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α)
(hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) :
bit1 a * bit1 b = bit1 e :=
by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/
meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr)
| ic a b :=
match match_numeral a, match_numeral b with
| zero, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, zero := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p)
| _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p)
| bit0 a, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
(ic, c') ← ic.mk_bit0 c',
return (ic, c', p)
| bit0 a, _ := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| _, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| bit1 a, bit1 b := do
(ic, c, pc) ← prove_mul_nat ic a b,
(ic, d, pd) ← prove_add_nat' ic a b,
(ic, c') ← ic.mk_bit0 c,
(ic, e, pe) ← prove_add_nat' ic c' d,
(ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe],
(ic, e') ← ic.mk_bit1 e,
return (ic, e', p)
| _, _ := failed
end
end
section
open match_numeral_result
/-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/
meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr)
| e :=
match match_numeral e with
| one := c.mk_app ``zero_lt_one' []
| bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p]
| bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p]
| _ := failed
end
end
/-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/
meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr)
| `(%%e₁ / %%e₂) := do
(c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂,
c.mk_app ``div_pos [e₁, e₂, p₁, p₂]
| e := prove_pos_nat c e
/-- `match_neg (- e) = some e`, otherwise `none` -/
meta def match_neg : expr → option expr
| `(- %%e) := some e
| _ := none
/-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/
meta def match_sign : expr → expr ⊕ bool
| `(- %%e) := sum.inl e
| `(has_zero.zero) := sum.inr ff
| _ := sum.inr tt
theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt
theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1
/-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/
meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_neg a with
| some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p]
| none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p]
end
theorem clear_denom_div {α} [division_ring α] (a b b' c d : α)
(h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c :=
by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀]
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom'
(prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr))
(c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) :
tactic (instance_cache × expr × expr) :=
if na.denom = 1 then
prove_mul_nat c a d
else do
[_, _, a, b] ← return a.get_app_args,
(c, b') ← c.of_nat (nd / na.denom),
(c, p₀) ← prove_ne_zero c b (rat.of_int na.denom),
(c, _, p₁) ← prove_mul_nat c b b',
(c, r, p₂) ← prove_mul_nat c a b',
(c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂],
return (c, r, p)
theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt
theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a :=
lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h)
theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a :=
one_lt_bit1.2 h
theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b :=
bit0_lt_bit0.2
theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b :=
lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _)
theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b :=
lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h)
theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b :=
bit1_lt_bit1.2
theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a :=
le_of_lt (lt_one_bit0 _ h)
-- deliberately strong hypothesis because bit1 0 is not a numeral
theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a :=
le_of_lt (lt_one_bit1 _ h)
theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b :=
bit0_le_bit0.2
theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b :=
le_of_lt (lt_bit0_bit1 _ _ h)
theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b :=
le_of_lt (lt_bit1_bit0 _ _ h)
theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b :=
bit1_le_bit1.2
theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a :=
bit0_le_bit0.2
theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a :=
le_bit0_bit1 _ _
theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b :=
le_bit1_bit0 _ _
theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b :=
bit1_le_bit1.2 h
theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) :
bit1 a + 1 ≤ bit0 b :=
(bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h
theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) :
bit1 a + 1 ≤ bit1 b :=
(bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h
/-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/
meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr)
| e@`(has_zero.zero) := ic.mk_app ``le_refl [e]
| e :=
if ic.α = `(ℕ) then
return (ic, `(nat.zero_le).mk_app [e])
else do
(ic, p) ← prove_pos ic e,
ic.mk_app ``nonneg_pos [e, p]
section
open match_numeral_result
/-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/
meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_numeral a with
| one := ic.mk_app ``le_refl [a]
| bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p]
| bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p]
| _ := failed
end
meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache)
with prove_le_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
if a = b then ic.mk_app ``le_refl [a] else
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p]
| _, _ := failed
end
with prove_sle_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p]
| _, _ := failed
end
/-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/
add_decl_doc prove_le_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/
add_decl_doc prove_sle_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/
meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_pos ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p]
| _, _ := failed
end
end
theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b :=
lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀)
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_lt_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) ← prove_lt_nat ic a' b',
ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p]
lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b :=
lt_trans (neg_neg_of_pos ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
-- we have to switch the order of `a` and `b` because `a < b ↔ -b < -a`
(ic, p) ← prove_lt_nonneg_rat ic b a (-nb) (-na),
ic.mk_app ``neg_lt_neg [b, a, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_pos ic a,
ic.mk_app ``neg_neg_of_pos [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_pos ic a,
(ic, pb) ← prove_pos ic b,
ic.mk_app ``lt_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_pos ic b
| sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb
end
theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b :=
le_of_mul_le_mul_right (by rwa [ha, hb]) h₀
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_le_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) ← prove_le_nat ic a' b',
ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p]
lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b :=
le_trans (neg_nonpos_of_nonneg ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb),
ic.mk_app ``neg_le_neg [a, b, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_nonneg ic a,
ic.mk_app ``neg_nonpos_of_nonneg [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_nonneg ic a,
(ic, pb) ← prove_nonneg ic b,
ic.mk_app ``le_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_nonneg ic b
| sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb
end
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove
`⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/
meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na < nb then do
(ic, p) ← prove_lt_rat ic a b na nb,
ic.mk_app ``ne_of_lt [a, b, p]
else do
(ic, p) ← prove_lt_rat ic b a nb na,
ic.mk_app ``ne_of_gt [a, b, p]
theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero
theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one
theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ nat.cast_bit0 _
theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ nat.cast_bit1 _
theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero
theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one
theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ int.cast_bit0 _
theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ int.cast_bit1 _
theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') :
↑(bit0 a) = bit0 a' :=
h ▸ rat.cast_bit0 _
theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') :
↑(bit1 a) = bit1 a' :=
h ▸ rat.cast_bit1 _
/-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(nc, e) ← nc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``nat_cast_zero [],
return (ic, nc, e, p)
| match_numeral_result.one := do
(nc, e) ← nc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``nat_cast_one [],
return (ic, nc, e, p)
| match_numeral_result.bit0 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a0) ← nc.mk_bit0 a,
(ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p],
return (ic, nc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a1) ← nc.mk_bit1 a,
(ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p],
return (ic, nc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(zc, e) ← zc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``int_cast_zero [],
return (ic, zc, e, p)
| match_numeral_result.one := do
(zc, e) ← zc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``int_cast_one [],
return (ic, zc, e, p)
| match_numeral_result.bit0 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a0) ← zc.mk_bit0 a,
(ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p],
return (ic, zc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a1) ← zc.mk_bit1 a,
(ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p],
return (ic, zc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(qc, e) ← qc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``rat.cast_zero [],
return (ic, qc, e, p)
| match_numeral_result.one := do
(qc, e) ← qc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``rat.cast_one [],
return (ic, qc, e, p)
| match_numeral_result.bit0 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a0) ← qc.mk_bit0 a,
(ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p],
return (ic, qc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a1) ← qc.mk_bit1 a,
(ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p],
return (ic, qc, a1, p)
| _ := failed
end
theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' :=
ha ▸ hb ▸ rat.cast_div _ _
/-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
if na'.denom = 1 then
prove_rat_uncast_nat ic qc cz_inst a'
else do
[_, _, a', b'] ← return a'.get_app_args,
(ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a',
(ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b',
(qc, e) ← qc.mk_app ``has_div.div [a, b],
(ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb],
return (ic, qc, e, p)
theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ int.cast_neg _
theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ rat.cast_neg _
/-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, zc, a, p) ← prove_int_uncast_nat ic zc a',
(zc, e) ← zc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``int_cast_neg [a, a', p],
return (ic, zc, e, p)
| none := prove_int_uncast_nat ic zc a'
end
/-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'),
(qc, e) ← qc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p],
return (ic, qc, e, p)
| none := prove_rat_uncast_nonneg ic qc cz_inst a' na'
end
theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt nat.cast_inj.1 h
theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt int.cast_inj.1 h
theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt rat.cast_inj.1 h
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods:
* Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order
* Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`.
This requires that the base type be `char_zero`, and also that it be a `division_ring`
so that the coercion from `ℚ` is well defined.
We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero`
rings and semirings. -/
meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr)
| ic a b na nb := prove_ne_rat ic a b na nb <|> do
cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance,
if na.denom = 1 ∧ nb.denom = 1 then
if na ≥ 0 ∧ nb ≥ 0 then do
guard (ic.α ≠ `(ℕ)),
nc ← mk_instance_cache `(ℕ),
(ic, nc, a', pa) ← prove_nat_uncast ic nc a,
(ic, nc, b', pb) ← prove_nat_uncast ic nc b,
(nc, p) ← prove_ne_rat nc a' b' na nb,
ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℤ)),
zc ← mk_instance_cache `(ℤ),
(ic, zc, a', pa) ← prove_int_uncast ic zc a,
(ic, zc, b', pb) ← prove_int_uncast ic zc b,
(zc, p) ← prove_ne_rat zc a' b' na nb,
ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℚ)),
qc ← mk_instance_cache `(ℚ),
(ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na,
(ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb,
(qc, p) ← prove_ne_rat qc a' b' na nb,
ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
/-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/
meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr)
| a na := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
prove_ne ic a z na 0
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ →
tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero
theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α)
(h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c')
(h : a' + b' = c') : a + b = c :=
mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc]
/-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_add_nat ic a b c
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_ne_zero ic d (rat.of_int nd),
(ic, a', pa) ← prove_clear_denom ic a d na nd,
(ic, b', pb) ← prove_clear_denom ic b d nb nd,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, p) ← prove_add_nat ic a' b' c',
ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p]
theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c :=
h ▸ by simp
theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c :=
h ▸ by simp
theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c :=
h ▸ by simp
theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c :=
h ▸ by simp
theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c :=
h ▸ by simp
/-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) :
tactic (instance_cache × expr) :=
match match_neg ea, match_neg eb, match_neg ec with
| some ea, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c),
ic.mk_app ``add_neg_neg [ea, eb, ec, p]
| some ea, none, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a),
ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p]
| some ea, none, none := do
(ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b,
ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p]
| none, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b),
ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p]
| none, some eb, none := do
(ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a,
ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p]
| _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c
end
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/
meta def prove_add_rat' (ic : instance_cache) (a b : expr) :
tactic (instance_cache × expr × expr) :=
do na ← a.to_rat,
nb ← b.to_rat,
let nc := na + nb,
(ic, c) ← ic.of_rat nc,
(ic, p) ← prove_add_rat ic a b c na nb nc,
return (ic, c, p)
theorem clear_denom_simple_nat {α} [division_ring α] (a : α) :
(1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩
theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) :
b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩
/-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)`
where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/
meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) :
tactic (instance_cache × expr × expr × expr) :=
if na.denom = 1 then do
(c, d) ← c.mk_app ``has_one.one [],
(c, p) ← c.mk_app ``clear_denom_simple_nat [a],
return (c, d, a, p)
else do
[α, _, a, b] ← return a.get_app_args,
(c, p₀) ← prove_ne_zero c b (rat.of_int na.denom),
(c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀],
return (c, b, a, p)
theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α)
(ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b')
(hc : c * d = c') (hd : d₁ * d₂ = d)
(h : a' * b' = c') : a * b = c :=
mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $
by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a]
/-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_mul_nat ic a b
else do
let nc := na * nb, (ic, c) ← ic.of_rat nc,
(ic, d₁, a', pa) ← prove_clear_denom_simple ic a na,
(ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb,
(ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, _, p) ← prove_mul_nat ic a' b',
(ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p],
return (ic, c, p)
theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp
theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp
theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb),
(ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, sum.inr ff := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| sum.inl a, sum.inr tt := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb,
(ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb),
(ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb
end
theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b :=
h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div]
theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one
theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a :=
by rw [one_div, inv_inv']
theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a :=
inv_eq_one_div _
theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a :=
by simp only [inv_eq_one_div, one_div_div]
/-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/
meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr)
| ic e n :=
match match_sign e with
| sum.inl e := do
(ic, e', p) ← prove_inv ic e (-n),
(ic, r) ← ic.mk_app ``has_neg.neg [e'],
(ic, p) ← ic.mk_app ``inv_neg [e, e', p],
return (ic, r, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``inv_zero [],
return (ic, e, p)
| sum.inr tt :=
if n.num = 1 then
if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_one [],
return (ic, e, p)
else do
let e := e.app_arg,
(ic, p) ← ic.mk_app ``inv_one_div [e],
return (ic, e, p)
else if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_div_one [e],
e ← infer_type p,
return (ic, e.app_arg, p)
else do
[_, _, a, b] ← return e.get_app_args,
(ic, e') ← ic.mk_app ``has_div.div [b, a],
(ic, p) ← ic.mk_app ``inv_div [a, b],
return (ic, e', p)
end
theorem div_eq {α} [division_ring α] (a b b' c : α)
(hb : b⁻¹ = b') (h : a * b' = c) : a / b = c :=
by rwa [ ← hb, ← div_eq_mul_inv] at h
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/
meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
do (ic, b', pb) ← prove_inv ic b nb,
(ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹,
(ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p],
return (ic, c, p)
/-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/
meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) :=
match match_sign a with
| sum.inl a := do
(ic, p) ← ic.mk_app ``neg_neg [a],
return (ic, a, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``neg_zero [],
return (ic, a, p)
| sum.inr tt := do
(ic, a') ← ic.mk_app ``has_neg.neg [a],
p ← mk_eq_refl a',
return (ic, a', p)
end
theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c :=
by rwa [← hb, ← sub_eq_add_neg] at h
theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c :=
by rwa sub_neg_eq_add
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) :=
match match_sign b with
| sum.inl b := do
(ic, c, p) ← prove_add_rat' ic a b,
(ic, p) ← ic.mk_app ``sub_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``sub_zero [a],
return (ic, a, p)
| sum.inr tt := do
(ic, b', pb) ← prove_neg ic b,
(ic, c, p) ← prove_add_rat' ic a b',
(ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p],
return (ic, c, p)
end
theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c :=
h ▸ nat.add_sub_cancel_left _ _
theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 :=
nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _
/-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) :=
do na ← a.to_nat, nb ← b.to_nat,
if nb ≤ na then do
(ic, c) ← ic.of_nat (na - nb),
(ic, p) ← prove_add_nat ic b c a,
return (c, `(sub_nat_pos).mk_app [a, b, c, p])
else do
(ic, c) ← ic.of_nat (nb - na),
(ic, p) ← prove_add_nat ic a c b,
return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p])
/-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals.
Also handles nat subtraction. Does not do recursive simplification; that is,
`1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level
`simp` call in `norm_num.derive`. -/
meta def eval_field : expr → tactic (expr × expr)
| `(%%e₁ + %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
let n₃ := n₁ + n₂,
(c, e₃) ← c.of_rat n₃,
(_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃,
return (e₃, p)
| `(%%e₁ * %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂
| `(- %%e) := do
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_neg c e
| `(@has_sub.sub %%α %%inst %%a %%b) := do
c ← mk_instance_cache α,
if α = `(nat) then prove_sub_nat c a b
else prod.snd <$> prove_sub c a b
| `(has_inv.inv %%e) := do
n ← e.to_rat,
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_inv c e n
| `(%%e₁ / %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_div c e₁ e₂ n₁ n₂
| _ := failed
lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ)
(h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c :=
h₂ ▸ by simp [pow_bit0, h]
lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ)
(h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c :=
by rw [← h₃, ← h₂]; simp [pow_bit1, h]
section
open match_numeral_result
/-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/
meta def prove_pow (a : expr) (na : ℚ) :
instance_cache → expr → tactic (instance_cache × expr × expr)
| ic b :=
match match_numeral b with
| zero := do
(ic, p) ← ic.mk_app ``pow_zero [a],
(ic, o) ← ic.mk_app ``has_one.one [],
return (ic, o, p)
| one := do
(ic, p) ← ic.mk_app ``pow_one [a],
return (ic, a, p)
| bit0 b := do
(ic, c', p) ← prove_pow ic b,
nc' ← expr.to_rat c',
(ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc',
(ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂],
return (ic, c, p)
| bit1 b := do
(ic, c₁, p) ← prove_pow ic b,
nc₁ ← expr.to_rat c₁,
(ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁,
(ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na,
(ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃],
return (ic, c, p)
| _ := failed
end
end
/-- Evaluates expressions of the form `a ^ b`, `monoid.npow a b` or `nat.pow a b`. -/
meta def eval_pow : expr → tactic (expr × expr)
| `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
match m with
| `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂
| _ := failed
end
| `(monoid.npow %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_pow e₁ n₁ c e₂
| _ := failed
/-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/
meta def true_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(true) <$> mk_app ``eq_true_intro [p]
/-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/
meta def false_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(false) <$> mk_app ``eq_false_intro [p]
theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false :=
eq_false_intro $ not_not_intro rfl
/-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/
meta def eval_ineq : expr → tactic (expr × expr)
| `(%%e₁ < %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then
do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p
else if n₁ = n₂ then do
(_, p) ← c.mk_app ``lt_irrefl [e₁],
false_intro p
else do
(c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'],
false_intro p
| `(%%e₁ ≤ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ ≤ n₂ then do
(_, p) ←
if n₁ = n₂ then c.mk_app ``le_refl [e₁]
else prove_le_rat c e₁ e₂ n₁ n₂,
true_intro p
else do
(c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p],
false_intro p
| `(%%e₁ = %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p
| `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≠ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then
prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁]
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p
| _ := failed
theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁
/-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral.
(We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure
that towers of successors coming from e.g. `induction` are a common case.) -/
meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr)
| `(nat.succ %%a) := do
(ic, n, b, p₁) ← prove_nat_succ a,
let n' := n + 1,
(ic, c) ← ic.of_nat n',
(ic, p₂) ← prove_add_nat ic b `(1) c,
return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂])
| e := do
n ← e.to_nat,
p ← mk_eq_refl e,
return (ic, n, e, p)
lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q :=
by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂),
nat.div_eq_of_lt h₂, zero_add]
lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) :
a / b = q :=
by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)),
int.div_eq_zero_of_lt h₁ h₂, zero_add]
lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r :=
by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂]
lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) :
a % b = r :=
by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂]
lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c :=
h₂ ▸ h ▸ int.div_neg _ _
lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c :=
(int.mod_neg _ _).trans h
/-- Given `a`,`b` numerals in `nat` or `int`,
* `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)`
* `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)`
-/
meta def prove_div_mod (ic : instance_cache) :
expr → expr → bool → tactic (instance_cache × expr × expr)
| a b mod :=
match match_neg b with
| some b := do
(ic, c', p) ← prove_div_mod a b mod,
if mod then
return (ic, c', `(int_mod_neg).mk_app [a, b, c', p])
else do
(ic, c, p₂) ← prove_neg ic c',
return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂])
| none := do
nb ← b.to_nat,
na ← a.to_int,
let nq := na / nb,
let nr := na % nb,
let nm := nq * nr,
(ic, q) ← ic.of_int nq,
(ic, r) ← ic.of_int nr,
(ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb),
(ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na),
(ic, p') ← prove_lt_nat ic r b,
if ic.α = `(nat) then
if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p'])
else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p'])
else if ic.α = `(int) then do
(ic, p₀) ← prove_nonneg ic r,
if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else failed
end
theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂
theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂
theorem int_to_nat_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
a.to_nat = b := by rw ← h; simp
theorem int_to_nat_neg (a : ℤ) (h : 0 < a) : (-a).to_nat = 0 :=
by simp [int.to_nat_zero_of_neg, h]
theorem nat_abs_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
a.nat_abs = b := by rw ← h; simp
theorem nat_abs_neg (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
(-a).nat_abs = b := by rw ← h; simp
theorem neg_succ_of_nat (a b : ℕ) (c : ℤ) (h₁ : a + 1 = b)
(h₂ : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = c) :
-[1+ a] = -c := by rw [← h₂, ← h₁, int.nat_cast_eq_coe_nat]; refl
/-- Evaluates some extra numeric operations on `nat` and `int`, specifically
`nat.succ`, `/` and `%`, and `∣` (divisibility). -/
meta def eval_nat_int_ext : expr → tactic (expr × expr)
| e@`(nat.succ _) := do
ic ← mk_instance_cache `(ℕ),
(_, _, ep) ← prove_nat_succ ic e,
return ep
| `(%%a / %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b ff
| `(%%a % %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b tt
| `(%%a ∣ %%b) := do
α ← infer_type a,
ic ← mk_instance_cache α,
th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else
if α = `(int) then return `(dvd_eq_int) else failed,
(ic, c, p₁) ← prove_div_mod ic b a tt,
(ic, z) ← ic.mk_app ``has_zero.zero [],
(e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq,
return (e', th.mk_app [a, b, c, e', p₁, p₂])
| `(int.to_nat %%a) := do
n ← a.to_int,
ic ← mk_instance_cache `(ℤ),
if n ≥ 0 then do
nc ← mk_instance_cache `(ℕ),
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(int_to_nat_pos).mk_app [a, b, p])
else do
a ← match_neg a,
(_, p) ← prove_pos ic a,
pure (`(0), `(int_to_nat_neg).mk_app [a, p])
| `(int.nat_abs %%a) := do
n ← a.to_int,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
if n ≥ 0 then do
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(nat_abs_pos).mk_app [a, b, p])
else do
a ← match_neg a,
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(nat_abs_neg).mk_app [a, b, p])
| `(int.neg_succ_of_nat %%a) := do
na ← a.to_nat,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
let nb := na + 1,
(nc, b) ← nc.of_nat nb,
(nc, p₁) ← prove_add_nat nc a `(1) b,
(ic, c) ← ic.of_nat nb,
(_, _, _, p₂) ← prove_nat_uncast ic nc c,
pure (`(-%%c : ℤ), `(neg_succ_of_nat).mk_app [a, b, c, p₁, p₂])
| _ := failed
theorem int_to_nat_cast (a : ℕ) (b : ℤ)
(h : (by haveI := @nat.cast_coe ℤ; exact a : ℤ) = b) :
↑a = b := eq.trans (by simp) h
/-- Evaluates the `↑n` cast operation from `ℕ`, `ℤ`, `ℚ` to an arbitrary type `α`. -/
meta def eval_cast : expr → tactic (expr × expr)
| `(@coe ℕ %%α %%inst %%a) := do
if inst.is_app_of ``coe_to_lift then
if inst.app_arg.is_app_of ``nat.cast_coe then do
n ← a.to_nat,
ic ← mk_instance_cache α,
nc ← mk_instance_cache `(ℕ),
(ic, b) ← ic.of_nat n,
(_, _, _, p) ← prove_nat_uncast ic nc b,
pure (b, p)
else if inst.app_arg.is_app_of ``int.cast_coe then do
n ← a.to_int,
ic ← mk_instance_cache α,
zc ← mk_instance_cache `(ℤ),
(ic, b) ← ic.of_int n,
(_, _, _, p) ← prove_int_uncast ic zc b,
pure (b, p)
else if inst.app_arg.is_app_of ``int.cast_coe then do
n ← a.to_rat,
cz_inst ← mk_mapp ``char_zero [α, none, none] >>= mk_instance,
ic ← mk_instance_cache α,
qc ← mk_instance_cache `(ℚ),
(ic, b) ← ic.of_rat n,
(_, _, _, p) ← prove_rat_uncast ic qc cz_inst b n,
pure (b, p)
else failed
else if inst = `(@coe_base nat int int.has_coe) then do
n ← a.to_nat,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(ic, b) ← ic.of_nat n,
(_, _, _, p) ← prove_nat_uncast ic nc b,
pure (b, `(int_to_nat_cast).mk_app [a, b, p])
else failed
| _ := failed
/-- This version of `derive` does not fail when the input is already a numeral -/
meta def derive.step (e : expr) : tactic (expr × expr) :=
eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e
/-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put
`@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on
subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical
function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical
expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`,
`12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the
original expression is equal to the rewritten expression.
Failure is used to indicate that this tactic does not apply to the term. For performance reasons,
it is best to detect non-applicability as soon as possible so that the next tactic can have a go,
so generally it will start with a pattern match and then checking that the arguments to the term
are numerals or of the appropriate form, followed by proof construction, which should not fail.
Propositions are treated like any other term. The normal form for propositions is `true` or
`false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be
used to help here.
-/
@[user_attribute]
protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit :=
{ name := `norm_num,
descr := "Add norm_num derivers",
cache_cfg :=
{ mk_cache := λ ns, do {
t ← ns.mfoldl
(λ (t : expr → tactic (expr × expr)) n, do
t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []),
pure (λ e, t' e <|> t e))
(λ _, failed),
pure (λ e, derive.step e <|> t e) },
dependencies := [] } }
add_tactic_doc
{ name := "norm_num",
category := doc_category.attr,
decl_names := [`norm_num.attr],
tags := ["arithmetic", "decision_procedure"] }
/-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with
additional reduction procedures. -/
meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache
/-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/
meta def derive' (step : expr → tactic (expr × expr))
: expr → tactic (expr × expr) | e :=
do e ← instantiate_mvars e,
(_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← step e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
/-- Simplify an expression bottom-up using the default `norm_num` set to simplify the
subexpressions. -/
meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e
end norm_num
/-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic
to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for
the basic builtin set of simplifications. -/
meta def tactic.norm_num1 (step : expr → tactic (expr × expr))
(loc : interactive.loc) : tactic unit :=
do ns ← loc.get_locals,
success ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal,
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction,
monad.unlessb success $ done <|> fail "norm_num failed to simplify"
/-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression;
use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of
simplifications. -/
meta def tactic.norm_num (step : expr → tactic (expr × expr))
(hs : list simp_arg_type) (l : interactive.loc) : tactic unit :=
repeat1 $ orelse' (tactic.norm_num1 step l) $
interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none]))
ff (simp_arg_type.except ``one_div :: hs) [] l >> skip
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do f ← get_step, tactic.norm_num1 f loc
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit :=
do f ← get_step, tactic.norm_num f hs l
add_hint_tactic "norm_num"
/-- Normalizes a numerical expression and tries to close the goal with the result. -/
meta def apply_normed (x : parse texpr) : tactic unit :=
do x₁ ← to_expr x,
(x₂,_) ← derive x₁,
tactic.exact x₂
/--
Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over
numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`,
`A < B` and `A ≤ B`, where `A` and `B` are
numerical expressions. It also has a relatively simple primality prover.
```lean
import data.real.basic
example : (2 : ℝ) + 2 = 4 := by norm_num
example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num
example : (73 : ℝ) < 789/2 := by norm_num
example : 123456789 + 987654321 = 1111111110 := by norm_num
example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num
example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num
example : nat.prime (2^13 - 1) := by norm_num
example : ¬ nat.prime (2^11 - 1) := by norm_num
example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption
```
The variant `norm_num1` does not call `simp`.
Both `norm_num` and `norm_num1` can be called inside the `conv` tactic.
The tactic `apply_normed` normalises a numerical expression and tries to close the goal with
the result. Compare:
```lean
def a : ℕ := 2^100
#print a -- 2 ^ 100
def normed_a : ℕ := by apply_normed 2^100
#print normed_a -- 1267650600228229401496703205376
```
-/
add_tactic_doc
{ name := "norm_num",
category := doc_category.tactic,
decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num,
`tactic.interactive.apply_normed],
tags := ["arithmetic", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive tactic.interactive
open norm_num (derive)
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 : conv unit := replace_lhs derive
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) : conv unit :=
repeat1 $ orelse' norm_num1 $
conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) []
{ discharger := tactic.interactive.norm_num1 (loc.ns [none]) }
end conv.interactive
|
725d29df7a4aa0404c46fd1698e753d50d38e277 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/sites/sheaf.lean | c2983cbe2a316c9978fb10958bed4359c9ebd246 | [
"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 | 22,613 | lean | /-
Copyright (c) 2020 Kevin Buzzard, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Bhavik Mehta
-/
import category_theory.limits.preserves.shapes.equalizers
import category_theory.limits.preserves.shapes.products
import category_theory.limits.yoneda
import category_theory.sites.sheaf_of_types
/-!
# Sheaves taking values in a category
If C is a category with a Grothendieck topology, we define the notion of a sheaf taking values in
an arbitrary category `A`. We follow the definition in https://stacks.math.columbia.edu/tag/00VR,
noting that the presheaf of sets "defined above" can be seen in the comments between tags 00VQ and
00VR on the page <https://stacks.math.columbia.edu/tag/00VL>. The advantage of this definition is
that we need no assumptions whatsoever on `A` other than the assumption that the morphisms in `C`
and `A` live in the same universe.
* An `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is defined to be a sheaf (for the topology `J`) iff for
every `E : A`, the type-valued presheaves of sets given by sending `U : Cᵒᵖ` to `Hom_{A}(E, P U)`
are all sheaves of sets, see `category_theory.presheaf.is_sheaf`.
* When `A = Type`, this recovers the basic definition of sheaves of sets, see
`category_theory.is_sheaf_iff_is_sheaf_of_type`.
* An alternate definition when `C` is small, has pullbacks and `A` has products is given by an
equalizer condition `category_theory.presheaf.is_sheaf'`. This is equivalent to the earlier
definition, shown in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`.
* When `A = Type`, this is *definitionally* equal to the equalizer condition for presieves in
`category_theory.sites.sheaf_of_types`.
* When `A` has limits and there is a functor `s : A ⥤ Type` which is faithful, reflects isomorphisms
and preserves limits, then `P : Cᵒᵖ ⥤ A` is a sheaf iff the underlying presheaf of types
`P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf (`category_theory.presheaf.is_sheaf_iff_is_sheaf_forget`).
Cf https://stacks.math.columbia.edu/tag/0073, which is a weaker version of this statement (it's
only over spaces, not sites) and https://stacks.math.columbia.edu/tag/00YR (a), which
additionally assumes filtered colimits.
-/
universes w v₁ v₂ u₁ u₂
noncomputable theory
namespace category_theory
open opposite category_theory category limits sieve
namespace presheaf
variables {C : Type u₁} [category.{v₁} C]
variables {A : Type u₂} [category.{v₂} A]
variables (J : grothendieck_topology C)
-- We follow https://stacks.math.columbia.edu/tag/00VL definition 00VR
/--
A sheaf of A is a presheaf P : Cᵒᵖ => A such that for every E : A, the
presheaf of types given by sending U : C to Hom_{A}(E, P U) is a sheaf of types.
https://stacks.math.columbia.edu/tag/00VR
-/
def is_sheaf (P : Cᵒᵖ ⥤ A) : Prop :=
∀ E : A, presieve.is_sheaf J (P ⋙ coyoneda.obj (op E))
section limit_sheaf_condition
open presieve presieve.family_of_elements limits
variables (P : Cᵒᵖ ⥤ A) {X : C} (S : sieve X) (R : presieve X) (E : Aᵒᵖ)
/-- Given a sieve `S` on `X : C`, a presheaf `P : Cᵒᵖ ⥤ A`, and an object `E` of `A`,
the cones over the natural diagram `S.arrows.diagram.op ⋙ P` associated to `S` and `P`
with cone point `E` are in 1-1 correspondence with sieve_compatible family of elements
for the sieve `S` and the presheaf of types `Hom (E, P -)`. -/
@[simps] def cones_equiv_sieve_compatible_family :
(S.arrows.diagram.op ⋙ P).cones.obj E ≃
{x : family_of_elements (P ⋙ coyoneda.obj E) S // x.sieve_compatible} :=
{ to_fun := λ π, ⟨λ Y f h, π.app (op ⟨over.mk f, h⟩), λ _, by
{ intros, apply (id_comp _).symm.trans, dsimp,
convert π.naturality (quiver.hom.op (over.hom_mk _ _)); dsimp; refl }⟩,
inv_fun := λ x, { app := λ f, x.1 f.unop.1.hom f.unop.2,
naturality' := λ f f' g, by
{ refine eq.trans _ (x.2 f.unop.1.hom g.unop.left f.unop.2),
erw id_comp, congr, rw over.w g.unop } },
left_inv := λ π, by { ext, dsimp, congr,
rw op_eq_iff_eq_unop, ext, symmetry, apply costructured_arrow.eq_mk },
right_inv := λ x, by { ext, refl } }
variables {P S E} {x : family_of_elements (P ⋙ coyoneda.obj E) S} (hx : x.sieve_compatible)
/-- The cone corresponding to a sieve_compatible family of elements, dot notation enabled. -/
@[simp] def _root_.category_theory.presieve.family_of_elements.sieve_compatible.cone :
cone (S.arrows.diagram.op ⋙ P) :=
{ X := E.unop, π := (cones_equiv_sieve_compatible_family P S E).inv_fun ⟨x,hx⟩ }
/-- Cone morphisms from the cone corresponding to a sieve_compatible family to the natural
cone associated to a sieve `S` and a presheaf `P` are in 1-1 correspondence with amalgamations
of the family. -/
def hom_equiv_amalgamation :
(hx.cone ⟶ P.map_cone S.arrows.cocone.op) ≃ {t // x.is_amalgamation t} :=
{ to_fun := λ l, ⟨l.hom, λ Y f hf, l.w (op ⟨over.mk f, hf⟩)⟩,
inv_fun := λ t, ⟨t.1, λ f, t.2 f.unop.1.hom f.unop.2⟩,
left_inv := λ l, by { ext, refl },
right_inv := λ t, by { ext, refl } }
variables (P S)
/-- Given sieve `S` and presheaf `P : Cᵒᵖ ⥤ A`, their natural associated cone is a limit cone
iff `Hom (E, P -)` is a sheaf of types for the sieve `S` and all `E : A`. -/
lemma is_limit_iff_is_sheaf_for :
nonempty (is_limit (P.map_cone S.arrows.cocone.op)) ↔
∀ E : Aᵒᵖ, is_sheaf_for (P ⋙ coyoneda.obj E) S :=
begin
dsimp [is_sheaf_for], simp_rw compatible_iff_sieve_compatible,
rw ((cone.is_limit_equiv_is_terminal _).trans (is_terminal_equiv_unique _ _)).nonempty_congr,
rw classical.nonempty_pi, split,
{ intros hu E x hx, specialize hu hx.cone,
erw (hom_equiv_amalgamation hx).unique_congr.nonempty_congr at hu,
exact (unique_subtype_iff_exists_unique _).1 hu },
{ rintros h ⟨E,π⟩, let eqv := cones_equiv_sieve_compatible_family P S (op E),
rw ← eqv.left_inv π, erw (hom_equiv_amalgamation (eqv π).2).unique_congr.nonempty_congr,
rw unique_subtype_iff_exists_unique, exact h _ _ (eqv π).2 },
end
/-- Given sieve `S` and presheaf `P : Cᵒᵖ ⥤ A`, their natural associated cone admits at most one
morphism from every cone in the same category (i.e. over the same diagram),
iff `Hom (E, P -)`is separated for the sieve `S` and all `E : A`. -/
lemma subsingleton_iff_is_separated_for :
(∀ c, subsingleton (c ⟶ P.map_cone S.arrows.cocone.op)) ↔
∀ E : Aᵒᵖ, is_separated_for (P ⋙ coyoneda.obj E) S :=
begin
split,
{ intros hs E x t₁ t₂ h₁ h₂, have hx := is_compatible_of_exists_amalgamation x ⟨t₁,h₁⟩,
rw compatible_iff_sieve_compatible at hx, specialize hs hx.cone, cases hs,
have := (hom_equiv_amalgamation hx).symm.injective,
exact subtype.ext_iff.1 (@this ⟨t₁,h₁⟩ ⟨t₂,h₂⟩ (hs _ _)) },
{ rintros h ⟨E,π⟩, let eqv := cones_equiv_sieve_compatible_family P S (op E), split,
rw ← eqv.left_inv π, intros f₁ f₂, let eqv' := hom_equiv_amalgamation (eqv π).2,
apply eqv'.injective, ext, apply h _ (eqv π).1; exact (eqv' _).2 },
end
/-- A presheaf `P` is a sheaf for the Grothendieck topology `J` iff for every covering sieve
`S` of `J`, the natural cone associated to `P` and `S` is a limit cone. -/
lemma is_sheaf_iff_is_limit : is_sheaf J P ↔
∀ ⦃X : C⦄ (S : sieve X), S ∈ J X → nonempty (is_limit (P.map_cone S.arrows.cocone.op)) :=
⟨λ h X S hS, (is_limit_iff_is_sheaf_for P S).2 (λ E, h E.unop S hS),
λ h E X S hS, (is_limit_iff_is_sheaf_for P S).1 (h S hS) (op E)⟩
/-- A presheaf `P` is separated for the Grothendieck topology `J` iff for every covering sieve
`S` of `J`, the natural cone associated to `P` and `S` admits at most one morphism from every
cone in the same category. -/
lemma is_separated_iff_subsingleton :
(∀ E : A, is_separated J (P ⋙ coyoneda.obj (op E))) ↔
∀ ⦃X : C⦄ (S : sieve X), S ∈ J X → ∀ c, subsingleton (c ⟶ P.map_cone S.arrows.cocone.op) :=
⟨λ h X S hS, (subsingleton_iff_is_separated_for P S).2 (λ E, h E.unop S hS),
λ h E X S hS, (subsingleton_iff_is_separated_for P S).1 (h S hS) (op E)⟩
/-- Given presieve `R` and presheaf `P : Cᵒᵖ ⥤ A`, the natural cone associated to `P` and
the sieve `sieve.generate R` generated by `R` is a limit cone iff `Hom (E, P -)` is a
sheaf of types for the presieve `R` and all `E : A`. -/
lemma is_limit_iff_is_sheaf_for_presieve :
nonempty (is_limit (P.map_cone (generate R).arrows.cocone.op)) ↔
∀ E : Aᵒᵖ, is_sheaf_for (P ⋙ coyoneda.obj E) R :=
(is_limit_iff_is_sheaf_for P _).trans (forall_congr (λ _, (is_sheaf_for_iff_generate _).symm))
/-- A presheaf `P` is a sheaf for the Grothendieck topology generated by a pretopology `K`
iff for every covering presieve `R` of `K`, the natural cone associated to `P` and
`sieve.generate R` is a limit cone. -/
lemma is_sheaf_iff_is_limit_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ ∀ ⦃X : C⦄ (R : presieve X), R ∈ K X →
nonempty (is_limit (P.map_cone (generate R).arrows.cocone.op)) :=
by { dsimp [is_sheaf], simp_rw is_sheaf_pretopology, exact
⟨λ h X R hR, (is_limit_iff_is_sheaf_for_presieve P R).2 (λ E, h E.unop R hR),
λ h E X R hR, (is_limit_iff_is_sheaf_for_presieve P R).1 (h R hR) (op E)⟩ }
end limit_sheaf_condition
variable {J}
/-- This is a wrapper around `presieve.is_sheaf_for.amalgamate` to be used below.
If `P`s a sheaf, `S` is a cover of `X`, and `x` is a collection of morphisms from `E`
to `P` evaluated at terms in the cover which are compatible, then we can amalgamate
the `x`s to obtain a single morphism `E ⟶ P.obj (op X)`. -/
def is_sheaf.amalgamate {A : Type u₂} [category.{max v₁ u₁} A]
{E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X)
(x : Π (I : S.arrow), E ⟶ P.obj (op I.Y))
(hx : ∀ (I : S.relation), x I.fst ≫ P.map I.g₁.op = x I.snd ≫ P.map I.g₂.op) :
E ⟶ P.obj (op X) :=
(hP _ _ S.condition).amalgamate (λ Y f hf, x ⟨Y,f,hf⟩) $
λ Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ w, hx ⟨Y₁, Y₂, Z, g₁, g₂, f₁, f₂, h₁, h₂, w⟩
@[simp, reassoc]
lemma is_sheaf.amalgamate_map {A : Type u₂} [category.{max v₁ u₁} A]
{E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X)
(x : Π (I : S.arrow), E ⟶ P.obj (op I.Y))
(hx : ∀ (I : S.relation), x I.fst ≫ P.map I.g₁.op = x I.snd ≫ P.map I.g₂.op)
(I : S.arrow) : hP.amalgamate S x hx ≫ P.map I.f.op = x _ :=
begin
rcases I with ⟨Y,f,hf⟩,
apply @presieve.is_sheaf_for.valid_glue _ _ _ _ _ _ (hP _ _ S.condition)
(λ Y f hf, x ⟨Y,f,hf⟩)
(λ Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ w, hx ⟨Y₁, Y₂, Z, g₁, g₂, f₁, f₂, h₁, h₂, w⟩) f hf,
end
lemma is_sheaf.hom_ext {A : Type u₂} [category.{max v₁ u₁} A]
{E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X)
(e₁ e₂ : E ⟶ P.obj (op X)) (h : ∀ (I : S.arrow), e₁ ≫ P.map I.f.op = e₂ ≫ P.map I.f.op) :
e₁ = e₂ :=
(hP _ _ S.condition).is_separated_for.ext (λ Y f hf, h ⟨Y,f,hf⟩)
variable (J)
end presheaf
variables {C : Type u₁} [category.{v₁} C]
variables (J : grothendieck_topology C)
variables (A : Type u₂) [category.{v₂} A]
/-- The category of sheaves taking values in `A` on a grothendieck topology. -/
structure Sheaf :=
(val : Cᵒᵖ ⥤ A)
(cond : presheaf.is_sheaf J val)
namespace Sheaf
variables {J A}
/-- Morphisms between sheaves are just morphisms of presheaves. -/
@[ext]
structure hom (X Y : Sheaf J A) :=
(val : X.val ⟶ Y.val)
@[simps]
instance : category (Sheaf J A) :=
{ hom := hom,
id := λ X, ⟨𝟙 _⟩,
comp := λ X Y Z f g, ⟨f.val ≫ g.val⟩,
id_comp' := λ X Y f, hom.ext _ _ $ id_comp _,
comp_id' := λ X Y f, hom.ext _ _ $ comp_id _,
assoc' := λ X Y Z W f g h, hom.ext _ _ $ assoc _ _ _ }
-- Let's make the inhabited linter happy...
instance (X : Sheaf J A) : inhabited (hom X X) := ⟨𝟙 X⟩
end Sheaf
/-- The inclusion functor from sheaves to presheaves. -/
@[simps]
def Sheaf_to_presheaf : Sheaf J A ⥤ (Cᵒᵖ ⥤ A) :=
{ obj := Sheaf.val,
map := λ _ _ f, f.val,
map_id' := λ X, rfl,
map_comp' := λ X Y Z f g, rfl }
instance : full (Sheaf_to_presheaf J A) := { preimage := λ X Y f, ⟨f⟩ }
instance : faithful (Sheaf_to_presheaf J A) := {}
/-- The sheaf of sections guaranteed by the sheaf condition. -/
@[simps] def sheaf_over {A : Type u₂} [category.{v₂} A] {J : grothendieck_topology C}
(ℱ : Sheaf J A) (E : A) : SheafOfTypes J := ⟨ℱ.val ⋙ coyoneda.obj (op E), ℱ.cond E⟩
lemma is_sheaf_iff_is_sheaf_of_type (P : Cᵒᵖ ⥤ Type w) :
presheaf.is_sheaf J P ↔ presieve.is_sheaf J P :=
begin
split,
{ intros hP,
refine presieve.is_sheaf_iso J _ (hP punit),
exact iso_whisker_left _ coyoneda.punit_iso ≪≫ P.right_unitor },
{ intros hP X Y S hS z hz,
refine ⟨λ x, (hP S hS).amalgamate (λ Z f hf, z f hf x) _, _, _⟩,
{ intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ h,
exact congr_fun (hz g₁ g₂ hf₁ hf₂ h) x },
{ intros Z f hf,
ext x,
apply presieve.is_sheaf_for.valid_glue },
{ intros y hy,
ext x,
apply (hP S hS).is_separated_for.ext,
intros Y' f hf,
rw [presieve.is_sheaf_for.valid_glue _ _ _ hf, ← hy _ hf],
refl } }
end
/--
The category of sheaves taking values in Type is the same as the category of set-valued sheaves.
-/
@[simps]
def Sheaf_equiv_SheafOfTypes : Sheaf J (Type w) ≌ SheafOfTypes J :=
{ functor :=
{ obj := λ S, ⟨S.val, (is_sheaf_iff_is_sheaf_of_type _ _).1 S.2⟩,
map := λ S T f, ⟨f.val⟩ },
inverse :=
{ obj := λ S, ⟨S.val, (is_sheaf_iff_is_sheaf_of_type _ _ ).2 S.2⟩,
map := λ S T f, ⟨f.val⟩ },
unit_iso := nat_iso.of_components (λ X, ⟨⟨𝟙 _⟩, ⟨𝟙 _⟩, by tidy, by tidy⟩) (by tidy),
counit_iso := nat_iso.of_components (λ X, ⟨⟨𝟙 _⟩, ⟨𝟙 _⟩, by tidy, by tidy⟩) (by tidy) }
instance : inhabited (Sheaf (⊥ : grothendieck_topology C) (Type w)) :=
⟨(Sheaf_equiv_SheafOfTypes _).inverse.obj default⟩
variables {J} {A}
/-- If the empty sieve is a cover of `X`, then `F(X)` is terminal. -/
def Sheaf.is_terminal_of_bot_cover (F : Sheaf J A) (X : C) (H : ⊥ ∈ J X) :
is_terminal (F.1.obj (op X)) :=
begin
apply_with is_terminal.of_unique { instances := ff },
intro Y,
choose t h using F.2 Y _ H (by tidy) (by tidy),
exact ⟨⟨t⟩, λ a, h.2 a (by tidy)⟩
end
end category_theory
namespace category_theory
open opposite category_theory category limits sieve
namespace presheaf
-- Under here is the equalizer story, which is equivalent if A has products (and doesn't
-- make sense otherwise). It's described in https://stacks.math.columbia.edu/tag/00VL,
-- between 00VQ and 00VR.
variables {C : Type u₁} [category.{v₁} C]
variables {A : Type u₂} [category.{max v₁ u₁} A]
variables (J : grothendieck_topology C)
variables {U : C} (R : presieve U)
variables (P : Cᵒᵖ ⥤ A)
section multiequalizer_conditions
/-- When `P` is a sheaf and `S` is a cover, the associated multifork is a limit. -/
def is_limit_of_is_sheaf {X : C} (S : J.cover X) (hP : is_sheaf J P) :
is_limit (S.multifork P) :=
{ lift := λ (E : multifork _), hP.amalgamate S (λ I, E.ι _) (λ I, E.condition _),
fac' := begin
rintros (E : multifork _) (a|b),
{ apply hP.amalgamate_map },
{ rw [← E.w (walking_multicospan.hom.fst b),
← (S.multifork P).w (walking_multicospan.hom.fst b), ← assoc],
congr' 1,
apply hP.amalgamate_map }
end,
uniq' := begin
rintros (E : multifork _) m hm,
apply hP.hom_ext S,
intros I,
erw hm (walking_multicospan.left I),
symmetry,
apply hP.amalgamate_map
end }
lemma is_sheaf_iff_multifork : is_sheaf J P ↔
(∀ (X : C) (S : J.cover X), nonempty (is_limit (S.multifork P))) :=
begin
refine ⟨λ hP X S, ⟨is_limit_of_is_sheaf _ _ _ hP⟩, _⟩,
intros h E X S hS x hx,
let T : J.cover X := ⟨S,hS⟩,
obtain ⟨hh⟩ := h _ T,
let K : multifork (T.index P) :=
multifork.of_ι _ E (λ I, x I.f I.hf) (λ I, hx _ _ _ _ I.w),
use hh.lift K,
dsimp, split,
{ intros Y f hf,
apply hh.fac K (walking_multicospan.left ⟨Y,f,hf⟩) },
{ intros e he,
apply hh.uniq K,
rintros (a|b),
{ apply he },
{ rw [← K.w (walking_multicospan.hom.fst b),
← (T.multifork P).w (walking_multicospan.hom.fst b), ← assoc],
congr' 1,
apply he } }
end
lemma is_sheaf_iff_multiequalizer
[∀ (X : C) (S : J.cover X), has_multiequalizer (S.index P)] : is_sheaf J P ↔
(∀ (X : C) (S : J.cover X), is_iso (S.to_multiequalizer P)) :=
begin
rw is_sheaf_iff_multifork,
refine forall₂_congr (λ X S, ⟨_, _⟩),
{ rintros ⟨h⟩,
let e : P.obj (op X) ≅ multiequalizer (S.index P) :=
h.cone_point_unique_up_to_iso (limit.is_limit _),
exact (infer_instance : is_iso e.hom) },
{ introsI h,
refine ⟨is_limit.of_iso_limit (limit.is_limit _) (cones.ext _ _)⟩,
{ apply (@as_iso _ _ _ _ _ h).symm },
{ intros a,
symmetry,
erw is_iso.inv_comp_eq,
change _ = limit.lift _ _ ≫ _,
simp } }
end
end multiequalizer_conditions
section
variables [has_products A]
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def first_obj : A :=
∏ (λ (f : Σ V, {f : V ⟶ U // R f}), P.obj (op f.1))
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def fork_map : P.obj (op U) ⟶ first_obj R P :=
pi.lift (λ f, P.map f.2.1.op)
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : A :=
∏ (λ (fg : (Σ V, {f : V ⟶ U // R f}) × (Σ W, {g : W ⟶ U // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of <https://stacks.math.columbia.edu/tag/00VM>. -/
def first_map : first_obj R P ⟶ second_obj R P :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
/-- The map `pr₁*` of <https://stacks.math.columbia.edu/tag/00VM>. -/
def second_map : first_obj R P ⟶ second_obj R P :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map R P ≫ first_map R P = fork_map R P ≫ second_map R P :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map, limit.lift_π, limit.lift_π_assoc, assoc,
fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
An alternative definition of the sheaf condition in terms of equalizers. This is shown to be
equivalent in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`.
-/
def is_sheaf' (P : Cᵒᵖ ⥤ A) : Prop := ∀ (U : C) (R : presieve U) (hR : generate R ∈ J U),
nonempty (is_limit (fork.of_ι _ (w R P)))
/-- (Implementation). An auxiliary lemma to convert between sheaf conditions. -/
def is_sheaf_for_is_sheaf_for' (P : Cᵒᵖ ⥤ A) (s : A ⥤ Type (max v₁ u₁))
[Π J, preserves_limits_of_shape (discrete.{max v₁ u₁} J) s] (U : C) (R : presieve U) :
is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃
is_limit (fork.of_ι _ (equalizer.presieve.w (P ⋙ s) R)) :=
begin
apply equiv.trans (is_limit_map_cone_fork_equiv _ _) _,
apply (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _),
{ apply nat_iso.of_components _ _,
{ rintro (_ | _),
{ apply preserves_product.iso s },
{ apply preserves_product.iso s } },
{ rintro _ _ (_ | _),
{ ext : 1,
dsimp [equalizer.presieve.first_map, first_map],
simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp],
erw pi_comparison_comp_π_assoc },
{ ext : 1,
dsimp [equalizer.presieve.second_map, second_map],
simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp],
erw pi_comparison_comp_π_assoc },
{ dsimp,
simp } } },
{ refine fork.ext (iso.refl _) _,
dsimp [equalizer.fork_map, fork_map],
simp [fork.ι] }
end
/-- The equalizer definition of a sheaf given by `is_sheaf'` is equivalent to `is_sheaf`. -/
theorem is_sheaf_iff_is_sheaf' :
is_sheaf J P ↔ is_sheaf' J P :=
begin
split,
{ intros h U R hR,
refine ⟨_⟩,
apply coyoneda_jointly_reflects_limits,
intro X,
have q : presieve.is_sheaf_for (P ⋙ coyoneda.obj X) _ := h X.unop _ hR,
rw ←presieve.is_sheaf_for_iff_generate at q,
rw equalizer.presieve.sheaf_condition at q,
replace q := classical.choice q,
apply (is_sheaf_for_is_sheaf_for' _ _ _ _).symm q },
{ intros h U X S hS,
rw equalizer.presieve.sheaf_condition,
refine ⟨_⟩,
refine is_sheaf_for_is_sheaf_for' _ _ _ _ _,
apply is_limit_of_preserves,
apply classical.choice (h _ S _),
simpa }
end
end
section concrete
variables [has_pullbacks C]
/--
For a concrete category `(A, s)` where the forgetful functor `s : A ⥤ Type v` preserves limits and
reflects isomorphisms, and `A` has limits, an `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is a sheaf iff its
underlying `Type`-valued presheaf `P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf.
Note this lemma applies for "algebraic" categories, eg groups, abelian groups and rings, but not
for the category of topological spaces, topological rings, etc since reflecting isomorphisms doesn't
hold.
-/
lemma is_sheaf_iff_is_sheaf_forget (s : A ⥤ Type (max v₁ u₁))
[has_limits A] [preserves_limits s] [reflects_isomorphisms s] :
is_sheaf J P ↔ is_sheaf J (P ⋙ s) :=
begin
rw [is_sheaf_iff_is_sheaf', is_sheaf_iff_is_sheaf'],
apply forall_congr (λ U, _),
apply ball_congr (λ R hR, _),
letI : reflects_limits s := reflects_limits_of_reflects_isomorphisms,
have : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (w R (P ⋙ s))) :=
is_sheaf_for_is_sheaf_for' P s U R,
rw ←equiv.nonempty_congr this,
split,
{ exact nonempty.map (λ t, is_limit_of_preserves s t) },
{ exact nonempty.map (λ t, is_limit_of_reflects s t) }
end
end concrete
end presheaf
end category_theory
|
8c01879db5126e6037ae28c311403e5c6580b249 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /linear_algebra/linear_map_module.lean | eed9ee082c44bada73819ca30f0bf5b47864d6e0 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 8,746 | 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, Kenny Lau
Type of linear functions
-/
import linear_algebra.basic
linear_algebra.prod_module
linear_algebra.quotient_module
linear_algebra.subtype_module
noncomputable theory
local attribute [instance] classical.prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace classical
lemma some_spec2 {α : Type u} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) :
q (some h) :=
hpq _ $ some_spec _
end classical
/-- The type of linear maps `β → γ` between α-modules β and γ -/
def linear_map {α : Type u} (β : Type v) (γ : Type w) [ring α] [module α β] [module α γ] :=
subtype (@is_linear_map α β γ _ _ _)
namespace linear_map
variables [ring α] [module α β] [module α γ]
variables {r : α} {A B C : linear_map β γ} {x y : β}
include α
instance : has_coe_to_fun (linear_map β γ) := ⟨_, subtype.val⟩
theorem ext (h : ∀ x, A x = B x) : A = B := subtype.eq $ funext h
lemma is_linear_map_coe : is_linear_map A := A.property
@[simp] lemma map_add : A (x + y) = A x + A y := is_linear_map_coe.add x y
@[simp] lemma map_smul : A (r • x) = r • A x := is_linear_map_coe.smul r x
@[simp] lemma map_zero : A 0 = 0 := is_linear_map_coe.zero
@[simp] lemma map_neg : A (-x) = -A x := is_linear_map_coe.neg _
@[simp] lemma map_sub : A (x - y) = A x - A y := is_linear_map_coe.sub _ _
/- kernel -/
/-- Kernel of a linear map, i.e. the set of vectors mapped to zero by the map -/
def ker (A : linear_map β γ) : set β := {y | A y = 0}
section ker
@[simp] lemma mem_ker : x ∈ A.ker ↔ A x = 0 := iff.rfl
theorem ker_of_map_eq_map (h : A x = A y) : x - y ∈ A.ker :=
by rw [mem_ker, map_sub]; exact sub_eq_zero_of_eq h
theorem inj_of_trivial_ker (H : A.ker ⊆ {0}) (h : A x = A y) : x = y :=
eq_of_sub_eq_zero $ set.eq_of_mem_singleton $ H $ ker_of_map_eq_map h
variables (α A)
instance ker.is_submodule : is_submodule A.ker :=
{ zero_ := map_zero,
add_ := λ x y HU HV, by rw mem_ker at *; simp [HU, HV, mem_ker],
smul := λ r x HV, by rw mem_ker at *; simp [HV] }
theorem sub_ker (HU : x ∈ A.ker) (HV : y ∈ A.ker) : x - y ∈ A.ker :=
is_submodule.sub HU HV
end ker
/- image -/
/-- Image of a linear map, the set of vectors of the form `A x` for some β -/
def im (A : linear_map β γ) : set γ := {x | ∃ y, A y = x}
@[simp] lemma mem_im {A : linear_map β γ} {z : γ} :
z ∈ A.im ↔ ∃ y, A y = z := iff.rfl
instance im.is_submodule : is_submodule A.im :=
{ zero_ := ⟨0, map_zero⟩,
add_ := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x + y, by simp [hx, hy]⟩,
smul := λ r a ⟨x, hx⟩, ⟨r • x, by simp [hx]⟩ }
/- equivalences -/
section
open is_submodule
/-- first isomorphism law -/
def quot_ker_equiv_im (f : linear_map β γ) : (quotient β f.ker) ≃ₗ f.im :=
{ to_fun := is_submodule.quotient.lift _
(is_linear_map_subtype_mk f.1 f.2 $ assume b, ⟨b, rfl⟩) (assume b eq, subtype.eq eq),
inv_fun := λb, @quotient.mk _ (quotient_rel _) (classical.some b.2),
left_inv := assume b', @quotient.induction_on _ (quotient_rel _) _ b' $
begin
assume b,
apply quotient.sound,
apply classical.some_spec2 (λa, f (a - b) = 0),
show (∀a, f a = f b → f (a - b) = 0), simp {contextual := tt}
end,
right_inv := assume c, subtype.eq $ classical.some_spec2 (λa, f a = c) $ assume b, id,
linear_fun :=
is_linear_map_quotient_lift _ $ @is_linear_map_subtype_mk _ _ _ _ _ _ f.im _ f f.2 _ }
lemma is_submodule.add_left_iff {s : set β} [is_submodule s] {b₁ b₂ : β} (h₂ : b₂ ∈ s) :
b₁ + b₂ ∈ s ↔ b₁ ∈ s :=
iff.intro
(assume h,
have b₁ + b₂ - b₂ ∈ s, from is_submodule.sub h h₂,
by rwa [add_sub_cancel] at this)
(assume h₁, is_submodule.add h₁ h₂)
lemma is_submodule.neg_iff {s : set β} [is_submodule s] {b : β} :
- b ∈ s ↔ b ∈ s :=
iff.intro
(assume h,
have - - b ∈ s, from is_submodule.neg h,
by rwa [neg_neg] at this)
is_submodule.neg
/-- second isomorphism law -/
def union_quotient_equiv_quotient_inter {s t : set β} [is_submodule s] [is_submodule t] :
quotient s (subtype.val ⁻¹' (s ∩ t)) ≃ₗ quotient (span (s ∪ t)) (subtype.val ⁻¹' t) :=
let sel₁ : s → span (s ∪ t) := λb, ⟨b.1, subset_span $ or.inl b.2⟩ in
have sel₁_val : ∀b:s, (sel₁ b).1 = b.1, from assume b, rfl,
have ∀b'∈span (s ∪ t), ∃x:s, ∃y∈t, b' = x.1 + y,
by simp [span_union, span_eq_of_is_submodule, _inst_4, _inst_5] {contextual := tt},
let sel₂ : span (s ∪ t) → s := λb', classical.some (this b'.1 b'.2) in
have sel₂_spec : ∀b':span (s ∪ t), ∃y∈t, b'.1 = (sel₂ b').1 + y,
from assume b', classical.some_spec (this b'.1 b'.2),
{ to_fun :=
begin
intro b,
fapply @quotient.lift_on _ _ (quotient_rel _) b,
{ intro b', apply quotient.mk, exact (sel₁ b') },
{ intros b₁ b₂ h, apply quotient.sound, simp [quotient_rel_eq, *] at * }
end,
inv_fun :=
begin
intro b,
fapply @quotient.lift_on _ _ (quotient_rel _) b,
{ intro b', apply quotient.mk, exact sel₂ b' },
{ intros b₁ b₂ h,
rcases (sel₂_spec b₁) with ⟨c₁, hc₁, eq_c₁⟩,
rcases (sel₂_spec b₂) with ⟨c₂, hc₂, eq_c₂⟩,
have : ((sel₂ b₁).1 - (sel₂ b₂).1) + (c₁ - c₂) ∈ t,
{ simpa [quotient_rel_eq, eq_c₁, eq_c₂, add_comm, add_left_comm, add_assoc] using h },
have ht : (sel₂ b₁).1 - (sel₂ b₂).1 ∈ t,
{ rwa [is_submodule.add_left_iff (is_submodule.sub hc₁ hc₂)] at this },
have hs : (sel₂ b₁).1 - (sel₂ b₂).1 ∈ s,
{ from is_submodule.sub (sel₂ b₁).2 (sel₂ b₂).2 },
apply quotient.sound,
simp [quotient_rel_eq, *] at * }
end,
right_inv := assume b', @quotient.induction_on _ (quotient_rel _) _ b'
begin
intro b, apply quotient.sound,
rcases (sel₂_spec b) with ⟨c, hc, eq_c⟩,
simp [quotient_rel_eq, eq_c, hc, is_submodule.neg_iff]
end,
left_inv := assume b', @quotient.induction_on _ (quotient_rel _) _ b'
begin
intro b, apply quotient.sound,
rcases (sel₂_spec (sel₁ b)) with ⟨c, hc, eq⟩,
have b_eq : b.1 = c + (sel₂ (sel₁ b)).1,
{ simpa [sel₁_val] using eq },
have : b.1 ∈ s, from b.2,
have hcs : c ∈ s,
{ rwa [b_eq, is_submodule.add_left_iff (sel₂ (sel₁ b)).2] at this },
show (sel₂ (sel₁ b) - b).1 ∈ s ∩ t, { simp [eq, hc, hcs, is_submodule.neg_iff] }
end,
linear_fun := is_linear_map_quotient_lift _ $ (is_linear_map_quotient_mk _).comp $
is_linear_map_subtype_mk _ (is_linear_map_subtype_val is_linear_map.id) _ }
end
section add_comm_group
instance : has_add (linear_map β γ) := ⟨λhf hg, ⟨_, hf.2.map_add hg.2⟩⟩
instance : has_zero (linear_map β γ) := ⟨⟨_, is_linear_map.map_zero⟩⟩
instance : has_neg (linear_map β γ) := ⟨λhf, ⟨_, hf.2.map_neg⟩⟩
@[simp] lemma add_app : (A + B) x = A x + B x := rfl
@[simp] lemma zero_app : (0 : linear_map β γ) x = 0 := rfl
@[simp] lemma neg_app : (-A) x = -A x := rfl
instance : add_comm_group (linear_map β γ) :=
by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply ext, simp }
end add_comm_group
end linear_map
namespace linear_map
variables [comm_ring α] [module α β] [module α γ]
instance : has_scalar α (linear_map β γ) := ⟨λr f, ⟨λb, r • f b, f.2.map_smul_right⟩⟩
@[simp] lemma smul_app {r : α} {x : β} {A : linear_map β γ} : (r • A) x = r • (A x) := rfl
variables (α β γ)
instance : module α (linear_map β γ) :=
by refine {smul := (•), ..linear_map.add_comm_group, ..};
{ intros, apply ext, simp [smul_add, add_smul, mul_smul] }
end linear_map
namespace module
variables [ring α] [module α β]
include α β
instance : has_one (linear_map β β) := ⟨⟨id, is_linear_map.id⟩⟩
instance : has_mul (linear_map β β) := ⟨λf g, ⟨_, is_linear_map.comp f.2 g.2⟩⟩
@[simp] lemma one_app (x : β) : (1 : linear_map β β) x = x := rfl
@[simp] lemma mul_app (A B : linear_map β β) (x : β) : (A * B) x = A (B x) := rfl
variables (α β)
-- declaring this an instance breaks `real.lean` with reaching max. instance resolution depth
def endomorphism_ring : ring (linear_map β β) :=
by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..};
{ intros, apply linear_map.ext, simp }
/-- The group of invertible linear maps from `β` to itself -/
def general_linear_group :=
by haveI := endomorphism_ring α β; exact units (linear_map β β)
end module
|
bff225c0529f2f0b7e059029814ca9f2efb28eb1 | ecad13897fdb44984cf1968424224d1750040236 | /lean/lean/examples/example01.lean | f2cff77c41def19414ff3620d80721067b1ca04f | [] | no_license | MetaBorgCube/sdf3-demo | 4899159b1cfb0a95ae3af325035bbba8a1255477 | e831606d5b404eba75b087916a1162923143b98a | refs/heads/master | 1,609,472,086,310 | 1,553,380,857,000 | 1,553,380,857,000 | 59,577,395 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25 | lean | (a : A) -> (z : S) -> x
|
d10f9e0376bd3c193cd770ba4b6a3634fb626a23 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/module/linear_map.lean | 91dc7de0d87514f36b25d38fc126f2c4317b6bc8 | [
"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 | 32,874 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen,
Frédéric Dupuis, Heather Macbeth
-/
import algebra.group.hom
import algebra.module.basic
import algebra.module.pi
import algebra.group_action_hom
import algebra.ring.comp_typeclasses
/-!
# (Semi)linear maps
In this file we define
* `linear_map σ M M₂`, `M →ₛₗ[σ] M₂` : a semilinear map between two `module`s. Here,
`σ` is a `ring_hom` from `R` to `R₂` and an `f : M →ₛₗ[σ] M₂` satisfies
`f (c • x) = (σ c) • (f x)`. We recover plain linear maps by choosing `σ` to be `ring_hom.id R`.
This is denoted by `M →ₗ[R] M₂`. We also add the notation `M →ₗ⋆[R] M₂` for star-linear maps.
* `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. (Note that this
was not generalized to semilinear maps.)
We then provide `linear_map` with the following instances:
* `linear_map.add_comm_monoid` and `linear_map.add_comm_group`: the elementwise addition structures
corresponding to addition in the codomain
* `linear_map.distrib_mul_action` and `linear_map.module`: the elementwise scalar action structures
corresponding to applying the action in the codomain.
* `module.End.semiring` and `module.End.ring`: the (semi)ring of endomorphisms formed by taking the
additive structure above with composition as multiplication.
## Implementation notes
To ensure that composition works smoothly for semilinear maps, we use the typeclasses
`ring_hom_comp_triple`, `ring_hom_inv_pair` and `ring_hom_surjective` from
`algebra/ring/comp_typeclasses`.
## Notation
* Throughout the file, we denote regular linear maps by `fₗ`, `gₗ`, etc, and semilinear maps
by `f`, `g`, etc.
## TODO
* Parts of this file have not yet been generalized to semilinear maps (i.e. `compatible_smul`)
## Tags
linear map
-/
open function
open_locale big_operators
universes u u' v w x y z
variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*}
variables {k : Type*} {S : Type*} {S₃ : Type*} {T : Type*}
variables {M : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*}
variables {N₁ : Type*} {N₂ : Type*} {N₃ : Type*} {ι : Type*}
/-- A map `f` between modules over a semiring is linear if it satisfies the two properties
`f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this
property. A bundled version is available with `linear_map`, and should be favored over
`is_linear_map` most of the time. -/
structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w}
[semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂]
(f : M → M₂) : Prop :=
(map_add : ∀ x y, f (x + y) = f x + f y)
(map_smul : ∀ (c : R) x, f (c • x) = c • f x)
section
set_option old_structure_cmd true
/-- A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S`
is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and
`f (c • x) = (σ c) • f x`. Elements of `linear_map σ M M₂` (available under the notation
`M →ₛₗ[σ] M₂`) are bundled versions of such maps. For plain linear maps (i.e. for which
`σ = ring_hom.id R`), the notation `M →ₗ[R] M₂` is available. An unbundled version of plain linear
maps is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/
structure linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S)
(M : Type*) (M₂ : Type*)
[add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂]
extends add_hom M M₂ :=
(map_smul' : ∀ (r : R) (x : M), to_fun (r • x) = (σ r) • to_fun x)
end
/-- The `add_hom` underlying a `linear_map`. -/
add_decl_doc linear_map.to_add_hom
notation M ` →ₛₗ[`:25 σ:25 `] `:0 M₂:0 := linear_map σ M M₂
notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map (ring_hom.id R) M M₂
notation M ` →ₗ⋆[`:25 R:25 `] `:0 M₂:0 := linear_map (star_ring_end R) M M₂
namespace linear_map
section add_comm_monoid
variables [semiring R] [semiring S]
section
variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃]
variables [module R M] [module R M₂] [module S M₃]
variables {σ : R →+* S}
instance : add_monoid_hom_class (M →ₛₗ[σ] M₃) M M₃ :=
{ coe := linear_map.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr',
map_add := linear_map.map_add',
map_zero := λ f, show f.to_fun 0 = 0, by { rw [← zero_smul R (0 : M), f.map_smul'], simp } }
/-- The `distrib_mul_action_hom` underlying a `linear_map`. -/
def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ :=
{ map_zero' := show f 0 = 0, from map_zero f, ..f }
/-- Helper instance for when there's too many metavariables to apply `to_fun.to_coe_fn` directly.
-/
instance : has_coe_to_fun (M →ₛₗ[σ] M₃) (λ _, M → M₃) := ⟨linear_map.to_fun⟩
@[simp] lemma to_fun_eq_coe {f : M →ₛₗ[σ] M₃} : f.to_fun = (f : M → M₃) := rfl
@[ext] theorem ext {f g : M →ₛₗ[σ] M₃} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
/-- Copy of a `linear_map` with a new `to_fun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : M →ₛₗ[σ] M₃) (f' : M → M₃) (h : f' = ⇑f) : M →ₛₗ[σ] M₃ :=
{ to_fun := f',
map_add' := h.symm ▸ f.map_add',
map_smul' := h.symm ▸ f.map_smul' }
initialize_simps_projections linear_map (to_fun → apply)
@[simp] lemma coe_mk {σ : R →+* S} (f : M → M₃) (h₁ h₂) :
((linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) : M → M₃) = f := rfl
/-- Identity map as a `linear_map` -/
def id : M →ₗ[R] M :=
{ to_fun := id, ..distrib_mul_action_hom.id R }
lemma id_apply (x : M) :
@id R M _ _ _ x = x := rfl
@[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id :=
by { ext x, refl }
end
section
variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃]
variables [module R M] [module R M₂] [module S M₃]
variables (σ : R →+* S)
variables (fₗ gₗ : M →ₗ[R] M₂) (f g : M →ₛₗ[σ] M₃)
theorem is_linear : is_linear_map R fₗ := ⟨fₗ.map_add', fₗ.map_smul'⟩
variables {fₗ gₗ f g σ}
theorem coe_injective : @injective (M →ₛₗ[σ] M₃) (M → M₃) coe_fn :=
fun_like.coe_injective
protected lemma congr_arg {x x' : M} : x = x' → f x = f x' :=
fun_like.congr_arg f
/-- If two linear maps are equal, they are equal at each point. -/
protected lemma congr_fun (h : f = g) (x : M) : f x = g x :=
fun_like.congr_fun h x
theorem ext_iff : f = g ↔ ∀ x, f x = g x :=
fun_like.ext_iff
@[simp] lemma mk_coe (f : M →ₛₗ[σ] M₃) (h₁ h₂) :
(linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) = f := ext $ λ _, rfl
variables (fₗ gₗ f g)
protected lemma map_add (x y : M) : f (x + y) = f x + f y := map_add f x y
@[simp] lemma map_smulₛₗ (c : R) (x : M) : f (c • x) = (σ c) • f x := f.map_smul' c x
lemma map_smul (c : R) (x : M) : fₗ (c • x) = c • fₗ x := fₗ.map_smul' c x
lemma map_smul_inv {σ' : S →+* R} [ring_hom_inv_pair σ σ'] (c : S) (x : M) :
c • f x = f (σ' c • x) :=
by simp
protected lemma map_zero : f 0 = 0 := map_zero f
-- TODO: generalize to `zero_hom_class`
@[simp] lemma map_eq_zero_iff (h : function.injective f) {x : M} : f x = 0 ↔ x = 0 :=
⟨λ w, by { apply h, simp [w], }, λ w, by { subst w, simp, }⟩
section pointwise
open_locale pointwise
@[simp] lemma image_smul_setₛₗ (c : R) (s : set M) :
f '' (c • s) = (σ c) • f '' s :=
begin
apply set.subset.antisymm,
{ rintros x ⟨y, ⟨z, zs, rfl⟩, rfl⟩,
exact ⟨f z, set.mem_image_of_mem _ zs, (f.map_smulₛₗ _ _).symm ⟩ },
{ rintros x ⟨y, ⟨z, hz, rfl⟩, rfl⟩,
exact (set.mem_image _ _ _).2 ⟨c • z, set.smul_mem_smul_set hz, f.map_smulₛₗ _ _⟩ }
end
lemma image_smul_set (c : R) (s : set M) :
fₗ '' (c • s) = c • fₗ '' s :=
by simp
lemma preimage_smul_setₛₗ {c : R} (hc : is_unit c) (s : set M₃) :
f ⁻¹' (σ c • s) = c • f ⁻¹' s :=
begin
apply set.subset.antisymm,
{ rintros x ⟨y, ys, hy⟩,
refine ⟨(hc.unit.inv : R) • x, _, _⟩,
{ simp only [←hy, smul_smul, set.mem_preimage, units.inv_eq_coe_inv, map_smulₛₗ, ← σ.map_mul,
is_unit.coe_inv_mul, one_smul, ring_hom.map_one, ys] },
{ simp only [smul_smul, is_unit.mul_coe_inv, one_smul, units.inv_eq_coe_inv] } },
{ rintros x ⟨y, hy, rfl⟩,
refine ⟨f y, hy, by simp only [ring_hom.id_apply, linear_map.map_smulₛₗ]⟩ }
end
lemma preimage_smul_set {c : R} (hc : is_unit c) (s : set M₂) :
fₗ ⁻¹' (c • s) = c • fₗ ⁻¹' s :=
fₗ.preimage_smul_setₛₗ hc s
end pointwise
variables (M M₂)
/--
A typeclass for `has_scalar` structures which can be moved through a `linear_map`.
This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that
we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if
`R` does not support negation.
-/
class compatible_smul (R S : Type*) [semiring S] [has_scalar R M]
[module S M] [has_scalar R M₂] [module S M₂] :=
(map_smul : ∀ (fₗ : M →ₗ[S] M₂) (c : R) (x : M), fₗ (c • x) = c • fₗ x)
variables {M M₂}
@[priority 100]
instance is_scalar_tower.compatible_smul
{R S : Type*} [semiring S] [has_scalar R S]
[has_scalar R M] [module S M] [is_scalar_tower R S M]
[has_scalar R M₂] [module S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S :=
⟨λ fₗ c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (fₗ x), map_smul]⟩
@[simp, priority 900]
lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M]
[module S M] [has_scalar R M₂] [module S M₂]
[compatible_smul M M₂ R S] (fₗ : M →ₗ[S] M₂) (c : R) (x : M) :
fₗ (c • x) = c • fₗ x :=
compatible_smul.map_smul fₗ c x
/-- convert a linear map to an additive map -/
def to_add_monoid_hom : M →+ M₃ :=
{ to_fun := f,
map_zero' := f.map_zero,
map_add' := f.map_add }
@[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl
section restrict_scalars
variables (R) [module S M] [module S M₂] [compatible_smul M M₂ R S]
/-- If `M` and `M₂` are both `R`-modules and `S`-modules and `R`-module structures
are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear
map from `M` to `M₂` is `R`-linear.
See also `linear_map.map_smul_of_tower`. -/
@[simps]
def restrict_scalars (fₗ : M →ₗ[S] M₂) : M →ₗ[R] M₂ :=
{ to_fun := fₗ,
map_add' := fₗ.map_add,
map_smul' := fₗ.map_smul_of_tower }
lemma restrict_scalars_injective :
function.injective (restrict_scalars R : (M →ₗ[S] M₂) → (M →ₗ[R] M₂)) :=
λ fₗ gₗ h, ext (linear_map.congr_fun h : _)
@[simp]
lemma restrict_scalars_inj (fₗ gₗ : M →ₗ[S] M₂) :
fₗ.restrict_scalars R = gₗ.restrict_scalars R ↔ fₗ = gₗ :=
(restrict_scalars_injective R).eq_iff
end restrict_scalars
variable {R}
@[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} :
f (∑ i in t, g i) = (∑ i in t, f (g i)) :=
f.to_add_monoid_hom.map_sum _ _
theorem to_add_monoid_hom_injective :
function.injective (to_add_monoid_hom : (M →ₛₗ[σ] M₃) → (M →+ M₃)) :=
λ f g h, ext $ add_monoid_hom.congr_fun h
/-- If two `σ`-linear maps from `R` are equal on `1`, then they are equal. -/
@[ext] theorem ext_ring {f g : R →ₛₗ[σ] M₃} (h : f 1 = g 1) : f = g :=
ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smulₛₗ, g.map_smulₛₗ, h]
theorem ext_ring_iff {σ : R →+* R} {f g : R →ₛₗ[σ] M} : f = g ↔ f 1 = g 1 :=
⟨λ h, h ▸ rfl, ext_ring⟩
end
/-- Interpret a `ring_hom` `f` as an `f`-semilinear map. -/
@[simps]
def _root_.ring_hom.to_semilinear_map (f : R →+* S) : R →ₛₗ[f] S :=
{ to_fun := f,
map_smul' := f.map_mul,
.. f}
section
variables [semiring R₁] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables {module_M₁ : module R₁ M₁} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃}
variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
variables (f : M₂ →ₛₗ[σ₂₃] M₃) (g : M₁ →ₛₗ[σ₁₂] M₂)
include module_M₁ module_M₂ module_M₃
/-- Composition of two linear maps is a linear map -/
def comp : M₁ →ₛₗ[σ₁₃] M₃ :=
{ to_fun := f ∘ g,
map_add' := by simp only [map_add, forall_const, eq_self_iff_true, comp_app],
map_smul' := λ r x, by rw [comp_app, map_smulₛₗ, map_smulₛₗ, ring_hom_comp_triple.comp_apply] }
omit module_M₁ module_M₂ module_M₃
infixr ` ∘ₗ `:80 := @linear_map.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
(ring_hom.id _) (ring_hom.id _) (ring_hom.id _) ring_hom_comp_triple.ids
include σ₁₃
lemma comp_apply (x : M₁) : f.comp g x = f (g x) := rfl
omit σ₁₃
include σ₁₃
@[simp, norm_cast] lemma coe_comp : (f.comp g : M₁ → M₃) = f ∘ g := rfl
omit σ₁₃
@[simp] theorem comp_id : f.comp id = f :=
linear_map.ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
linear_map.ext $ λ x, rfl
end
variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
/-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/
def inverse [module R M] [module S M₂] {σ : R →+* S} {σ' : S →+* R} [ring_hom_inv_pair σ σ']
(f : M →ₛₗ[σ] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) :
M₂ →ₛₗ[σ'] M :=
by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact
{ to_fun := g,
map_add' := λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] },
map_smul' := λ a b, by { rw [← h₁ (g (a • b)), ← h₁ ((σ' a) • g b)], simp [h₂] } }
end add_comm_monoid
section add_comm_group
variables [semiring R] [semiring S] [add_comm_group M] [add_comm_group M₂]
variables {module_M : module R M} {module_M₂ : module S M₂} {σ : R →+* S}
variables (f : M →ₛₗ[σ] M₂)
protected lemma map_neg (x : M) : f (- x) = - f x := map_neg f x
protected lemma map_sub (x y : M) : f (x - y) = f x - f y := map_sub f x y
instance compatible_smul.int_module
{S : Type*} [semiring S] [module S M] [module S M₂] : compatible_smul M M₂ ℤ S :=
⟨λ fₗ c x, begin
induction c using int.induction_on,
case hz : { simp },
case hp : n ih { simp [add_smul, ih] },
case hn : n ih { simp [sub_smul, ih] }
end⟩
instance compatible_smul.units {R S : Type*}
[monoid R] [mul_action R M] [mul_action R M₂] [semiring S] [module S M] [module S M₂]
[compatible_smul M M₂ R S] :
compatible_smul M M₂ Rˣ S :=
⟨λ fₗ c x, (compatible_smul.map_smul fₗ (c : R) x : _)⟩
end add_comm_group
end linear_map
namespace module
/-- `g : R →+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/
@[simps]
def comp_hom.to_linear_map {R S : Type*} [semiring R] [semiring S] (g : R →+* S) :
(by haveI := comp_hom S g; exact (R →ₗ[R] S)) :=
by exact
{ to_fun := (g : R → S),
map_add' := g.map_add,
map_smul' := g.map_mul }
end module
namespace distrib_mul_action_hom
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂]
/-- A `distrib_mul_action_hom` between two modules is a linear map. -/
def to_linear_map (fₗ : M →+[R] M₂) : M →ₗ[R] M₂ := { ..fₗ }
instance : has_coe (M →+[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
@[simp] lemma to_linear_map_eq_coe (f : M →+[R] M₂) :
f.to_linear_map = ↑f :=
rfl
@[simp, norm_cast] lemma coe_to_linear_map (f : M →+[R] M₂) :
((f : M →ₗ[R] M₂) : M → M₂) = f :=
rfl
lemma to_linear_map_injective {f g : M →+[R] M₂} (h : (f : M →ₗ[R] M₂) = (g : M →ₗ[R] M₂)) :
f = g :=
by { ext m, exact linear_map.congr_fun h m, }
end distrib_mul_action_hom
namespace is_linear_map
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
variables [module R M] [module R M₂]
include R
/-- Convert an `is_linear_map` predicate to a `linear_map` -/
def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ[R] M₂ :=
{ to_fun := f, map_add' := H.1, map_smul' := H.2 }
@[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) :
mk' f H x = f x := rfl
lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M]
(c : R) :
is_linear_map R (λ (z : M), c • z) :=
begin
refine is_linear_map.mk (smul_add c) _,
intros _ _,
simp only [smul_smul, mul_comm]
end
lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (a : M) :
is_linear_map R (λ (c : R), c • a) :=
is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a)
variables {f : M → M₂} (lin : is_linear_map R f)
include M M₂ lin
lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero
end add_comm_monoid
section add_comm_group
variables [semiring R] [add_comm_group M] [add_comm_group M₂]
variables [module R M] [module R M₂]
include R
lemma is_linear_map_neg :
is_linear_map R (λ (z : M), -z) :=
is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm)
variables {f : M → M₂} (lin : is_linear_map R f)
include M M₂ lin
lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x
lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y
end add_comm_group
end is_linear_map
/-- Linear endomorphisms of a module, with associated ring structure
`module.End.semiring` and algebra structure `module.End.algebra`. -/
abbreviation module.End (R : Type u) (M : Type v)
[semiring R] [add_comm_monoid M] [module R M] := M →ₗ[R] M
/-- Reinterpret an additive homomorphism as a `ℕ`-linear map. -/
def add_monoid_hom.to_nat_linear_map [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) :
M →ₗ[ℕ] M₂ :=
{ to_fun := f, map_add' := f.map_add, map_smul' := f.map_nat_module_smul }
lemma add_monoid_hom.to_nat_linear_map_injective [add_comm_monoid M] [add_comm_monoid M₂] :
function.injective (@add_monoid_hom.to_nat_linear_map M M₂ _ _) :=
by { intros f g h, ext, exact linear_map.congr_fun h x }
/-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/
def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) :
M →ₗ[ℤ] M₂ :=
{ to_fun := f, map_add' := f.map_add, map_smul' := f.map_int_module_smul }
lemma add_monoid_hom.to_int_linear_map_injective [add_comm_group M] [add_comm_group M₂] :
function.injective (@add_monoid_hom.to_int_linear_map M M₂ _ _) :=
by { intros f g h, ext, exact linear_map.congr_fun h x }
@[simp] lemma add_monoid_hom.coe_to_int_linear_map [add_comm_group M] [add_comm_group M₂]
(f : M →+ M₂) :
⇑f.to_int_linear_map = f := rfl
/-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/
def add_monoid_hom.to_rat_linear_map [add_comm_group M] [module ℚ M]
[add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) :
M →ₗ[ℚ] M₂ :=
{ map_smul' := f.map_rat_module_smul, ..f }
lemma add_monoid_hom.to_rat_linear_map_injective
[add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] :
function.injective (@add_monoid_hom.to_rat_linear_map M M₂ _ _ _ _) :=
by { intros f g h, ext, exact linear_map.congr_fun h x }
@[simp] lemma add_monoid_hom.coe_to_rat_linear_map [add_comm_group M] [module ℚ M]
[add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) :
⇑f.to_rat_linear_map = f := rfl
namespace linear_map
/-! ### Arithmetic on the codomain -/
section arithmetic
variables [semiring R₁] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [add_comm_group N₁] [add_comm_group N₂] [add_comm_group N₃]
variables [module R₁ M] [module R₂ M₂] [module R₃ M₃]
variables [module R₁ N₁] [module R₂ N₂] [module R₃ N₃]
variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
/-- The constant 0 map is linear. -/
instance : has_zero (M →ₛₗ[σ₁₂] M₂) :=
⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩
@[simp] lemma zero_apply (x : M) : (0 : M →ₛₗ[σ₁₂] M₂) x = 0 := rfl
@[simp] theorem comp_zero (g : M₂ →ₛₗ[σ₂₃] M₃) : (g.comp (0 : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃) = 0 :=
ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, g.map_zero]
@[simp] theorem zero_comp (f : M →ₛₗ[σ₁₂] M₂) : ((0 : M₂ →ₛₗ[σ₂₃] M₃).comp f : M →ₛₗ[σ₁₃] M₃) = 0 :=
rfl
instance : inhabited (M →ₛₗ[σ₁₂] M₂) := ⟨0⟩
@[simp] lemma default_def : (default : (M →ₛₗ[σ₁₂] M₂)) = 0 := rfl
/-- The sum of two linear maps is linear. -/
instance : has_add (M →ₛₗ[σ₁₂] M₂) :=
⟨λ f g, { to_fun := f + g,
map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩
@[simp] lemma add_apply (f g : M →ₛₗ[σ₁₂] M₂) (x : M) : (f + g) x = f x + g x := rfl
lemma add_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] M₃) :
((h + g).comp f : M →ₛₗ[σ₁₃] M₃) = h.comp f + g.comp f := rfl
lemma comp_add (f g : M →ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃) :
(h.comp (f + g) : M →ₛₗ[σ₁₃] M₃) = h.comp f + h.comp g :=
ext $ λ _, h.map_add _ _
/-- The type of linear maps is an additive monoid. -/
instance : add_comm_monoid (M →ₛₗ[σ₁₂] M₂) :=
{ zero := 0,
add := (+),
add_assoc := λ f g h, linear_map.ext $ λ x, add_assoc _ _ _,
zero_add := λ f, linear_map.ext $ λ x, zero_add _,
add_zero := λ f, linear_map.ext $ λ x, add_zero _,
add_comm := λ f g, linear_map.ext $ λ x, add_comm _ _,
nsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x,
begin
rw [f.map_smulₛₗ],
simp [smul_comm n (σ₁₂ c) (f x)],
end },
nsmul_zero' := λ f, linear_map.ext $ λ x, add_comm_monoid.nsmul_zero' _,
nsmul_succ' := λ n f, linear_map.ext $ λ x, add_comm_monoid.nsmul_succ' _ _ }
/-- The negation of a linear map is linear. -/
instance : has_neg (M →ₛₗ[σ₁₂] N₂) :=
⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩
@[simp] lemma neg_apply (f : M →ₛₗ[σ₁₂] N₂) (x : M) : (- f) x = - f x := rfl
include σ₁₃
@[simp] lemma neg_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] N₃) : (- g).comp f = - g.comp f := rfl
@[simp] lemma comp_neg (f : M →ₛₗ[σ₁₂] N₂) (g : N₂ →ₛₗ[σ₂₃] N₃) : g.comp (- f) = - g.comp f :=
ext $ λ _, g.map_neg _
omit σ₁₃
/-- The negation of a linear map is linear. -/
instance : has_sub (M →ₛₗ[σ₁₂] N₂) :=
⟨λ f g, { to_fun := f - g,
map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm],
map_smul' := λ r x, by simp [pi.sub_apply, map_smul, smul_sub] }⟩
@[simp] lemma sub_apply (f g : M →ₛₗ[σ₁₂] N₂) (x : M) : (f - g) x = f x - g x := rfl
include σ₁₃
lemma sub_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] N₃) :
(g - h).comp f = g.comp f - h.comp f := rfl
lemma comp_sub (f g : M →ₛₗ[σ₁₂] N₂) (h : N₂ →ₛₗ[σ₂₃] N₃) :
h.comp (g - f) = h.comp g - h.comp f :=
ext $ λ _, h.map_sub _ _
omit σ₁₃
/-- The type of linear maps is an additive group. -/
instance : add_comm_group (M →ₛₗ[σ₁₂] N₂) :=
{ zero := 0,
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
sub_eq_add_neg := λ f g, linear_map.ext $ λ m, sub_eq_add_neg _ _,
add_left_neg := λ f, linear_map.ext $ λ m, add_left_neg _,
nsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] },
zsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] },
zsmul_zero' := λ a, linear_map.ext $ λ m, zero_smul _ _,
zsmul_succ' := λ n a, linear_map.ext $ λ m, add_comm_group.zsmul_succ' n _,
zsmul_neg' := λ n a, linear_map.ext $ λ m, add_comm_group.zsmul_neg' n _,
.. linear_map.add_comm_monoid }
end arithmetic
section actions
variables [semiring R] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
section has_scalar
variables [monoid S] [distrib_mul_action S M₂] [smul_comm_class R₂ S M₂]
variables [monoid S₃] [distrib_mul_action S₃ M₃] [smul_comm_class R₃ S₃ M₃]
variables [monoid T] [distrib_mul_action T M₂] [smul_comm_class R₂ T M₂]
instance : has_scalar S (M →ₛₗ[σ₁₂] M₂) :=
⟨λ a f, { to_fun := a • f,
map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add],
map_smul' := λ c x, by simp [pi.smul_apply, smul_comm (σ₁₂ c)] }⟩
@[simp] lemma smul_apply (a : S) (f : M →ₛₗ[σ₁₂] M₂) (x : M) : (a • f) x = a • f x := rfl
lemma coe_smul (a : S) (f : M →ₛₗ[σ₁₂] M₂) : ⇑(a • f) = a • f := rfl
instance [smul_comm_class S T M₂] : smul_comm_class S T (M →ₛₗ[σ₁₂] M₂) :=
⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩
-- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and
-- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible.
instance [has_scalar S T] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₛₗ[σ₁₂] M₂) :=
{ smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ }
instance [distrib_mul_action Sᵐᵒᵖ M₂] [smul_comm_class R₂ Sᵐᵒᵖ M₂] [is_central_scalar S M₂] :
is_central_scalar S (M →ₛₗ[σ₁₂] M₂) :=
{ op_smul_eq_smul := λ a b, ext $ λ x, op_smul_eq_smul _ _ }
instance : distrib_mul_action S (M →ₛₗ[σ₁₂] M₂) :=
{ one_smul := λ f, ext $ λ _, one_smul _ _,
mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _,
smul_add := λ c f g, ext $ λ x, smul_add _ _ _,
smul_zero := λ c, ext $ λ x, smul_zero _ }
include σ₁₃
theorem smul_comp (a : S₃) (g : M₂ →ₛₗ[σ₂₃] M₃) (f : M →ₛₗ[σ₁₂] M₂) :
(a • g).comp f = a • (g.comp f) := rfl
omit σ₁₃
-- TODO: generalize this to semilinear maps
theorem comp_smul [module R M₂] [module R M₃] [smul_comm_class R S M₂] [distrib_mul_action S M₃]
[smul_comm_class R S M₃] [compatible_smul M₃ M₂ S R]
(g : M₃ →ₗ[R] M₂) (a : S) (f : M →ₗ[R] M₃) : g.comp (a • f) = a • (g.comp f) :=
ext $ λ x, g.map_smul_of_tower _ _
end has_scalar
section module
variables [semiring S] [module S M₂] [smul_comm_class R₂ S M₂]
instance : module S (M →ₛₗ[σ₁₂] M₂) :=
{ add_smul := λ a b f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
instance [no_zero_smul_divisors S M₂] : no_zero_smul_divisors S (M →ₛₗ[σ₁₂] M₂) :=
coe_injective.no_zero_smul_divisors _ rfl coe_smul
end module
end actions
/-!
### Monoid structure of endomorphisms
Lemmas about `pow` such as `linear_map.pow_apply` appear in later files.
-/
section endomorphisms
variables [semiring R] [add_comm_monoid M] [add_comm_group N₁] [module R M] [module R N₁]
instance : has_one (module.End R M) := ⟨linear_map.id⟩
instance : has_mul (module.End R M) := ⟨linear_map.comp⟩
lemma one_eq_id : (1 : module.End R M) = id := rfl
lemma mul_eq_comp (f g : module.End R M) : f * g = f.comp g := rfl
@[simp] lemma one_apply (x : M) : (1 : module.End R M) x = x := rfl
@[simp] lemma mul_apply (f g : module.End R M) (x : M) : (f * g) x = f (g x) := rfl
lemma coe_one : ⇑(1 : module.End R M) = _root_.id := rfl
lemma coe_mul (f g : module.End R M) : ⇑(f * g) = f ∘ g := rfl
instance _root_.module.End.monoid : monoid (module.End R M) :=
{ mul := (*),
one := (1 : M →ₗ[R] M),
mul_assoc := λ f g h, linear_map.ext $ λ x, rfl,
mul_one := comp_id,
one_mul := id_comp }
instance _root_.module.End.semiring : semiring (module.End R M) :=
{ mul := (*),
one := (1 : M →ₗ[R] M),
zero := 0,
add := (+),
npow := @npow_rec _ ⟨(1 : M →ₗ[R] M)⟩ ⟨(*)⟩,
mul_zero := comp_zero,
zero_mul := zero_comp,
left_distrib := λ f g h, comp_add _ _ _,
right_distrib := λ f g h, add_comp _ _ _,
.. _root_.module.End.monoid,
.. linear_map.add_comm_monoid }
instance _root_.module.End.ring : ring (module.End R N₁) :=
{ ..module.End.semiring, ..linear_map.add_comm_group }
section
variables [monoid S] [distrib_mul_action S M] [smul_comm_class R S M]
instance _root_.module.End.is_scalar_tower :
is_scalar_tower S (module.End R M) (module.End R M) := ⟨smul_comp⟩
instance _root_.module.End.smul_comm_class [has_scalar S R] [is_scalar_tower S R M] :
smul_comm_class S (module.End R M) (module.End R M) :=
⟨λ s _ _, (comp_smul _ s _).symm⟩
instance _root_.module.End.smul_comm_class' [has_scalar S R] [is_scalar_tower S R M] :
smul_comm_class (module.End R M) S (module.End R M) :=
smul_comm_class.symm _ _ _
end
/-! ### Action by a module endomorphism. -/
/-- The tautological action by `module.End R M` (aka `M →ₗ[R] M`) on `M`.
This generalizes `function.End.apply_mul_action`. -/
instance apply_module : module (module.End R M) M :=
{ smul := ($),
smul_zero := linear_map.map_zero,
smul_add := linear_map.map_add,
add_smul := linear_map.add_apply,
zero_smul := (linear_map.zero_apply : ∀ m, (0 : M →ₗ[R] M) m = 0),
one_smul := λ _, rfl,
mul_smul := λ _ _ _, rfl }
@[simp] protected lemma smul_def (f : module.End R M) (a : M) : f • a = f a := rfl
/-- `linear_map.apply_module` is faithful. -/
instance apply_has_faithful_scalar : has_faithful_scalar (module.End R M) M :=
⟨λ _ _, linear_map.ext⟩
instance apply_smul_comm_class : smul_comm_class R (module.End R M) M :=
{ smul_comm := λ r e m, (e.map_smul r m).symm }
instance apply_smul_comm_class' : smul_comm_class (module.End R M) R M :=
{ smul_comm := linear_map.map_smul }
instance apply_is_scalar_tower {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] :
is_scalar_tower R (module.End R M) M :=
⟨λ t f m, rfl⟩
end endomorphisms
end linear_map
/-! ### Actions as module endomorphisms -/
namespace distrib_mul_action
variables (R M) [semiring R] [add_comm_monoid M] [module R M]
variables [monoid S] [distrib_mul_action S M] [smul_comm_class S R M]
/-- Each element of the monoid defines a linear map.
This is a stronger version of `distrib_mul_action.to_add_monoid_hom`. -/
@[simps]
def to_linear_map (s : S) : M →ₗ[R] M :=
{ to_fun := has_scalar.smul s,
map_add' := smul_add s,
map_smul' := λ a b, smul_comm _ _ _ }
/-- Each element of the monoid defines a module endomorphism.
This is a stronger version of `distrib_mul_action.to_add_monoid_End`. -/
@[simps]
def to_module_End : S →* module.End R M :=
{ to_fun := to_linear_map R M,
map_one' := linear_map.ext $ one_smul _,
map_mul' := λ a b, linear_map.ext $ mul_smul _ _ }
end distrib_mul_action
namespace module
variables (R M) [semiring R] [add_comm_monoid M] [module R M]
variables [semiring S] [module S M] [smul_comm_class S R M]
/-- Each element of the monoid defines a module endomorphism.
This is a stronger version of `distrib_mul_action.to_module_End`. -/
@[simps]
def to_module_End : S →+* module.End R M :=
{ to_fun := distrib_mul_action.to_linear_map R M,
map_zero' := linear_map.ext $ zero_smul _,
map_add' := λ f g, linear_map.ext $ add_smul _ _,
..distrib_mul_action.to_module_End R M }
end module
|
ac262c4beed633abb46affbb5b16c6a35b695eab | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/algebra/group_with_zero/basic.lean | 677b487ae8f31faab06e2f974e89f2398ac2574c | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 35,430 | 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 logic.nontrivial
import algebra.group.units_hom
import algebra.group.inj_surj
import algebra.group_with_zero.defs
/-!
# Groups with an adjoined zero element
This file describes structures that are not usually studied on their own right in mathematics,
namely a special sort of monoid: apart from a distinguished “zero element” they form a group,
or in other words, they are groups with an adjoined zero element.
Examples are:
* division rings;
* the value monoid of a multiplicative valuation;
* in particular, the non-negative real numbers.
## Main definitions
Various lemmas about `group_with_zero` and `comm_group_with_zero`.
To reduce import dependencies, the type-classes themselves are in
`algebra.group_with_zero.defs`.
## Implementation details
As is usual in mathlib, we extend the inverse function to the zero element,
and require `0⁻¹ = 0`.
-/
set_option old_structure_cmd true
open_locale classical
open function
variables {M₀ G₀ M₀' G₀' : Type*}
mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to
reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are
division-free."
section
section mul_zero_class
variables [mul_zero_class M₀] {a b : M₀}
/-- Pullback a `mul_zero_class` instance along an injective function. -/
protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul],
mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] }
/-- Pushforward a `mul_zero_class` instance along an surjective function. -/
protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero],
zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] }
lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b
lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a
lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b)
lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a)
lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩
lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) :
a * b = 0 :=
if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero]
end mul_zero_class
/-- Pushforward a `no_zero_divisors` instance along an injective function. -/
protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀]
[has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀']
(f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
no_zero_divisors M₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H,
have f x * f y = 0, by rw [← mul, H, zero],
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) }
lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀]
{a : M₀} (h : a * a = 0) :
a = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id
section
variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀}
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero,
λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
/-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them
are nonzero. -/
theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr mul_eq_zero).trans not_or_distrib
theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero_iff.2 ⟨ha, hb⟩
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is
`b * a`. -/
theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 :=
mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is
`b * a`. -/
theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 :=
not_congr mul_eq_zero_comm
lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp
lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp
end
end
section
variables [monoid_with_zero M₀] [nontrivial M₀] {a b : M₀}
/-- In a nontrivial monoid with zero, zero and one are different. -/
@[simp] lemma zero_ne_one : 0 ≠ (1:M₀) :=
begin
assume h,
rcases exists_pair_ne M₀ with ⟨x, y, hx⟩,
apply hx,
calc x = 1 * x : by rw [one_mul]
... = 0 : by rw [← h, zero_mul]
... = 1 * y : by rw [← h, zero_mul]
... = y : by rw [one_mul]
end
@[simp] lemma one_ne_zero : (1:M₀) ≠ 0 :=
zero_ne_one.symm
lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 :=
calc a = 1 : h
... ≠ 0 : one_ne_zero
lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 :=
left_ne_zero_of_mul $ ne_zero_of_eq_one h
lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 :=
right_ne_zero_of_mul $ ne_zero_of_eq_one h
/-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/
protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' :=
⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩
end
/-- The division operation on a group with zero element. -/
@[priority 100] -- see Note [lower instance priority]
instance group_with_zero.has_div {G₀ : Type*} [group_with_zero G₀] :
has_div G₀ := ⟨λ g h, g * h⁻¹⟩
section monoid_with_zero
/-- Pullback a `monoid_with_zero` class along an injective function. -/
protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function. -/
protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pullback a `monoid_with_zero` class along an injective function. -/
protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function. -/
protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
variables [monoid_with_zero M₀]
namespace units
/-- An element of the unit group of a nonzero monoid with zero represented as an element
of the monoid is nonzero. -/
@[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) :
(u : M₀) ≠ 0 :=
left_ne_zero_of_mul_eq_one u.mul_inv
-- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume
-- `nonzero M₀`.
@[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩
@[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩
end units
namespace is_unit
lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ := ha in hu ▸ u.ne_zero
lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 :=
let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero
lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 :=
let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero
end is_unit
/-- In a monoid with zero, if zero equals one, then zero is the only element. -/
lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 :=
by rw [← mul_one a, ← h, mul_zero]
/-- In a monoid with zero, if zero equals one, then zero is the unique element.
Somewhat arbitrarily, we define the default element to be `0`.
All other elements will be provably equal to it, but not necessarily definitionally equal. -/
def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ :=
{ default := 0, uniq := eq_zero_of_zero_eq_one h }
/-- In a monoid with zero, zero equals one if and only if all elements of that semiring are equal. -/
theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ :=
⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩
alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _
lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b :=
@subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b
@[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 :=
⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0,
λ h, @is_unit_of_subsingleton _ _ (subsingleton_of_zero_eq_one h) 0⟩
@[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) :=
mt is_unit_zero_iff.1 zero_ne_one
variable (M₀)
/-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/
lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) :=
not_or_of_imp eq_zero_of_zero_eq_one
end monoid_with_zero
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero M₀] {a b c : M₀}
@[priority 10] -- see Note [lower instance priority]
instance comm_cancel_monoid_with_zero.no_zero_divisors : no_zero_divisors M₀ :=
⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right,
apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩
lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel' hc, λ h, h ▸ rfl⟩
lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel' ha, λ h, h ▸ rfl⟩
@[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 :=
by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]]
@[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 :=
by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]]
/-- Pullback a `monoid_with_zero` class along an injective function. -/
protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
cancel_monoid_with_zero M₀' :=
{ mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel' ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel' ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
.. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel' ha $ h₂.symm ▸ (mul_one a).symm
/-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel' ha $ h₂.symm ▸ (one_mul a).symm
end cancel_monoid_with_zero
section group_with_zero
variables [group_with_zero G₀]
alias div_eq_mul_inv ← division_def
/-- Pullback a `group_with_zero` class along an injective function. -/
protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) :
group_with_zero G₀' :=
{ inv := has_inv.inv,
inv_zero := hf $ by erw [inv, zero, inv_zero],
mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)],
.. hf.monoid_with_zero f zero one mul,
.. pullback_nonzero f zero one }
/-- Pushforward a `group_with_zero` class along an surjective function. -/
protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] (h01 : (0:G₀') ≠ 1)
(f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) :
group_with_zero G₀' :=
{ inv := has_inv.inv,
inv_zero := by erw [← zero, ← inv, inv_zero],
mul_inv_cancel := hf.forall.2 $ λ x hx,
by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)];
exact one,
exists_pair_ne := ⟨0, 1, h01⟩,
.. hf.monoid_with_zero f zero one mul }
@[simp] lemma mul_inv_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) :
(a * b) * b⁻¹ = a :=
calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma mul_inv_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) :
a * (a⁻¹ * b) = b :=
calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
lemma inv_ne_zero {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 :=
assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h
@[simp] lemma inv_mul_cancel {a : G₀} (h : a ≠ 0) : a⁻¹ * a = 1 :=
calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h]
... = a⁻¹ * a⁻¹⁻¹ : by simp [h]
... = 1 : by simp [inv_ne_zero h]
@[simp] lemma inv_mul_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) :
(a * b⁻¹) * b = a :=
calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma inv_mul_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) :
a⁻¹ * (a * b) = b :=
calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
@[simp] lemma inv_one : 1⁻¹ = (1:G₀) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:G₀) : by simp
@[simp] lemma inv_inv' (a : G₀) : a⁻¹⁻¹ = a :=
begin
classical,
by_cases h : a = 0, { simp [h] },
calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h]
... = a : by simp [inv_ne_zero h]
end
/-- Multiplying `a` by itself and then by its inverse results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a :=
begin
classical,
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_assoc, mul_inv_cancel h, mul_one] }
end
/-- Multiplying `a` by its inverse and then by itself results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a :=
begin
classical,
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_inv_cancel h, one_mul] }
end
/-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a`
is zero). -/
@[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a :=
begin
classical,
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [inv_mul_cancel h, one_mul] }
end
/-- Multiplying `a` by itself and then dividing by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a :=
by rw [div_eq_mul_inv, mul_self_mul_inv a]
/-- Dividing `a` by itself and then multiplying by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a :=
by rw [div_eq_mul_inv, mul_inv_mul_self a]
lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) :=
inv_inv'
lemma eq_inv_of_mul_right_eq_one {a b : G₀} (h : a * b = 1) :
b = a⁻¹ :=
by rw [← inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b, h, mul_one]
lemma eq_inv_of_mul_left_eq_one {a b : G₀} (h : a * b = 1) :
a = b⁻¹ :=
by rw [← mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a, h, one_mul]
lemma inv_injective' : function.injective (@has_inv.inv G₀ _) :=
inv_involutive'.injective
@[simp] lemma inv_inj' {g h : G₀} : g⁻¹ = h⁻¹ ↔ g = h := inv_injective'.eq_iff
lemma inv_eq_iff {g h : G₀} : g⁻¹ = h ↔ h⁻¹ = g :=
by rw [← inv_inj', eq_comm, inv_inv']
@[simp] lemma inv_eq_one' {g : G₀} : g⁻¹ = 1 ↔ g = 1 :=
by rw [inv_eq_iff, inv_one, eq_comm]
end group_with_zero
namespace units
variables [group_with_zero G₀]
variables {a b : G₀}
/-- Embed a non-zero element of a `group_with_zero` into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl
@[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u :=
units.ext rfl
@[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ :=
eq_inv_of_mul_left_eq_one u.inv_mul
@[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero
@[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero
@[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
@[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 :=
⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩
end units
section group_with_zero
variables [group_with_zero G₀]
lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx)
lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 :=
units.exists_iff_ne_zero
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
begin
classical, contrapose! h,
exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero
end,
.. (‹_› : group_with_zero G₀) }
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ :=
{ mul_left_cancel_of_ne_zero := λ x y z hx h,
by rw [← inv_mul_cancel_left' hx y, h, inv_mul_cancel_left' hx z],
mul_right_cancel_of_ne_zero := λ x y z hy h,
by rw [← mul_inv_cancel_right' hy x, h, mul_inv_cancel_right' hy z],
.. (‹_› : group_with_zero G₀) }
lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
classical,
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
symmetry,
apply eq_inv_of_mul_left_eq_one,
simp [mul_assoc, hx, hy]
end
@[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 :=
by rw [div_eq_mul_inv, mul_inv_cancel h]
@[simp] lemma div_one (a : G₀) : a / 1 = a :=
by simp [div_eq_mul_inv a 1]
@[simp] lemma one_div (a : G₀) : 1 / a = a⁻¹ :=
by rw [div_eq_mul_inv, one_mul]
@[simp] lemma zero_div (a : G₀) : 0 / a = 0 :=
by rw [div_eq_mul_inv, zero_mul]
@[simp] lemma div_zero (a : G₀) : a / 0 = 0 :=
by rw [div_eq_mul_inv, inv_zero, mul_zero]
@[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a :=
by rw [div_eq_mul_inv, inv_mul_cancel_right' h a]
lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a)
@[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a :=
by rw [div_eq_mul_inv, mul_inv_cancel_right' h a]
lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a)
lemma mul_div_assoc {a b c : G₀} : a * b / c = a * (b / c) :=
by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _]
local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm
lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma one_div_one : 1 / 1 = (1:G₀) :=
div_self (ne.symm zero_ne_one)
lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 :=
by simpa only [one_div] using inv_ne_zero h
lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_right_eq_one h
lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_left_eq_one h
@[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a :=
by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv', div_eq_mul_inv]
lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a :=
by simp
lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div a, h, one_div_one_div]
variables {a b c : G₀}
@[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 :=
by rw [inv_eq_iff, inv_zero, eq_comm]
@[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a :=
eq_comm.trans $ inv_eq_zero.trans eq_comm
lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) :=
by simp only [div_eq_mul_inv, one_mul, mul_inv_rev']
theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u :=
by simpa only [div_eq_mul_inv] using congr_arg ((*) a) u.coe_inv'
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div : (a / b)⁻¹ = b / a :=
by rw [div_eq_mul_inv, mul_inv_rev', div_eq_mul_inv, inv_inv']
lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ :=
by rw [mul_inv_rev', div_eq_mul_inv]
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
by { rw div_eq_mul_inv, exact mul_ne_zero ha (inv_ne_zero hb) }
@[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:=
by simp [div_eq_mul_inv]
lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr div_eq_zero_iff).trans not_or_distrib
lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
by rw [eq_comm, div_eq_iff_mul_eq hc]
lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z :=
(div_eq_iff_mul_eq hx).2 h.symm
lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x :=
eq.symm $ div_eq_of_eq_mul hx h.symm
lemma eq_of_div_eq_one (h : a / b = 1) : a = b :=
begin
classical,
by_cases hb : b = 0,
{ rw [hb, div_zero] at h,
exact eq_of_zero_eq_one h a b },
{ rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h }
end
lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩
lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by simp only [div_eq_mul_inv, mul_inv_rev', mul_inv_cancel_left' hb, one_mul]
lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by simp only [div_eq_mul_inv, mul_inv_rev', mul_assoc, mul_inv_cancel_left' hc]
lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) :=
by simp [hb]
end group_with_zero
section comm_group_with_zero -- comm
variables [comm_group_with_zero G₀] {a b c : G₀}
@[priority 10] -- see Note [lower instance priority]
instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ :=
{ ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ }
/-- Pullback a `comm_group_with_zero` class along an injective function. -/
protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero f zero one mul inv, .. hf.comm_semigroup f mul }
/-- Pushforward a `comm_group_with_zero` class along an surjective function. -/
protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] (h01 : (0:G₀') ≠ 1)
(f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero h01 f zero one mul inv, .. hf.comm_semigroup f mul }
lemma mul_inv' : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev', mul_comm]
lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div_rev, mul_comm b]
lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
by rw [mul_comm, div_mul_left ha]
lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b :=
by rw [mul_comm, mul_div_cancel_of_imp h]
lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b :=
mul_div_cancel_left_of_imp $ λ h, (ha h).elim
lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a :=
by rw [mul_comm, div_mul_cancel_of_imp h]
lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div (a b c d : G₀) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by simp [div_eq_mul_inv, mul_inv']
lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc]
@[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c :=
by simp [div_eq_mul_inv]
lemma div_mul_eq_mul_div_comm (a b c : G₀) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul]
lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_div_eq_mul_div (a b c : G₀) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
@[field_simps] lemma div_div_eq_div_mul (a b c : G₀) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a : G₀) {b c d : G₀} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
lemma div_mul_eq_div_mul_one_div (a b c : G₀) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
/-- Dividing `a` by the result of dividing `a` by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_div_self (a : G₀) : a / (a / a) = a :=
begin
rw div_div_eq_mul_div,
exact mul_self_div_self a
end
lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, ((one_div_ne_zero ha) h).elim)
lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
end comm_group_with_zero
section comm_group_with_zero
variables [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_eq_inv_mul : a / b = b⁻¹ * a :=
by rw [div_eq_mul_inv, mul_comm]
lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b :=
by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc, div_eq_mul_inv]
lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b :=
by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm]
lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
@[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) :
by rw [mul_left_inj' (mul_ne_zero hb hd)]
... ↔ a * d = c * b :
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
@[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero
@[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha]
end comm_group_with_zero
namespace semiconj_by
@[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 :=
by simp only [semiconj_by, mul_zero, zero_mul]
@[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y :=
by simp only [semiconj_by, mul_zero, zero_mul]
variables [group_with_zero G₀] {a x y x' y' : G₀}
@[simp] lemma inv_symm_left_iff' : semiconj_by a⁻¹ x y ↔ semiconj_by a y x :=
classical.by_cases
(λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left])
(λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _)
lemma inv_symm_left' (h : semiconj_by a x y) : semiconj_by a⁻¹ y x :=
semiconj_by.inv_symm_left_iff'.2 h
lemma inv_right' (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ :=
begin
classical,
by_cases ha : a = 0,
{ simp only [ha, zero_left] },
by_cases hx : x = 0,
{ subst x,
simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h,
simp [h.resolve_right ha] },
{ have := mul_ne_zero ha hx,
rw [h.eq, mul_ne_zero_iff] at this,
exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h },
end
@[simp] lemma inv_right_iff' : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
⟨λ h, inv_inv' x ▸ inv_inv' y ▸ h.inv_right', inv_right'⟩
lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x / x') (y / y') :=
by { rw [div_eq_mul_inv, div_eq_mul_inv], exact h.mul_right h'.inv_right' }
end semiconj_by
namespace commute
@[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a
@[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a
variables [group_with_zero G₀] {a b c : G₀}
@[simp] theorem inv_left_iff' : commute a⁻¹ b ↔ commute a b :=
semiconj_by.inv_symm_left_iff'
theorem inv_left' (h : commute a b) : commute a⁻¹ b := inv_left_iff'.2 h
@[simp] theorem inv_right_iff' : commute a b⁻¹ ↔ commute a b :=
semiconj_by.inv_right_iff'
theorem inv_right' (h : commute a b) : commute a b⁻¹ := inv_right_iff'.2 h
theorem inv_inv' (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left'.inv_right'
@[simp] theorem div_right (hab : commute a b) (hac : commute a c) :
commute a (b / c) :=
hab.div_right hac
@[simp] theorem div_left (hac : commute a c) (hbc : commute b c) :
commute (a / b) c :=
by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left' }
end commute
namespace monoid_with_zero_hom
variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀]
section monoid_with_zero
variables (f : monoid_with_zero_hom G₀ M₀) {a : G₀}
lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 :=
⟨λ hfa ha, hfa $ ha.symm ▸ f.map_zero, λ ha, ((is_unit.mk0 a ha).map f.to_monoid_hom).ne_zero⟩
lemma map_eq_zero : f a = 0 ↔ a = 0 :=
by { classical, exact not_iff_not.1 f.map_ne_zero }
end monoid_with_zero
section group_with_zero
variables (f : monoid_with_zero_hom G₀ G₀') (a b : G₀)
/-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/
lemma map_inv' : f a⁻¹ = (f a)⁻¹ :=
begin
classical, by_cases h : a = 0, by simp [h],
apply eq_inv_of_mul_left_eq_one,
rw [← f.map_mul, inv_mul_cancel h, f.map_one]
end
lemma map_div : f (a / b) = f a / f b :=
by simpa only [div_eq_mul_inv] using ((f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv' b)
end group_with_zero
end monoid_with_zero_hom
@[simp] lemma monoid_hom.map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀]
(f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ :=
by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', monoid_hom.map_inv]
|
d6664bb335af5999e76a95a8041ad556f8cca919 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/polynomial/hermite/gaussian.lean | 307939d32d9fa8f3ecfa82c74bf6269d68f217df | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,559 | lean | /-
Copyright (c) 2023 Luke Mantle. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Mantle, Jake Levinson
-/
import ring_theory.polynomial.hermite.basic
import analysis.calculus.deriv.pow
import analysis.calculus.deriv.add
import analysis.special_functions.exp
import analysis.special_functions.exp_deriv
/-!
# Hermite polynomials and Gaussians
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file shows that the Hermite polynomial `hermite n` is (up to sign) the
polynomial factor occurring in the `n`th derivative of a gaussian.
## Results
* `polynomial.deriv_gaussian_eq_hermite_mul_gaussian`:
The Hermite polynomial is (up to sign) the polynomial factor occurring in the
`n`th derivative of a gaussian.
## References
* [Hermite Polynomials](https://en.wikipedia.org/wiki/Hermite_polynomials)
-/
noncomputable theory
open polynomial
namespace polynomial
/-- `hermite n` is (up to sign) the factor appearing in `deriv^[n]` of a gaussian -/
lemma deriv_gaussian_eq_hermite_mul_gaussian (n : ℕ) (x : ℝ) :
deriv^[n] (λ y, real.exp (-(y^2 / 2))) x =
(-1 : ℝ)^n * aeval x (hermite n) * real.exp (-(x^2 / 2)) :=
begin
rw mul_assoc,
induction n with n ih generalizing x,
{ rw [function.iterate_zero_apply, pow_zero, one_mul, hermite_zero, C_1, map_one, one_mul] },
{ replace ih : (deriv^[n] _) = _ := _root_.funext ih,
have deriv_gaussian : deriv (λ y, real.exp (-(y^2 / 2))) x = (-x) * real.exp (-(x^2 / 2)),
{ simp [mul_comm, ← neg_mul] },
rw [function.iterate_succ_apply', ih, deriv_const_mul_field, deriv_mul, pow_succ (-1 : ℝ),
deriv_gaussian, hermite_succ, map_sub, map_mul, aeval_X, polynomial.deriv_aeval],
ring,
{ apply polynomial.differentiable_aeval },
{ simp } }
end
lemma hermite_eq_deriv_gaussian (n : ℕ) (x : ℝ) :
aeval x (hermite n) =
(-1 : ℝ)^n * (deriv^[n] (λ y, real.exp (-(y^2 / 2))) x) / real.exp (-(x^2 / 2)) :=
begin
rw deriv_gaussian_eq_hermite_mul_gaussian,
field_simp [real.exp_ne_zero],
rw [← @smul_eq_mul ℝ _ ((-1)^n), ← inv_smul_eq_iff₀, mul_assoc, smul_eq_mul,
← inv_pow, ← neg_inv, inv_one],
exact pow_ne_zero _ (by norm_num),
end
lemma hermite_eq_deriv_gaussian' (n : ℕ) (x : ℝ) :
aeval x (hermite n) =
(-1 : ℝ)^n * (deriv^[n] (λ y, real.exp (-(y^2 / 2))) x) * real.exp (x^2 / 2) :=
begin
rw [hermite_eq_deriv_gaussian, real.exp_neg],
field_simp [real.exp_ne_zero],
end
end polynomial
|
f0bcc04277d69d1a3c1f9941fc3d339a326e0d19 | dc06cc9775d64d571bf4778459ec6fde1f344116 | /src/data/finsupp.lean | 0beea7962687a4fe6d3aa5692e6d1af25afbba1a | [
"Apache-2.0"
] | permissive | mgubi/mathlib | 8c1ea39035776ad52cf189a7af8cc0eee7dea373 | 7c09ed5eec8434176fbc493e0115555ccc4c8f99 | refs/heads/master | 1,642,222,572,514 | 1,563,782,424,000 | 1,563,782,424,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 62,351 | 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
Type of functions with finite support.
Functions with finite support provide the basis for the following concrete instances:
* ℕ →₀ α: Polynomials (where α is a ring)
* (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names)
* α →₀ ℕ: Multisets
* α →₀ ℤ: Abelian groups freely generated by α
* β →₀ α: Linear combinations over β where α is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm
@[extensionality]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨set.fintype_of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
def equiv_fun_on_fintype [fintype α] [decidable_eq β]: (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
section single
variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [finsupp.ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_swap {α β : Type*} [decidable_eq α] [decidable_eq β] [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp [unique.eq_default i]
end single
section on_finset
variables [decidable_eq β] [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s := filter_subset _
end on_finset
section map_range
variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
finsupp.ext $ λ a, by simp [hf]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
variables [decidable_eq α] [decidable_eq β₁]
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
section emb_domain
variables [has_zero β] [decidable_eq α₂]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported
function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f` it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp [h],
rw [← finsupp.not_mem_support_iff, classical.not_not],
apply finset.choose_mem },
{ simp [h] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (finsupp.not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂] [decidable_eq β₁] [decidable_eq β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
classical,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
[decidable_eq α₁] [decidable_eq α₂] [decidable_eq β]
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = finsupp.single a b) :
∃ x, l = finsupp.single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = finset.singleton a,
by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp [h_map_support],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← finsupp.emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp [h_cases.symm, hc₂] },
{ rw [finsupp.single_apply, finsupp.single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.inj (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin
haveI := classical.dec_eq β₁,
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
section erase
variables [decidable_eq α] [decidable_eq β]
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
end erase
-- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive finsupp.sum]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1
@[to_additive finsupp.sum_map_range_index]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive finsupp.sum_zero_index]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 := rfl
section decidable
variables [decidable_eq α] [decidable_eq β]
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a := rfl
end nat_sub
section add_monoid
variables [add_monoid β]
@[to_additive finsupp.sum_single_index]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [decidable_eq β₁] [decidable_eq β₂] [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive finsupp.sum_neg_index]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(finset.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive finsupp.sum_add_index]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive finsupp.sum_finset_sum_index]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive finsupp.sum_sum_index]
lemma prod_sum_index
[decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(finset.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(finset.sum_hom multiset.sum).symm
section map_range
variables
[decidable_eq β₁] [decidable_eq β₂] [add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
section map_domain
variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v := sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive finsupp.sum_map_domain_index]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
classical,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
section comap_domain
noncomputable def comap_domain {α₁ α₂ γ : Type*} [decidable_eq α₁] [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
lemma comap_domain_apply {α₁ α₂ γ : Type*} [decidable_eq α₁] [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
begin
unfold_coes,
unfold comap_domain,
simp,
refl
end
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [decidable_eq α₁] [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set):
(comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g :=
begin
unfold sum,
haveI := classical.dec_eq α₂,
simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*}
[add_comm_monoid γ] [decidable_eq α₁] [decidable_eq α₂] [decidable_eq γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) :
comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*}
[add_comm_monoid γ] [decidable_eq α₁] [decidable_eq α₂] [decidable_eq γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (set.inj_on_of_injective _ hf)) = l :=
begin
ext a,
haveI := classical.dec (a ∈ set.range f),
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl (finset.mem_coe.2 (mem_support_iff.2 (λ h, h_contr h.symm)))) }
end
end comap_domain
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
section filter
section has_zero
variables [has_zero β] (p : α → Prop) [decidable_pred p] (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h' h
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) [decidable_pred p] :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
section frange
variables [has_zero β]
def frange (f : α →₀ β) : finset β :=
finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive finsupp.sum_subtype_domain_index]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom [add_monoid β] :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, by by_cases p a; simp [h]
instance filter.is_add_monoid_hom (p : α → Prop) [decidable_pred p] :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(finset.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(finset.sum_hom _).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
def of_multiset [decidable_eq α] (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply [decidable_eq α] (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
def equiv_multiset [decidable_eq α] : (α →₀ ℕ) ≃ multiset α :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [decidable_eq α] [decidable_eq β] [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
section curry_uncurry
protected def curry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
protected def uncurry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
def finsupp_prod_equiv [add_comm_monoid γ] [decidable_eq α] [decidable_eq β] [decidable_eq γ] :
((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β]
(f : α₁ × α₂ →₀ β) (p : α₁ → Prop) [decidable_pred p] :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ _ _ p _ _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry
[decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.semiring }
instance [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.semiring }
instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [decidable_eq ι] [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..finsupp.semimodule α β }
instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) :=
{ ..finsupp.module α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
@[simp] lemma filter_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, by by_cases p a; simp [h]
end
lemma map_domain_smul {α'} [decidable_eq α'] {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, {simp},
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]]
end
@[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
end decidable
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp [eq_zero_of_zero_eq_one β zero_eq_one (l i)]
end
def restrict_support_equiv [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
(s : set α) [decidable_pred (λx, x ∈ s)] :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β) :=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
protected def dom_congr [decidable_eq α₁] [decidable_eq α₂] [decidable_eq β] [add_comm_monoid β]
(e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
section sigma
variables {αs : ι → Type*} [decidable_eq ι] [∀ i, decidable_eq (αs i)] [has_zero β] (l : (Σ i, αs i) →₀ β)
noncomputable def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
def split_support : finset ι := finset.image (sigma.fst) l.support
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
classical,
rw [split_support, mem_image, ne.def, ← support_eq_empty,
← exists_mem_iff_ne_empty, split, comap_domain],
simp
end
noncomputable def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw mem_split_support_iff_nonzero,
haveI := classical.dec,
rwa not_iff_not,
exact hg _ _,
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp [finset.ext, split_support, split, comap_domain]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) :=
by simp [sum, sigma_support, sum_sigma,split_apply]
end sigma
end finsupp
namespace multiset
variables [decidable_eq α]
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset := rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a := rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by simp [finsupp.single_apply, h] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
namespace finsupp
variables {σ : Type*} [decidable_eq σ]
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_comm_monoid α] [decidable_eq α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] [decidable_eq α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] [decidable_eq α] :
ordered_cancel_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa using congr_arg multiset.to_finsupp h },
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa using congr_arg to_multiset h },
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa [mem_antidiagonal_support, add_comm] using hf
end finsupp
|
8881780ccc0159fc2cafd8cde658f24b480e99e3 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/limits/preserves/filtered.lean | 6e015b1640b350794dce25d5202ee99b0362ecf6 | [
"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 | 2,667 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import category_theory.limits.preserves.basic
import category_theory.filtered
import category_theory.limits.types
/-!
# Preservation of filtered colimits and cofiltered limits.
Typically forgetful functors from algebraic categories preserve filtered colimits
(although not general colimits). See e.g. `algebra/category/Mon/filtered_colimits`.
-/
open category_theory
open category_theory.functor
namespace category_theory.limits
universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [category.{v} C]
variables {D : Type u₂} [category.{v} D]
variables {E : Type u₃} [category.{v} E]
variables {J : Type v} [small_category J] {K : J ⥤ C}
/--
A functor is said to preserve filtered colimits, if it preserves all colimits of shape `J`, where
`J` is a filtered category.
-/
class preserves_filtered_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(preserves_filtered_colimits : Π (J : Type v) [small_category J] [is_filtered J],
preserves_colimits_of_shape J F)
attribute [instance, priority 100] preserves_filtered_colimits.preserves_filtered_colimits
@[priority 100]
instance preserves_colimits.preserves_filtered_colimits (F : C ⥤ D) [preserves_colimits F] :
preserves_filtered_colimits F :=
{ preserves_filtered_colimits := infer_instance }
instance comp_preserves_filtered_colimits (F : C ⥤ D) (G : D ⥤ E)
[preserves_filtered_colimits F] [preserves_filtered_colimits G] :
preserves_filtered_colimits (F ⋙ G) :=
{ preserves_filtered_colimits := λ J _ _, by exactI infer_instance }
/--
A functor is said to preserve cofiltered limits, if it preserves all limits of shape `J`, where
`J` is a cofiltered category.
-/
class preserves_cofiltered_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(preserves_cofiltered_limits : Π (J : Type v) [small_category J] [is_cofiltered J],
preserves_limits_of_shape J F)
attribute [instance, priority 100] preserves_cofiltered_limits.preserves_cofiltered_limits
@[priority 100]
instance preserves_limits.preserves_cofiltered_limits (F : C ⥤ D) [preserves_limits F] :
preserves_cofiltered_limits F :=
{ preserves_cofiltered_limits := infer_instance }
instance comp_preserves_cofiltered_limits (F : C ⥤ D) (G : D ⥤ E)
[preserves_cofiltered_limits F] [preserves_cofiltered_limits G] :
preserves_cofiltered_limits (F ⋙ G) :=
{ preserves_cofiltered_limits := λ J _ _, by exactI infer_instance }
end category_theory.limits
|
e84e8e97b169fdea39b92eddb04c05c5f0baa70a | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/ns2.lean | d1d55132e206d666783b2739e994d2ec3fa8892a | [
"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 | 521 | lean | definition foo.id {A : Type} (a : A) := a
constant foo.T : Type.{1}
#check foo.id
#check foo.T
inductive foo.v.I | unit : foo.v.I
#check foo.v.I
#check foo.v.I.unit
namespace foo
#check id
#check T
#check v.I
end foo
namespace bla
definition vvv.pr {A : Type} (a b : A) := a
#check vvv.pr
end bla
#check bla.vvv.pr
namespace bla
namespace vvv
#check pr
inductive my.empty : Type
end vvv
end bla
#check bla.vvv.my.empty
namespace foo.bla
structure vvv.xyz := mk
end foo.bla
#check foo.bla.vvv.xyz.mk
|
157e2fdbec2ad25be5a9d5f66f53dedb9b687072 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/filter/archimedean_auto.lean | f0844c8542ddca236f2f66ce6ddac0f5b14ebdf9 | [] | 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,316 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.filter.at_top_bot
import Mathlib.algebra.archimedean
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# `at_top` filter and archimedean (semi)rings/fields
In this file we prove that for a linear ordered archimedean semiring `R` and a function `f : α → ℕ`,
the function `coe ∘ f : α → R` tends to `at_top` along a filter `l` if and only if so does `f`.
We also prove that `coe : ℕ → R` tends to `at_top` along `at_top`, as well as version of these
two results for `ℤ` (and a ring `R`) and `ℚ` (and a field `R`).
-/
theorem tendsto_coe_nat_at_top_iff {α : Type u_1} {R : Type u_2} [ordered_semiring R] [nontrivial R]
[archimedean R] {f : α → ℕ} {l : filter α} :
filter.tendsto (fun (n : α) => ↑(f n)) l filter.at_top ↔ filter.tendsto f l filter.at_top :=
filter.tendsto_at_top_embedding (fun (a₁ a₂ : ℕ) => nat.cast_le) exists_nat_ge
theorem tendsto_coe_nat_at_top_at_top {R : Type u_2} [ordered_semiring R] [archimedean R] :
filter.tendsto coe filter.at_top filter.at_top :=
monotone.tendsto_at_top_at_top nat.mono_cast exists_nat_ge
theorem tendsto_coe_int_at_top_iff {α : Type u_1} {R : Type u_2} [ordered_ring R] [nontrivial R]
[archimedean R] {f : α → ℤ} {l : filter α} :
filter.tendsto (fun (n : α) => ↑(f n)) l filter.at_top ↔ filter.tendsto f l filter.at_top :=
sorry
theorem tendsto_coe_int_at_top_at_top {R : Type u_2} [ordered_ring R] [archimedean R] :
filter.tendsto coe filter.at_top filter.at_top :=
sorry
theorem tendsto_coe_rat_at_top_iff {α : Type u_1} {R : Type u_2} [linear_ordered_field R]
[archimedean R] {f : α → ℚ} {l : filter α} :
filter.tendsto (fun (n : α) => ↑(f n)) l filter.at_top ↔ filter.tendsto f l filter.at_top :=
sorry
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `filter.tendsto.const_mul_at_top`). -/
theorem filter.tendsto.const_mul_at_top' {α : Type u_1} {R : Type u_2} [linear_ordered_semiring R]
[archimedean R] {l : filter α} {f : α → R} {r : R} (hr : 0 < r)
(hf : filter.tendsto f l filter.at_top) :
filter.tendsto (fun (x : α) => r * f x) l filter.at_top :=
sorry
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `filter.tendsto.at_top_mul_const`). -/
theorem filter.tendsto.at_top_mul_const' {α : Type u_1} {R : Type u_2} [linear_ordered_semiring R]
[archimedean R] {l : filter α} {f : α → R} {r : R} (hr : 0 < r)
(hf : filter.tendsto f l filter.at_top) :
filter.tendsto (fun (x : α) => f x * r) l filter.at_top :=
sorry
end Mathlib |
c60f295a1505670c584b82a3bef311e2f533fd34 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/set_theory/cardinal.lean | 2fd58ffa9f22c36fd0e70c9d4e6f64890bd3bb32 | [
"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 | 40,358 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Mario Carneiro
Cardinal arithmetic.
Cardinals are represented as quotient over equinumerous types.
-/
import data.set.countable data.quot logic.function set_theory.schroeder_bernstein
open function lattice set
local attribute [instance] classical.prop_decidable
universes u v w x
variables {α β : Type u}
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal of a type -/
def mk : Type u → cardinal := quotient.mk
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total }
noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
not_iff_comm.1
⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩,
λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : zero_ne_one_class cardinal.{u} :=
{ zero := 0, one := 1, zero_ne_one :=
ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ }
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a,
quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩)
section order_properties
open sum
theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩
theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 :=
by simp [le_antisymm_iff, zero_le]
theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 :=
by simp [lt_iff_le_and_ne, eq_comm, zero_le]
theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩
theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
add_le_add (le_refl _)
theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c :=
add_le_add h (le_refl _)
theorem le_add_right (a b : cardinal) : a ≤ a + b :=
by simpa using add_le_add_left a (zero_le b)
theorem le_add_left (a b : cardinal) : a ≤ b + a :=
by simpa using add_le_add_right a (zero_le b)
theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩
theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c :=
mul_le_mul (le_refl _)
theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c :=
mul_le_mul h (le_refl _)
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ↥-range f) ≃ β, from
(equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩
end order_properties
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := zero_le, ..cardinal.linear_order }
instance : canonically_ordered_monoid cardinal.{u} :=
{ add_le_add_left := λ a b h c, add_le_add_left _ h,
lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _),
le_iff_exists_add := @le_iff_exists_add,
..cardinal.lattice.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.injective_min _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.injective_min _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩),
cases classical.not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.inj h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨embedding.sigma_congr_right $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 :=
by { rw [←le_zero, sup_le], intro x, exfalso, exact h x }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
conv in (f _) {rw ← mk_out (f i)},
simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def],
exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩,
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, begin
have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf,
simp at this,
rw [← fintype.card_fin n, ← this],
exact finset.card_le_of_subset (finset.subset_univ _)
end,
λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h,
have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp] theorem nat_succ (n : ℕ) : succ n = n.succ :=
le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by simpa using nat_succ 0
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩
theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
classical.not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, ←nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- König's theorem -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, classical.not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩
@[simp] theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α :=
mk_le_of_injective subtype.val_injective
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.set.range f h).symm⟩
lemma mk_range_eq_of_inj {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨ set.embedding_of_subset h ⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
⟨⟨subtype.val, subtype.val_injective⟩⟩
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : α → Prop) (e : α ≃ β) :
mk {a : α // p a} = mk {b : β // p (e.symm b)} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype' e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact injective_comp h subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le }
end cardinal
|
73d6bff56aa3dd7b9f0f0885ec9effc52a12bdbf | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/analysis/specific_limits.lean | 91dbda02a6cf58429f89695f89139a865571d403 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 29,581 | 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
A collection of specific limit computations.
-/
import analysis.normed_space.basic
import algebra.geom_sum
import topology.instances.ennreal
import tactic.ring_exp
noncomputable theory
open_locale classical topological_space
open classical function filter finset metric
open_locale big_operators
variables {α : Type*} {β : Type*} {ι : Type*}
lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top :=
tendsto_abs_at_top_at_top
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_left'`). -/
lemma tendsto_at_top_mul_left [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ r * n, by rwa nsmul_eq_mul' at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)],
assume x hx,
calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ }
... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _)
... = r * (n * max b 0) : by rw [mul_assoc]
... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_right'`). -/
lemma tendsto_at_top_mul_right [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ (n : α) * r, by rwa nsmul_eq_mul at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)],
assume x hx,
calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ }
... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _)
... = (max b 0 * n) * r : by rw [mul_assoc]
... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_left` instead. -/
lemma tendsto_at_top_mul_left' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
filter_upwards [(tendsto_at_top _ _).1 hf (b/r)],
assume x hx,
simpa [div_le_iff' hr] using hx
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_right` instead. -/
lemma tendsto_at_top_mul_right' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf
/-- If a function tends to infinity along a filter, then this function divided by a positive
constant also tends to infinity. -/
lemma tendsto_at_top_div [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x / r) l at_top :=
tendsto_at_top_mul_right' (inv_pos.2 hr) hf
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λx:α, x⁻¹) (nhds_within (0 : α) (set.Ioi 0)) at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
refine mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(max b 1)⁻¹, by simp [zero_lt_one], λx hx, _⟩,
calc b ≤ max b 1 : le_max_left _ _
... ≤ x⁻¹ : begin
apply (le_inv _ hx.1).2 (le_of_lt hx.2),
exact lt_of_lt_of_le zero_lt_one (le_max_right _ _)
end
end
/-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/
lemma tendsto_inv_at_top_zero' [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λr:α, r⁻¹) at_top (nhds_within (0 : α) (set.Ioi 0)) :=
begin
assume s hs,
rw mem_nhds_within_Ioi_iff_exists_Ioc_subset at hs,
rcases hs with ⟨C, C0, hC⟩,
change 0 < C at C0,
refine filter.mem_map.2 (mem_sets_of_superset (mem_at_top C⁻¹) (λ x hx, hC _)),
have : 0 < x, from lt_of_lt_of_le (inv_pos.2 C0) hx,
exact ⟨inv_pos.2 this, (inv_le C0 this).1 hx⟩
end
lemma tendsto_inv_at_top_zero [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λr:α, r⁻¹) at_top (𝓝 0) :=
tendsto_le_right inf_le_left tendsto_inv_at_top_zero'
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero.comp (tendsto_coe_nat_real_at_top_iff.2 tendsto_id)
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : nnreal)⁻¹) at_top (𝓝 0) :=
by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp }
lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : nnreal) :
tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
/-! ### Powers -/
lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α}
(h : 0 < r) :
tendsto (λ n:ℕ, (r + 1)^n) at_top at_top :=
tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $
not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h
lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α]
{r : α} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h)
lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) :
tendsto (λn:ℕ, m ^ n) at_top at_top :=
begin
simp only [← nat.pow_eq_pow],
exact nat.sub_add_cancel (le_of_lt h) ▸
tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h)
end
lemma lim_norm_zero' {𝕜 : Type*} [normed_group 𝕜] :
tendsto (norm : 𝕜 → ℝ) (nhds_within 0 {x | x ≠ 0}) (nhds_within 0 (set.Ioi 0)) :=
lim_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx
lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] :
tendsto (λ x:𝕜, ∥x⁻¹∥) (nhds_within 0 {x | x ≠ 0}) at_top :=
(tendsto_inv_zero_at_top.comp lim_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
by_cases
(assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto_inv_at_top_zero.comp
(tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂),
tendsto.congr' (univ_mem_sets' $ by simp *) this)
lemma geom_lt {u : ℕ → ℝ} {k : ℝ} (hk : 0 < k) {n : ℕ} (h : ∀ m ≤ n, k*u m < u (m + 1)) :
k^(n + 1) *u 0 < u (n + 1) :=
begin
induction n with n ih,
{ simpa using h 0 (le_refl _) },
have : (∀ (m : ℕ), m ≤ n → k * u m < u (m + 1)),
intros m hm, apply h, exact nat.le_succ_of_le hm,
specialize ih this,
change k ^ (n + 2) * u 0 < u (n + 2),
replace h : k * u (n + 1) < u (n + 2) := h (n+1) (le_refl _),
calc k ^ (n + 2) * u 0 = k*(k ^ (n + 1) * u 0) : by ring_exp
... < k*(u (n + 1)) : mul_lt_mul_of_pos_left ih hk
... < u (n + 2) : h,
end
/-- If a sequence `v` of real numbers satisfies `k*v n < v (n+1)` with `1 < k`,
then it goes to +∞. -/
lemma tendsto_at_top_of_geom_lt {v : ℕ → ℝ} {k : ℝ} (h₀ : 0 < v 0) (hk : 1 < k)
(hu : ∀ n, k*v n < v (n+1)) : tendsto v at_top at_top :=
begin
apply tendsto_at_top_mono,
show ∀ n, k^n*v 0 ≤ v n,
{ intro n,
induction n with n ih,
{ simp },
calc
k ^ (n + 1) * v 0 = k*(k^n*v 0) : by ring_exp
... ≤ k*v n : mul_le_mul_of_nonneg_left ih (by linarith)
... ≤ v (n + 1) : le_of_lt (hu n) },
apply tendsto_at_top_mul_right h₀,
exact tendsto_pow_at_top_at_top_of_one_lt hk,
end
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
/-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/
lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R}
(h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) :=
begin
apply squeeze_zero_norm' (eventually_norm_pow_le x),
exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h,
end
lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
tendsto_pow_at_top_nhds_0_of_norm_lt_1 h
/-! ### Geometric series-/
section geometric
lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
have r ≠ 1, from ne_of_lt h₂,
have r + -1 ≠ 0,
by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩
lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric_of_lt_1 _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
has_sum_geometric_two.tsum_eq
lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 :=
begin
have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i,
{ intro i, apply pow_nonneg, norm_num },
convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two,
exact tsum_geometric_two.symm
end
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp, refl, },
{ norm_num }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a :=
(has_sum_geometric_two' a).tsum_eq
lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric_of_lt_1 r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(nnreal.has_sum_geometric hr).tsum_eq
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range]
... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) }
end
variables {K : Type*} [normed_field K] {ξ : K}
lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ :=
begin
have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] },
have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds,
have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl,
rw [has_sum_iff_tendsto_nat_of_summable_norm, B],
{ simpa [geom_sum, xi_ne_one, neg_inv] using A },
{ simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] }
end
lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) :=
⟨_, has_sum_geometric_of_norm_lt_1 h⟩
lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ :=
(has_sum_geometric_of_norm_lt_1 h).tsum_eq
lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
has_sum_geometric_of_norm_lt_1 h
lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) :=
summable_geometric_of_norm_lt_1 h
lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_1 h
end geometric
/-!
### Sequences with geometrically decaying distance in metric spaces
In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance
between two consecutive terms decays geometrically. We show that such sequences are Cauchy
sequences, and bound their distances to the limit. We also discuss series with geometrically
decaying terms.
-/
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.tsum_mul_left, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
have h0 : 0 ≤ C,
by simpa using le_trans dist_nonneg (hu 0),
rcases eq_or_lt_of_le h0 with rfl | Cpos,
{ simp [has_sum_zero] },
{ have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left
(by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos,
refine has_sum.mul_left C _,
by simpa using has_sum_geometric_of_lt_1 rnonneg hr }
end
variables (r C)
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(aux_has_sum_of_le_geometric hr hu).tsum_eq ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (this.mul_left _).tsum_eq.symm
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact ((has_sum_geometric_two' C).mul_right _).tsum_eq
end
end le_geometric
section summable_le_geometric
variables [normed_group α] {r C : ℝ} {f : ℕ → α}
lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) :
dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n :=
begin
rw [sum_range_succ, dist_eq_norm, ← norm_neg],
convert hf n,
rw [neg_sub, add_sub_cancel]
end
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) :
cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) :=
cauchy_seq_finset_of_norm_bounded _
(aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n)
{a : α} (ha : has_sum f a) (n : ℕ) :
∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) :=
begin
rw ← dist_eq_norm,
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf),
exact ha.tendsto_sum_nat
end
end summable_le_geometric
section normed_ring_geometric
variables {R : Type*} [normed_ring R] [complete_space R]
open normed_space
/-- A geometric series in a complete normed ring is summable.
Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/
lemma normed_ring.summable_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) :=
begin
have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h,
refine summable_of_norm_bounded_eventually _ h1 _,
rw nat.cofinite_eq_at_top,
exact eventually_norm_pow_le x,
end
lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) :
(∑' (i:ℕ), x ^ i) * (1 - x) = 1 :=
begin
have := has_sum_of_bounded_monoid_hom_of_summable
(normed_ring.summable_geometric_of_norm_lt_1 x h) (∥1 - x∥)
(mul_right_bound (1 - x)),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1),
{ simpa using tendsto_const_nhds.sub
(tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←geom_sum_mul_neg, geom_series_def, finset.sum_mul],
simp,
end
lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) :
(1 - x) * (∑' (i:ℕ), x ^ i) = 1 :=
begin
have := has_sum_of_bounded_monoid_hom_of_summable
(normed_ring.summable_geometric_of_norm_lt_1 x h) (∥1 - x∥)
(mul_left_bound (1 - x)),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1),
{ simpa using tendsto_const_nhds.sub
(tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←mul_neg_geom_sum, geom_series_def, finset.mul_sum],
simp,
end
end normed_ring_geometric
/-! ### Positive sequences with small sums on encodable types -/
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
/-!
### Harmonic series
Here we define the harmonic series and prove some basic lemmas about it,
leading to a proof of its divergence to +∞ -/
/-- The harmonic series `1 + 1/2 + 1/3 + ... + 1/n`-/
def harmonic_series (n : ℕ) : ℝ :=
∑ i in range n, 1/(i+1 : ℝ)
lemma mono_harmonic : monotone harmonic_series :=
begin
intros p q hpq,
apply sum_le_sum_of_subset_of_nonneg,
rwa range_subset,
intros x h _,
exact le_of_lt nat.one_div_pos_of_nat,
end
lemma half_le_harmonic_double_sub_harmonic (n : ℕ) (hn : 0 < n) :
1/2 ≤ harmonic_series (2*n) - harmonic_series n :=
begin
suffices : harmonic_series n + 1 / 2 ≤ harmonic_series (n + n),
{ rw two_mul,
linarith },
have : harmonic_series n + ∑ k in Ico n (n + n), 1/(k + 1 : ℝ) = harmonic_series (n + n) :=
sum_range_add_sum_Ico _ (show n ≤ n+n, by linarith),
rw [← this, add_le_add_iff_left],
have : ∑ k in Ico n (n + n), 1/(n+n : ℝ) = 1/2,
{ have : (n : ℝ) + n ≠ 0,
{ norm_cast, linarith },
rw [sum_const, Ico.card],
field_simp [this],
ring },
rw ← this,
apply sum_le_sum,
intros x hx,
rw one_div_le_one_div,
{ exact_mod_cast nat.succ_le_of_lt (Ico.mem.mp hx).2 },
{ norm_cast, linarith },
{ exact_mod_cast nat.zero_lt_succ x }
end
lemma self_div_two_le_harmonic_two_pow (n : ℕ) : (n / 2 : ℝ) ≤ harmonic_series (2^n) :=
begin
induction n with n hn,
unfold harmonic_series,
simp only [one_div_eq_inv, nat.cast_zero, euclidean_domain.zero_div, nat.cast_succ, sum_singleton,
inv_one, zero_add, nat.pow_zero, range_one, zero_le_one],
have : harmonic_series (2^n) + 1 / 2 ≤ harmonic_series (2^(n+1)),
{ have := half_le_harmonic_double_sub_harmonic (2^n) (by {apply nat.pow_pos, linarith}),
rw [nat.mul_comm, ← nat.pow_succ] at this,
linarith },
apply le_trans _ this,
rw (show (n.succ / 2 : ℝ) = (n/2 : ℝ) + (1/2), by field_simp),
linarith,
end
/-- The harmonic series diverges to +∞ -/
theorem harmonic_tendsto_at_top : tendsto harmonic_series at_top at_top :=
begin
suffices : tendsto (λ n : ℕ, harmonic_series (2^n)) at_top at_top, by
{ exact tendsto_at_top_of_monotone_of_subseq mono_harmonic this },
apply tendsto_at_top_mono self_div_two_le_harmonic_two_pow,
apply tendsto_at_top_div,
norm_num,
exact tendsto_coe_nat_real_at_top_at_top
end
|
50ec0fe78bf7617510fa783d8ef585917bf2087d | 534c92d7322a8676cfd1583e26f5946134561b54 | /src/Exercises/01_Propositions/Q0108/S0008.lean | 3d7f921a9f25550501011478b2262c3bfa6ce776 | [
"Apache-2.0"
] | permissive | kbuzzard/mathematics-in-lean | 53f387174f04d6077f434e27c407aee9425837f7 | 3fad7bb7e888dabef94921101af8671b78a4304a | refs/heads/master | 1,586,812,457,439 | 1,546,893,744,000 | 1,546,893,744,000 | 163,450,734 | 8 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 107 | lean | theorem not_not (P : Prop) : P → ¬ (¬ P) :=
begin
intro HP,
intro HnP,
apply HnP,
exact HP
end
|
353312e46d3e1818645b4e913327eacfb94a51a8 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.24.lean | 7eca1a513340b862e23e884d98abbc07f46ff3eb | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 557 | lean | import standard
example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
begin
apply iff.intro,
intro H,
apply (or.elim (and.elim_right H)),
intro Hq,
show (p ∧ q) ∨ (p ∧ r),
from or.inl (and.intro (and.elim_left H) Hq),
intro Hr,
show (p ∧ q) ∨ (p ∧ r),
from or.inr (and.intro (and.elim_left H) Hr),
intro H,
apply (or.elim H),
intro Hpq,
show p ∧ (q ∨ r), from
and.intro
(and.elim_left Hpq)
(or.inl (and.elim_right Hpq)),
intro Hpr,
show p ∧ (q ∨ r), from
and.intro
(and.elim_left Hpr)
(or.inr (and.elim_right Hpr))
end
|
e94f768b2e50ace7df68260e01a8b0c2978fff52 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/nonarchimedean/basic.lean | 1ee2fdc6957f250f30b29c74c3d02b7bf8d7ca75 | [
"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 | 5,851 | lean | /-
Copyright (c) 2021 Ashwin Iyengar. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Johan Commelin, Ashwin Iyengar, Patrick Massot
-/
import topology.algebra.ring
import topology.algebra.open_subgroup
import data.set.basic
import group_theory.subgroup.basic
/-!
# Nonarchimedean Topology
In this file we set up the theory of nonarchimedean topological groups and rings.
A nonarchimedean group is a topological group whose topology admits a basis of
open neighborhoods of the identity element in the group consisting of open subgroups.
A nonarchimedean ring is a topological ring whose underlying topological (additive)
group is nonarchimedean.
## Definitions
- `nonarchimedean_add_group`: nonarchimedean additive group.
- `nonarchimedean_group`: nonarchimedean multiplicative group.
- `nonarchimedean_ring`: nonarchimedean ring.
-/
open_locale pointwise
/-- An topological additive group is nonarchimedean if every neighborhood of 0
contains an open subgroup. -/
class nonarchimedean_add_group (G : Type*)
[add_group G] [topological_space G] extends topological_add_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U)
/-- A topological group is nonarchimedean if every neighborhood of 1 contains an open subgroup. -/
@[to_additive]
class nonarchimedean_group (G : Type*)
[group G] [topological_space G] extends topological_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U)
/-- An topological ring is nonarchimedean if its underlying topological additive
group is nonarchimedean. -/
class nonarchimedean_ring (R : Type*)
[ring R] [topological_space R] extends topological_ring R : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : R), ∃ V : open_add_subgroup R, (V : set R) ⊆ U)
/-- Every nonarchimedean ring is naturally a nonarchimedean additive group. -/
@[priority 100] -- see Note [lower instance priority]
instance nonarchimedean_ring.to_nonarchimedean_add_group
(R : Type*) [ring R] [topological_space R] [t: nonarchimedean_ring R] :
nonarchimedean_add_group R := {..t}
namespace nonarchimedean_group
variables {G : Type*} [group G] [topological_space G] [nonarchimedean_group G]
variables {H : Type*} [group H] [topological_space H] [topological_group H]
variables {K : Type*} [group K] [topological_space K] [nonarchimedean_group K]
/-- If a topological group embeds into a nonarchimedean group, then it
is nonarchimedean. -/
@[to_additive nonarchimedean_add_group.nonarchimedean_of_emb]
lemma nonarchimedean_of_emb (f : G →* H) (emb : open_embedding f) : nonarchimedean_group H :=
{ is_nonarchimedean := λ U hU, have h₁ : (f ⁻¹' U) ∈ nhds (1 : G), from
by {apply emb.continuous.tendsto, rwa f.map_one},
let ⟨V, hV⟩ := is_nonarchimedean (f ⁻¹' U) h₁ in
⟨{is_open' := emb.is_open_map _ V.is_open, ..subgroup.map f V},
set.image_subset_iff.2 hV⟩ }
/-- An open neighborhood of the identity in the cartesian product of two nonarchimedean groups
contains the cartesian product of an open neighborhood in each group. -/
@[to_additive nonarchimedean_add_group.prod_subset]
lemma prod_subset {U} (hU : U ∈ nhds (1 : G × K)) :
∃ (V : open_subgroup G) (W : open_subgroup K), (V : set G).prod (W : set K) ⊆ U :=
begin
erw [nhds_prod_eq, filter.mem_prod_iff] at hU,
rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩,
cases is_nonarchimedean _ hU₁ with V hV,
cases is_nonarchimedean _ hU₂ with W hW,
use V, use W,
rw set.prod_subset_iff,
intros x hX y hY,
exact set.subset.trans (set.prod_mono hV hW) h (set.mem_sep hX hY),
end
/-- An open neighborhood of the identity in the cartesian square of a nonarchimedean group
contains the cartesian square of an open neighborhood in the group. -/
@[to_additive nonarchimedean_add_group.prod_self_subset]
lemma prod_self_subset {U} (hU : U ∈ nhds (1 : G × G)) :
∃ (V : open_subgroup G), (V : set G).prod (V : set G) ⊆ U :=
let ⟨V, W, h⟩ := prod_subset hU in
⟨V ⊓ W, by {refine set.subset.trans (set.prod_mono _ _) ‹_›; simp}⟩
/-- The cartesian product of two nonarchimedean groups is nonarchimedean. -/
@[to_additive]
instance : nonarchimedean_group (G × K) :=
{ is_nonarchimedean := λ U hU, let ⟨V, W, h⟩ := prod_subset hU in ⟨V.prod W, ‹_›⟩ }
end nonarchimedean_group
namespace nonarchimedean_ring
open nonarchimedean_ring
open nonarchimedean_add_group
variables {R S : Type*}
variables [ring R] [topological_space R] [nonarchimedean_ring R]
variables [ring S] [topological_space S] [nonarchimedean_ring S]
/-- The cartesian product of two nonarchimedean rings is nonarchimedean. -/
instance : nonarchimedean_ring (R × S) :=
{ is_nonarchimedean := nonarchimedean_add_group.is_nonarchimedean }
/-- Given an open subgroup `U` and an element `r` of a nonarchimedean ring, there is an open
subgroup `V` such that `r • V` is contained in `U`. -/
lemma left_mul_subset (U : open_add_subgroup R) (r : R) :
∃ V : open_add_subgroup R, r • (V : set R) ⊆ U :=
⟨U.comap (add_monoid_hom.mul_left r) (continuous_mul_left r),
(U : set R).image_preimage_subset _⟩
/-- An open subgroup of a nonarchimedean ring contains the square of another one. -/
lemma mul_subset (U : open_add_subgroup R) :
∃ V : open_add_subgroup R, (V : set R) * V ⊆ U :=
let ⟨V, H⟩ := prod_self_subset (is_open.mem_nhds (is_open.preimage continuous_mul U.is_open)
begin
simpa only [set.mem_preimage, open_add_subgroup.mem_coe, prod.snd_zero, mul_zero]
using U.zero_mem,
end) in
begin
use V,
rintros v ⟨a, b, ha, hb, hv⟩,
have hy := H (set.mk_mem_prod ha hb),
simp only [set.mem_preimage, open_add_subgroup.mem_coe] at hy,
rwa hv at hy
end
end nonarchimedean_ring
|
8747ea7878b53cbf14ef167c4dd22fbc244909eb | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/normed_space/pi_Lp.lean | 12b33f1a0c6db831e4162870f637a12db7137e70 | [
"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 | 34,920 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Jireh Loreaux
-/
import analysis.mean_inequalities
import data.fintype.order
/-!
# `L^p` distance on finite products of metric spaces
Given finitely many metric spaces, one can put the max distance on their product, but there is also
a whole family of natural distances, indexed by a parameter `p : ℝ≥0∞`, that also induce
the product topology. We define them in this file. For `0 < p < ∞`, the distance on `Π i, α i`
is given by
$$
d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}.
$$,
whereas for `p = 0` it is the cardinality of the set ${ i | x_i ≠ y_i}$. For `p = ∞` the distance
is the supremum of the distances.
We give instances of this construction for emetric spaces, metric spaces, normed groups and normed
spaces.
To avoid conflicting instances, all these are defined on a copy of the original Π-type, named
`pi_Lp p α`. The assumpion `[fact (1 ≤ p)]` is required for the metric and normed space instances.
We ensure that the topology, bornology and uniform structure on `pi_Lp p α` are (defeq to) the
product topology, product bornology and product uniformity, to be able to use freely continuity
statements for the coordinate functions, for instance.
## Implementation notes
We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be
distinct. A closely related construction is `lp`, the `L^p` norm on a product of (possibly
infinitely many) normed spaces, where the norm is
$$
\left(\sum ‖f (x)‖^p \right)^{1/p}.
$$
However, the topology induced by this construction is not the product topology, and some functions
have infinite `L^p` norm. These subtleties are not present in the case of finitely many metric
spaces, hence it is worth devoting a file to this specific case which is particularly well behaved.
Another related construction is `measure_theory.Lp`, the `L^p` norm on the space of functions from
a measure space to a normed space, where the norm is
$$
\left(\int ‖f (x)‖^p dμ\right)^{1/p}.
$$
This has all the same subtleties as `lp`, and the further subtlety that this only
defines a seminorm (as almost everywhere zero functions have zero `L^p` norm).
The construction `pi_Lp` corresponds to the special case of `measure_theory.Lp` in which the basis
is a finite space equipped with the counting measure.
To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance
are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms
are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit
(easy) proof which provides a comparison between these two norms with explicit constants.
We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`.
-/
open real set filter is_R_or_C bornology
open_locale big_operators uniformity topological_space nnreal ennreal
noncomputable theory
/-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is
already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass
resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put
different distances. -/
@[nolint unused_arguments]
def pi_Lp (p : ℝ≥0∞) {ι : Type*} (α : ι → Type*) : Type* := Π (i : ι), α i
instance (p : ℝ≥0∞) {ι : Type*} (α : ι → Type*) [Π i, inhabited (α i)] : inhabited (pi_Lp p α) :=
⟨λ i, default⟩
namespace pi_Lp
variables (p : ℝ≥0∞) (𝕜 : Type*) {ι : Type*} (α : ι → Type*) (β : ι → Type*)
/-- Canonical bijection between `pi_Lp p α` and the original Pi type. We introduce it to be able
to compare the `L^p` and `L^∞` distances through it. -/
protected def equiv : pi_Lp p α ≃ Π (i : ι), α i :=
equiv.refl _
/-! Note that the unapplied versions of these lemmas are deliberately omitted, as they break
the use of the type synonym. -/
@[simp] lemma equiv_apply (x : pi_Lp p α) (i : ι) : pi_Lp.equiv p α x i = x i := rfl
@[simp] lemma equiv_symm_apply (x : Π i, α i) (i : ι) : (pi_Lp.equiv p α).symm x i = x i := rfl
section dist_norm
variables [fintype ι]
/-!
### Definition of `edist`, `dist` and `norm` on `pi_Lp`
In this section we define the `edist`, `dist` and `norm` functions on `pi_Lp p α` without assuming
`[fact (1 ≤ p)]` or metric properties of the spaces `α i`. This allows us to provide the rewrite
lemmas for each of three cases `p = 0`, `p = ∞` and `0 < p.to_real`.
-/
section edist
variables [Π i, has_edist (β i)]
/-- Endowing the space `pi_Lp p β` with the `L^p` edistance. We register this instance
separate from `pi_Lp.pseudo_emetric` since the latter requires the type class hypothesis
`[fact (1 ≤ p)]` in order to prove the triangle inequality.
Registering this separately allows for a future emetric-like structure on `pi_Lp p β` for `p < 1`
satisfying a relaxed triangle inequality. The terminology for this varies throughout the
literature, but it is sometimes called a *quasi-metric* or *semi-metric*. -/
instance : has_edist (pi_Lp p β) :=
{ edist := λ f g, if hp : p = 0 then {i | f i ≠ g i}.to_finite.to_finset.card
else (if p = ∞ then ⨆ i, edist (f i) (g i)
else (∑ i, (edist (f i) (g i) ^ p.to_real)) ^ (1/p.to_real)) }
variable {β}
lemma edist_eq_card (f g : pi_Lp 0 β) : edist f g = {i | f i ≠ g i}.to_finite.to_finset.card :=
if_pos rfl
lemma edist_eq_sum {p : ℝ≥0∞} (hp : 0 < p.to_real) (f g : pi_Lp p β) :
edist f g = (∑ i, edist (f i) (g i) ^ p.to_real) ^ (1/p.to_real) :=
let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne)
lemma edist_eq_supr (f g : pi_Lp ∞ β) : edist f g = ⨆ i, edist (f i) (g i) :=
by { dsimp [edist], exact if_neg ennreal.top_ne_zero }
end edist
section edist_prop
variables {β} [Π i, pseudo_emetric_space (β i)]
/-- This holds independent of `p` and does not require `[fact (1 ≤ p)]`. We keep it separate
from `pi_Lp.pseudo_emetric_space` so it can be used also for `p < 1`. -/
protected lemma edist_self (f : pi_Lp p β) : edist f f = 0 :=
begin
rcases p.trichotomy with (rfl | rfl | h),
{ simp [edist_eq_card], },
{ simp [edist_eq_supr], },
{ simp [edist_eq_sum h, ennreal.zero_rpow_of_pos h, ennreal.zero_rpow_of_pos (inv_pos.2 $ h)]}
end
/-- This holds independent of `p` and does not require `[fact (1 ≤ p)]`. We keep it separate
from `pi_Lp.pseudo_emetric_space` so it can be used also for `p < 1`. -/
protected lemma edist_comm (f g : pi_Lp p β) : edist f g = edist g f :=
begin
rcases p.trichotomy with (rfl | rfl | h),
{ simp only [edist_eq_card, eq_comm, ne.def] },
{ simp only [edist_eq_supr, edist_comm] },
{ simp only [edist_eq_sum h, edist_comm] }
end
end edist_prop
section dist
variables [Π i, has_dist (α i)]
/-- Endowing the space `pi_Lp p β` with the `L^p` distance. We register this instance
separate from `pi_Lp.pseudo_metric` since the latter requires the type class hypothesis
`[fact (1 ≤ p)]` in order to prove the triangle inequality.
Registering this separately allows for a future metric-like structure on `pi_Lp p β` for `p < 1`
satisfying a relaxed triangle inequality. The terminology for this varies throughout the
literature, but it is sometimes called a *quasi-metric* or *semi-metric*. -/
instance : has_dist (pi_Lp p α) :=
{ dist := λ f g, if hp : p = 0 then {i | f i ≠ g i}.to_finite.to_finset.card
else (if p = ∞ then ⨆ i, dist (f i) (g i)
else (∑ i, (dist (f i) (g i) ^ p.to_real)) ^ (1/p.to_real)) }
variable {α}
lemma dist_eq_card (f g : pi_Lp 0 α) : dist f g = {i | f i ≠ g i}.to_finite.to_finset.card :=
if_pos rfl
lemma dist_eq_sum {p : ℝ≥0∞} (hp : 0 < p.to_real) (f g : pi_Lp p α) :
dist f g = (∑ i, dist (f i) (g i) ^ p.to_real) ^ (1/p.to_real) :=
let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne)
lemma dist_eq_csupr (f g : pi_Lp ∞ α) : dist f g = ⨆ i, dist (f i) (g i) :=
by { dsimp [dist], exact if_neg ennreal.top_ne_zero }
end dist
section norm
variables [Π i, has_norm (β i)] [Π i, has_zero (β i)]
/-- Endowing the space `pi_Lp p β` with the `L^p` norm. We register this instance
separate from `pi_Lp.seminormed_add_comm_group` since the latter requires the type class hypothesis
`[fact (1 ≤ p)]` in order to prove the triangle inequality.
Registering this separately allows for a future norm-like structure on `pi_Lp p β` for `p < 1`
satisfying a relaxed triangle inequality. These are called *quasi-norms*. -/
instance has_norm : has_norm (pi_Lp p β) :=
{ norm := λ f, if hp : p = 0 then {i | f i ≠ 0}.to_finite.to_finset.card
else (if p = ∞ then ⨆ i, ‖f i‖ else (∑ i, ‖f i‖ ^ p.to_real) ^ (1 / p.to_real)) }
variables {p β}
lemma norm_eq_card (f : pi_Lp 0 β) : ‖f‖ = {i | f i ≠ 0}.to_finite.to_finset.card :=
if_pos rfl
lemma norm_eq_csupr (f : pi_Lp ∞ β) : ‖f‖ = ⨆ i, ‖f i‖ :=
by { dsimp [norm], exact if_neg ennreal.top_ne_zero }
lemma norm_eq_sum (hp : 0 < p.to_real) (f : pi_Lp p β) :
‖f‖ = (∑ i, ‖f i‖ ^ p.to_real) ^ (1 / p.to_real) :=
let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne)
end norm
end dist_norm
section aux
/-!
### The uniformity on finite `L^p` products is the product uniformity
In this section, we put the `L^p` edistance on `pi_Lp p α`, and we check that the uniformity
coming from this edistance coincides with the product uniformity, by showing that the canonical
map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and
antiLipschitz.
We only register this emetric space structure as a temporary instance, as the true instance (to be
registered later) will have as uniformity exactly the product uniformity, instead of the one coming
from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance]
explaining why having definitionally the right uniformity is often important.
-/
variables [fact (1 ≤ p)] [Π i, pseudo_metric_space (α i)] [Π i, pseudo_emetric_space (β i)]
variables [fintype ι]
/-- Endowing the space `pi_Lp p β` with the `L^p` pseudoemetric structure. This definition is not
satisfactory, as it does not register the fact that the topology and the uniform structure coincide
with the product one. Therefore, we do not register it as an instance. Using this as a temporary
pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to
the product one, and then register an instance in which we replace the uniform structure by the
product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/
def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p β) :=
{ edist_self := pi_Lp.edist_self p,
edist_comm := pi_Lp.edist_comm p,
edist_triangle := λ f g h,
begin
unfreezingI { rcases p.dichotomy with (rfl | hp) },
{ simp only [edist_eq_supr],
casesI is_empty_or_nonempty ι,
{ simp only [csupr_of_empty, ennreal.bot_eq_zero, add_zero, nonpos_iff_eq_zero] },
exact supr_le (λ i, (edist_triangle _ (g i) _).trans $
add_le_add (le_supr _ i) (le_supr _ i))},
{ simp only [edist_eq_sum (zero_lt_one.trans_le hp)],
calc (∑ i, edist (f i) (h i) ^ p.to_real) ^ (1 / p.to_real) ≤
(∑ i, (edist (f i) (g i) + edist (g i) (h i)) ^ p.to_real) ^ (1 / p.to_real) :
begin
apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ zero_le_one.trans hp),
refine finset.sum_le_sum (λ i hi, _),
exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (zero_le_one.trans hp),
end
... ≤ (∑ i, edist (f i) (g i) ^ p.to_real) ^ (1 / p.to_real)
+ (∑ i, edist (g i) (h i) ^ p.to_real) ^ (1 / p.to_real) : ennreal.Lp_add_le _ _ _ hp },
end }
local attribute [instance] pi_Lp.pseudo_emetric_aux
/-- An auxiliary lemma used twice in the proof of `pi_Lp.pseudo_metric_aux` below. Not intended for
use outside this file. -/
lemma supr_edist_ne_top_aux {ι : Type*} [finite ι] {α : ι → Type*} [Π i, pseudo_metric_space (α i)]
(f g : pi_Lp ∞ α) : (⨆ i, edist (f i) (g i)) ≠ ⊤ :=
begin
casesI nonempty_fintype ι,
obtain ⟨M, hM⟩ := fintype.exists_le (λ i, (⟨dist (f i) (g i), dist_nonneg⟩ : ℝ≥0)),
refine ne_of_lt ((supr_le $ λ i, _).trans_lt (@ennreal.coe_lt_top M)),
simp only [edist, pseudo_metric_space.edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg],
exact_mod_cast hM i,
end
/-- Endowing the space `pi_Lp p α` with the `L^p` pseudometric structure. This definition is not
satisfactory, as it does not register the fact that the topology, the uniform structure, and the
bornology coincide with the product ones. Therefore, we do not register it as an instance. Using
this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal
(but not defeq) to the product one, and then register an instance in which we replace the uniform
structure and the bornology by the product ones using this pseudometric space,
`pseudo_metric_space.replace_uniformity`, and `pseudo_metric_space.replace_bornology`.
See note [reducible non-instances] -/
@[reducible] def pseudo_metric_aux : pseudo_metric_space (pi_Lp p α) :=
pseudo_emetric_space.to_pseudo_metric_space_of_dist dist
(λ f g,
begin
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ exact supr_edist_ne_top_aux f g },
{ rw edist_eq_sum (zero_lt_one.trans_le h),
exact ennreal.rpow_ne_top_of_nonneg (one_div_nonneg.2 (zero_le_one.trans h)) (ne_of_lt $
(ennreal.sum_lt_top $ λ i hi, ennreal.rpow_ne_top_of_nonneg (zero_le_one.trans h)
(edist_ne_top _ _)))}
end)
(λ f g,
begin
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ rw [edist_eq_supr, dist_eq_csupr],
{ casesI is_empty_or_nonempty ι,
{ simp only [real.csupr_empty, csupr_of_empty, ennreal.bot_eq_zero, ennreal.zero_to_real] },
{ refine le_antisymm (csupr_le $ λ i, _) _,
{ rw [←ennreal.of_real_le_iff_le_to_real (supr_edist_ne_top_aux f g),
←pseudo_metric_space.edist_dist],
exact le_supr _ i, },
{ refine ennreal.to_real_le_of_le_of_real (real.Sup_nonneg _ _) (supr_le $ λ i, _),
{ rintro - ⟨i, rfl⟩,
exact dist_nonneg, },
{ unfold edist, rw pseudo_metric_space.edist_dist,
exact ennreal.of_real_le_of_real (le_csupr (fintype.bdd_above_range _) i), } } } } },
{ have A : ∀ i, edist (f i) (g i) ^ p.to_real ≠ ⊤,
from λ i, ennreal.rpow_ne_top_of_nonneg (zero_le_one.trans h) (edist_ne_top _ _),
simp only [edist_eq_sum (zero_lt_one.trans_le h), dist_edist, ennreal.to_real_rpow,
dist_eq_sum (zero_lt_one.trans_le h), ← ennreal.to_real_sum (λ i _, A i)] }
end)
local attribute [instance] pi_Lp.pseudo_metric_aux
lemma lipschitz_with_equiv_aux : lipschitz_with 1 (pi_Lp.equiv p β) :=
begin
intros x y,
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ simpa only [ennreal.coe_one, one_mul, edist_eq_supr, edist, finset.sup_le_iff,
finset.mem_univ, forall_true_left] using le_supr (λ i, edist (x i) (y i)), },
{ have cancel : p.to_real * (1/p.to_real) = 1 := mul_div_cancel' 1 (zero_lt_one.trans_le h).ne',
rw edist_eq_sum (zero_lt_one.trans_le h),
simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff,
ennreal.coe_one],
assume i,
calc
edist (x i) (y i) = (edist (x i) (y i) ^ p.to_real) ^ (1/p.to_real) :
by simp [← ennreal.rpow_mul, cancel, -one_div]
... ≤ (∑ i, edist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) :
begin
apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ (zero_le_one.trans h)),
exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i)
end }
end
lemma antilipschitz_with_equiv_aux :
antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1 / p).to_real) (pi_Lp.equiv p β) :=
begin
intros x y,
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ simp only [edist_eq_supr, ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero,
ennreal.coe_one, one_mul, supr_le_iff],
exact λ i, finset.le_sup (finset.mem_univ i), },
{ have pos : 0 < p.to_real := zero_lt_one.trans_le h,
have nonneg : 0 ≤ 1 / p.to_real := one_div_nonneg.2 (le_of_lt pos),
have cancel : p.to_real * (1/p.to_real) = 1 := mul_div_cancel' 1 (ne_of_gt pos),
rw [edist_eq_sum pos, ennreal.to_real_div 1 p],
simp only [edist, ←one_div, ennreal.one_to_real],
calc (∑ i, edist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) ≤
(∑ i, edist (pi_Lp.equiv p β x) (pi_Lp.equiv p β y) ^ p.to_real) ^ (1 / p.to_real) :
begin
apply ennreal.rpow_le_rpow _ nonneg,
apply finset.sum_le_sum (λ i hi, _),
apply ennreal.rpow_le_rpow _ (le_of_lt pos),
exact finset.le_sup (finset.mem_univ i)
end
... = (((fintype.card ι : ℝ≥0)) ^ (1 / p.to_real) : ℝ≥0) *
edist (pi_Lp.equiv p β x) (pi_Lp.equiv p β y) :
begin
simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const,
ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel],
have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) :=
(ennreal.coe_nat (fintype.card ι)).symm,
rw [this, ennreal.coe_rpow_of_nonneg _ nonneg]
end }
end
lemma aux_uniformity_eq :
𝓤 (pi_Lp p β) = @uniformity _ (Pi.uniform_space _) :=
begin
have A : uniform_inducing (pi_Lp.equiv p β) :=
(antilipschitz_with_equiv_aux p β).uniform_inducing
(lipschitz_with_equiv_aux p β).uniform_continuous,
have : (λ (x : pi_Lp p β × pi_Lp p β),
((pi_Lp.equiv p β) x.fst, (pi_Lp.equiv p β) x.snd)) = id,
by ext i; refl,
rw [← A.comap_uniformity, this, comap_id]
end
lemma aux_cobounded_eq :
cobounded (pi_Lp p α) = @cobounded _ pi.bornology :=
calc cobounded (pi_Lp p α) = comap (pi_Lp.equiv p α) (cobounded _) :
le_antisymm (antilipschitz_with_equiv_aux p α).tendsto_cobounded.le_comap
(lipschitz_with_equiv_aux p α).comap_cobounded_le
... = _ : comap_id
end aux
/-! ### Instances on finite `L^p` products -/
instance uniform_space [Π i, uniform_space (β i)] : uniform_space (pi_Lp p β) :=
Pi.uniform_space _
variable [fintype ι]
instance bornology [Π i, bornology (β i)] : bornology (pi_Lp p β) := pi.bornology
-- throughout the rest of the file, we assume `1 ≤ p`
variables [fact (1 ≤ p)]
/-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the
`L^p` pseudoedistance, and having as uniformity the product uniformity. -/
instance [Π i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p β) :=
(pseudo_emetric_aux p β).replace_uniformity (aux_uniformity_eq p β).symm
/-- emetric space instance on the product of finitely many emetric spaces, using the `L^p`
edistance, and having as uniformity the product uniformity. -/
instance [Π i, emetric_space (α i)] : emetric_space (pi_Lp p α) :=
@emetric.of_t0_pseudo_emetric_space (pi_Lp p α) _ pi.t0_space
/-- pseudometric space instance on the product of finitely many psuedometric spaces, using the
`L^p` distance, and having as uniformity the product uniformity. -/
instance [Π i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p β) :=
((pseudo_metric_aux p β).replace_uniformity (aux_uniformity_eq p β).symm).replace_bornology $
λ s, filter.ext_iff.1 (aux_cobounded_eq p β).symm sᶜ
/-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance,
and having as uniformity the product uniformity. -/
instance [Π i, metric_space (α i)] : metric_space (pi_Lp p α) :=
metric.of_t0_pseudo_metric_space _
lemma nndist_eq_sum {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*}
[Π i, pseudo_metric_space (β i)] (hp : p ≠ ∞) (x y : pi_Lp p β) :
nndist x y = (∑ i : ι, nndist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) :=
subtype.ext $ by { push_cast, exact dist_eq_sum (p.to_real_pos_iff_ne_top.mpr hp) _ _ }
lemma nndist_eq_supr {β : ι → Type*} [Π i, pseudo_metric_space (β i)] (x y : pi_Lp ∞ β) :
nndist x y = ⨆ i, nndist (x i) (y i) :=
subtype.ext $ by { push_cast, exact dist_eq_csupr _ _ }
lemma lipschitz_with_equiv [Π i, pseudo_emetric_space (β i)] :
lipschitz_with 1 (pi_Lp.equiv p β) :=
lipschitz_with_equiv_aux p β
lemma antilipschitz_with_equiv [Π i, pseudo_emetric_space (β i)] :
antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1 / p).to_real) (pi_Lp.equiv p β) :=
antilipschitz_with_equiv_aux p β
lemma infty_equiv_isometry [Π i, pseudo_emetric_space (β i)] :
isometry (pi_Lp.equiv ∞ β) :=
λ x y, le_antisymm (by simpa only [ennreal.coe_one, one_mul] using lipschitz_with_equiv ∞ β x y)
(by simpa only [ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero, ennreal.coe_one, one_mul]
using antilipschitz_with_equiv ∞ β x y)
variables (p β)
/-- seminormed group instance on the product of finitely many normed groups, using the `L^p`
norm. -/
instance seminormed_add_comm_group [Π i, seminormed_add_comm_group (β i)] :
seminormed_add_comm_group (pi_Lp p β) :=
{ dist_eq := λ x y,
begin
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ simpa only [dist_eq_csupr, norm_eq_csupr, dist_eq_norm] },
{ have : p ≠ ∞, { intros hp, rw [hp, ennreal.top_to_real] at h, linarith,} ,
simpa only [dist_eq_sum (zero_lt_one.trans_le h), norm_eq_sum (zero_lt_one.trans_le h),
dist_eq_norm], }
end,
.. pi.add_comm_group, }
/-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/
instance normed_add_comm_group [Π i, normed_add_comm_group (α i)] :
normed_add_comm_group (pi_Lp p α) :=
{ ..pi_Lp.seminormed_add_comm_group p α }
lemma nnnorm_eq_sum {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*} (hp : p ≠ ∞)
[Π i, seminormed_add_comm_group (β i)] (f : pi_Lp p β) :
‖f‖₊ = (∑ i, ‖f i‖₊ ^ p.to_real) ^ (1 / p.to_real) :=
by { ext, simp [nnreal.coe_sum, norm_eq_sum (p.to_real_pos_iff_ne_top.mpr hp)] }
lemma nnnorm_eq_csupr {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (f : pi_Lp ∞ β) :
‖f‖₊ = ⨆ i, ‖f i‖₊ :=
by { ext, simp [nnreal.coe_supr, norm_eq_csupr] }
lemma norm_eq_of_nat {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*}
[Π i, seminormed_add_comm_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p β) :
‖f‖ = (∑ i, ‖f i‖ ^ n) ^ (1/(n : ℝ)) :=
begin
have := p.to_real_pos_iff_ne_top.mpr (ne_of_eq_of_ne h $ ennreal.nat_ne_top n),
simp only [one_div, h, real.rpow_nat_cast, ennreal.to_real_nat, eq_self_iff_true,
finset.sum_congr, norm_eq_sum this],
end
lemma norm_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) :
‖x‖ = sqrt (∑ (i : ι), ‖x i‖ ^ 2) :=
by { convert norm_eq_of_nat 2 (by norm_cast) _, rw sqrt_eq_rpow, norm_cast }
lemma nnnorm_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) :
‖x‖₊ = nnreal.sqrt (∑ (i : ι), ‖x i‖₊ ^ 2) :=
subtype.ext $ by { push_cast, exact norm_eq_of_L2 x }
lemma norm_sq_eq_of_L2 (β : ι → Type*) [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) :
‖x‖ ^ 2 = ∑ (i : ι), ‖x i‖ ^ 2 :=
begin
suffices : ‖x‖₊ ^ 2 = ∑ (i : ι), ‖x i‖₊ ^ 2,
{ simpa only [nnreal.coe_sum] using congr_arg (coe : ℝ≥0 → ℝ) this },
rw [nnnorm_eq_of_L2, nnreal.sq_sqrt],
end
lemma dist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) :
dist x y = (∑ i, dist (x i) (y i) ^ 2).sqrt :=
by simp_rw [dist_eq_norm, norm_eq_of_L2, pi.sub_apply]
lemma nndist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) :
nndist x y = (∑ i, nndist (x i) (y i) ^ 2).sqrt :=
subtype.ext $ by { push_cast, exact dist_eq_of_L2 _ _ }
lemma edist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) :
edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) :=
by simp [pi_Lp.edist_eq_sum]
variables [normed_field 𝕜]
/-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/
instance normed_space [Π i, seminormed_add_comm_group (β i)]
[Π i, normed_space 𝕜 (β i)] : normed_space 𝕜 (pi_Lp p β) :=
{ norm_smul_le := λ c f,
begin
unfreezingI { rcases p.dichotomy with (rfl | hp) },
{ letI : module 𝕜 (pi_Lp ∞ β) := pi.module ι β 𝕜,
suffices : ‖c • f‖₊ = ‖c‖₊ * ‖f‖₊, { exact_mod_cast nnreal.coe_mono this.le },
simpa only [nnnorm_eq_csupr, nnreal.mul_supr, ←nnnorm_smul] },
{ have : p.to_real * (1 / p.to_real) = 1 := mul_div_cancel' 1 (zero_lt_one.trans_le hp).ne',
simp only [norm_eq_sum (zero_lt_one.trans_le hp), norm_smul, mul_rpow, norm_nonneg,
←finset.mul_sum, pi.smul_apply],
rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _),
this, rpow_one],
exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) },
end,
.. (pi.module ι β 𝕜) }
instance finite_dimensional [Π i, seminormed_add_comm_group (β i)]
[Π i, normed_space 𝕜 (β i)] [I : ∀ i, finite_dimensional 𝕜 (β i)] :
finite_dimensional 𝕜 (pi_Lp p β) :=
finite_dimensional.finite_dimensional_pi' _ _
/- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas
for Pi types will not trigger. -/
variables {𝕜 p α} [Π i, seminormed_add_comm_group (β i)] [Π i, normed_space 𝕜 (β i)] (c : 𝕜)
variables (x y : pi_Lp p β) (x' y' : Π i, β i) (i : ι)
@[simp] lemma zero_apply : (0 : pi_Lp p β) i = 0 := rfl
@[simp] lemma add_apply : (x + y) i = x i + y i := rfl
@[simp] lemma sub_apply : (x - y) i = x i - y i := rfl
@[simp] lemma smul_apply : (c • x) i = c • x i := rfl
@[simp] lemma neg_apply : (-x) i = - (x i) := rfl
/-- The canonical map `pi_Lp.equiv` between `pi_Lp ∞ β` and `Π i, β i` as a linear isometric
equivalence. -/
def equivₗᵢ : pi_Lp ∞ β ≃ₗᵢ[𝕜] Π i, β i :=
{ map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
norm_map' := λ f,
begin
suffices : finset.univ.sup (λ i, ‖f i‖₊) = ⨆ i, ‖f i‖₊,
{ simpa only [nnreal.coe_supr] using congr_arg (coe : ℝ≥0 → ℝ) this },
refine antisymm (finset.sup_le (λ i _, le_csupr (fintype.bdd_above_range (λ i, ‖f i‖₊)) _)) _,
casesI is_empty_or_nonempty ι,
{ simp only [csupr_of_empty, finset.univ_eq_empty, finset.sup_empty], },
{ exact csupr_le (λ i, finset.le_sup (finset.mem_univ i)) },
end,
.. pi_Lp.equiv ∞ β }
variables {ι' : Type*}
variables [fintype ι']
variables (p 𝕜) (E : Type*) [normed_add_comm_group E] [normed_space 𝕜 E]
/-- An equivalence of finite domains induces a linearly isometric equivalence of finitely supported
functions-/
def _root_.linear_isometry_equiv.pi_Lp_congr_left (e : ι ≃ ι') :
pi_Lp p (λ i : ι, E) ≃ₗᵢ[𝕜] pi_Lp p (λ i : ι', E) :=
{ to_linear_equiv := linear_equiv.Pi_congr_left' 𝕜 (λ i : ι, E) e,
norm_map' := λ x,
begin
unfreezingI { rcases p.dichotomy with (rfl | h) },
{ simp_rw [norm_eq_csupr, linear_equiv.Pi_congr_left'_apply 𝕜 (λ i : ι, E) e x _],
exact e.symm.supr_congr (λ i, rfl) },
{ simp only [norm_eq_sum (zero_lt_one.trans_le h)],
simp_rw linear_equiv.Pi_congr_left'_apply 𝕜 (λ i : ι, E) e x _,
congr,
exact (fintype.sum_equiv (e.symm) _ _ (λ i, rfl)) }
end, }
variables {p 𝕜 E}
@[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_apply
(e : ι ≃ ι') (v : pi_Lp p (λ i : ι, E)) :
linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e v = equiv.Pi_congr_left' (λ i : ι, E) e v :=
rfl
@[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_symm (e : ι ≃ ι') :
(linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e).symm
= (linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e.symm) :=
linear_isometry_equiv.ext $ λ x, rfl
@[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_single
[decidable_eq ι] [decidable_eq ι'] (e : ι ≃ ι') (i : ι) (v : E) :
linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e (pi.single i v) = pi.single (e i) v :=
begin
funext x,
simp [linear_isometry_equiv.pi_Lp_congr_left, linear_equiv.Pi_congr_left', equiv.Pi_congr_left',
pi.single, function.update, equiv.symm_apply_eq],
end
@[simp] lemma equiv_zero : pi_Lp.equiv p β 0 = 0 := rfl
@[simp] lemma equiv_symm_zero : (pi_Lp.equiv p β).symm 0 = 0 := rfl
@[simp] lemma equiv_add :
pi_Lp.equiv p β (x + y) = pi_Lp.equiv p β x + pi_Lp.equiv p β y := rfl
@[simp] lemma equiv_symm_add :
(pi_Lp.equiv p β).symm (x' + y') = (pi_Lp.equiv p β).symm x' + (pi_Lp.equiv p β).symm y' := rfl
@[simp] lemma equiv_sub : pi_Lp.equiv p β (x - y) = pi_Lp.equiv p β x - pi_Lp.equiv p β y := rfl
@[simp] lemma equiv_symm_sub :
(pi_Lp.equiv p β).symm (x' - y') = (pi_Lp.equiv p β).symm x' - (pi_Lp.equiv p β).symm y' := rfl
@[simp] lemma equiv_neg : pi_Lp.equiv p β (-x) = -pi_Lp.equiv p β x := rfl
@[simp] lemma equiv_symm_neg : (pi_Lp.equiv p β).symm (-x') = -(pi_Lp.equiv p β).symm x' := rfl
@[simp] lemma equiv_smul : pi_Lp.equiv p β (c • x) = c • pi_Lp.equiv p β x := rfl
@[simp] lemma equiv_symm_smul :
(pi_Lp.equiv p β).symm (c • x') = c • (pi_Lp.equiv p β).symm x' := rfl
/-- When `p = ∞`, this lemma does not hold without the additional assumption `nonempty ι` because
the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See
`pi_Lp.nnnorm_equiv_symm_const'` for a version which exchanges the hypothesis `p ≠ ∞` for
`nonempty ι`. -/
lemma nnnorm_equiv_symm_const {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) (b : β) :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖₊=
fintype.card ι ^ (1 / p).to_real * ‖b‖₊ :=
begin
rcases p.dichotomy with (h | h),
{ exact false.elim (hp h) },
{ have ne_zero : p.to_real ≠ 0 := (zero_lt_one.trans_le h).ne',
simp_rw [nnnorm_eq_sum hp, equiv_symm_apply, function.const_apply, finset.sum_const,
finset.card_univ, nsmul_eq_mul, nnreal.mul_rpow, ←nnreal.rpow_mul, mul_one_div_cancel ne_zero,
nnreal.rpow_one, ennreal.to_real_div, ennreal.one_to_real], },
end
/-- When `is_empty ι`, this lemma does not hold without the additional assumption `p ≠ ∞` because
the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See
`pi_Lp.nnnorm_equiv_symm_const` for a version which exchanges the hypothesis `nonempty ι`.
for `p ≠ ∞`. -/
lemma nnnorm_equiv_symm_const' {β} [seminormed_add_comm_group β] [nonempty ι] (b : β) :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖₊=
fintype.card ι ^ (1 / p).to_real * ‖b‖₊ :=
begin
unfreezingI { rcases (em $ p = ∞) with (rfl | hp) },
{ simp only [equiv_symm_apply, ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero, one_mul,
nnnorm_eq_csupr, function.const_apply, csupr_const], },
{ exact nnnorm_equiv_symm_const hp b, },
end
/-- When `p = ∞`, this lemma does not hold without the additional assumption `nonempty ι` because
the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See
`pi_Lp.norm_equiv_symm_const'` for a version which exchanges the hypothesis `p ≠ ∞` for
`nonempty ι`. -/
lemma norm_equiv_symm_const {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) (b : β) :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖ =
fintype.card ι ^ (1 / p).to_real * ‖b‖ :=
(congr_arg coe $ nnnorm_equiv_symm_const hp b).trans $ by simp
/-- When `is_empty ι`, this lemma does not hold without the additional assumption `p ≠ ∞` because
the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See
`pi_Lp.norm_equiv_symm_const` for a version which exchanges the hypothesis `nonempty ι`.
for `p ≠ ∞`. -/
lemma norm_equiv_symm_const' {β} [seminormed_add_comm_group β] [nonempty ι] (b : β) :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖ =
fintype.card ι ^ (1 / p).to_real * ‖b‖ :=
(congr_arg coe $ nnnorm_equiv_symm_const' b).trans $ by simp
lemma nnnorm_equiv_symm_one {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) [has_one β] :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm 1‖₊ = fintype.card ι ^ (1 / p).to_real * ‖(1 : β)‖₊ :=
(nnnorm_equiv_symm_const hp (1 : β)).trans rfl
lemma norm_equiv_symm_one {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) [has_one β] :
‖(pi_Lp.equiv p (λ _ : ι, β)).symm 1‖ = fintype.card ι ^ (1 / p).to_real * ‖(1 : β)‖ :=
(norm_equiv_symm_const hp (1 : β)).trans rfl
variables (𝕜 p)
/-- `pi_Lp.equiv` as a linear map. -/
@[simps {fully_applied := ff}]
protected def linear_equiv : pi_Lp p β ≃ₗ[𝕜] Π i, β i :=
{ to_fun := pi_Lp.equiv _ _,
inv_fun := (pi_Lp.equiv _ _).symm,
..linear_equiv.refl _ _}
section basis
variables (ι)
/-- A version of `pi.basis_fun` for `pi_Lp`. -/
def basis_fun : basis ι 𝕜 (pi_Lp p (λ _, 𝕜)) :=
basis.of_equiv_fun (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜))
@[simp] lemma basis_fun_apply [decidable_eq ι] (i) :
basis_fun p 𝕜 ι i = (pi_Lp.equiv p _).symm (pi.single i 1) :=
by { simp_rw [basis_fun, basis.coe_of_equiv_fun, pi_Lp.linear_equiv_symm_apply, pi.single],
congr /- Get rid of a `decidable_eq` mismatch. -/ }
@[simp] lemma basis_fun_repr (x : pi_Lp p (λ i : ι, 𝕜)) (i : ι) :
(basis_fun p 𝕜 ι).repr x i = x i :=
rfl
lemma basis_fun_eq_pi_basis_fun :
basis_fun p 𝕜 ι = (pi.basis_fun 𝕜 ι).map (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜)).symm :=
rfl
@[simp] lemma basis_fun_map :
(basis_fun p 𝕜 ι).map (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜)) = pi.basis_fun 𝕜 ι :=
rfl
open_locale matrix
lemma basis_to_matrix_basis_fun_mul (b : basis ι 𝕜 (pi_Lp p (λ i : ι, 𝕜))) (A : matrix ι ι 𝕜) :
b.to_matrix (pi_Lp.basis_fun _ _ _) ⬝ A =
matrix.of (λ i j, b.repr ((pi_Lp.equiv _ _).symm (Aᵀ j)) i) :=
begin
have := basis_to_matrix_basis_fun_mul (b.map (pi_Lp.linear_equiv _ 𝕜 _)) A,
simp_rw [←pi_Lp.basis_fun_map p, basis.map_repr, linear_equiv.trans_apply,
pi_Lp.linear_equiv_symm_apply, basis.to_matrix_map, function.comp, basis.map_apply,
linear_equiv.symm_apply_apply] at this,
exact this,
end
end basis
end pi_Lp
|
23a03a80789b1f57e4d937f49162549e4a7ae153 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/elabissues/namespace_vs_prefix.lean | bbc731cf12242e6f9d25abbd63c9187cdfde8283 | [
"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 | 725 | lean | inductive Foo : Type
| mk : Nat → Foo
namespace Foo
def worksInNamespace : Foo → Nat
| mk n => n --works
end Foo
-- The following fails, because `namespace Foo` is not open,
-- despite the `Foo.` prefix in the name.
def Foo.failsWithPrefix : Foo → Nat
| mk n => n -- error: invalid application, function expected
def Foo.worksWithQualifiedName : Foo → Nat
| Foo.mk n => n -- works
/-
This has always (slightly) annoyed me, because
I find that function bodies can be clunky without the open namespace,
while surrounding functions with
namespace Foo
def ...
end Foo
adds a lot of clutter to a file.
Here are the semantics I always seem to expect:
def Foo.f ...
as sugar for
namespace Foo
def f ...
end Foo
-/
|
a2815fde28e506d7439362ae88bb44e071f1633c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/localization/num_denom.lean | db61a20f6d8218a470f7cd02e5e9c3a9870d3f4b | [
"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,968 | 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, Anne Baanen
-/
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
import ring_theory.unique_factorization_domain
/-!
# Numerator and denominator in a localization
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## 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]
variables [algebra R S] {P : Type*} [comm_ring P]
namespace is_fraction_ring
open is_localization
section num_denom
variables (A : Type*) [comm_ring A] [is_domain A] [unique_factorization_monoid A]
variables {K : Type*} [field K] [algebra A K] [is_fraction_ring A K]
lemma exists_reduced_fraction (x : K) :
∃ (a : A) (b : non_zero_divisors A),
(∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ mk' K a b = x :=
begin
obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := exists_integer_multiple (non_zero_divisors A) 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, _⟩,
refine mul_left_cancel₀
(is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors b_nonzero) _,
simp only [subtype.coe_mk, ring_hom.map_mul, algebra.smul_def] 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 : K) : A :=
classical.some (exists_reduced_fraction A x)
/-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/
noncomputable def denom (x : K) : non_zero_divisors A :=
classical.some (classical.some_spec (exists_reduced_fraction A x))
lemma num_denom_reduced (x : K) {d} : d ∣ num A x → d ∣ denom A x → is_unit d :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).1
@[simp] lemma mk'_num_denom (x : K) : mk' K (num A x) (denom A x) = x :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).2
variables {A}
lemma num_mul_denom_eq_num_iff_eq {x y : K} :
x * algebra_map A K (denom A y) = algebra_map A K (num A 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 : K} :
y * algebra_map A K (denom A x) = algebra_map A K (num A 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 : K} :
num A y * denom A x = num A x * denom A 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 : K} (h : num A 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 : K} (h : is_unit (denom A x : A)) : is_integer A x :=
begin
cases h with d hd,
have d_ne_zero : algebra_map A K (denom A x) ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors (denom A x).2,
use ↑d⁻¹ * num A x,
refine trans _ (mk'_num_denom A x),
rw [map_mul, 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 : K} (h : num A x = 0) : is_unit (denom A x : A) :=
num_denom_reduced A x (h.symm ▸ dvd_zero _) dvd_rfl
end num_denom
variables (S)
end is_fraction_ring
|
6b4ef4ac6c7bfa2cba9c7dfc7aa7ca0f8daaa942 | 7c92a46ce39266c13607ecdef7f228688f237182 | /src/valuation/with_zero_topology.lean | eaa8e08288875f98da31ea3f089700e15f0a7ecc | [
"Apache-2.0"
] | permissive | asym57/lean-perfectoid-spaces | 3217d01f6ddc0d13e9fb68651749469750420767 | 359187b429f254a946218af4411d45f08705c83e | refs/heads/master | 1,609,457,937,251 | 1,577,542,616,000 | 1,577,542,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,173 | lean | import topology.algebra.ordered
import for_mathlib.filter
import for_mathlib.topology
import valuation.linear_ordered_comm_group_with_zero
/-!
# The topology on linearly ordered commutative groups with zero
Let Γ₀ be a linearly ordered commutative group to which we have adjoined a zero element.
Then Γ₀ may naturally be endowed with a topology that turns Γ₀ into a topological monoid.
The topology is the following:
A subset U ⊆ Γ₀ is open if 0 ∉ U or if there is an invertible γ₀ ∈ Γ₀ such that {γ | γ < γ₀} ⊆ U.
-/
local attribute [instance, priority 0] classical.DLO
local notation `𝓝` x: 70 := nhds x
namespace linear_ordered_comm_group_with_zero
open topological_space filter set linear_ordered_structure
variables (Γ₀ : Type*) [linear_ordered_comm_group_with_zero Γ₀]
/--The neighbourhoods around γ ∈ Γ₀, used in the definition of the topology on Γ₀.
These neighbourhoods are defined as follows:
A set s is a neighbourhood of 0 if there is an invertible γ₀ ∈ Γ₀ such that {γ | γ < γ₀} ⊆ s.
If γ ≠ 0, then every set that contains γ is a neighbourhood of γ. -/
def nhds_fun : Γ₀ → filter Γ₀ :=
(λ x : Γ₀, if x = 0 then ⨅ (γ₀ : units Γ₀), principal {γ | γ < γ₀} else pure x)
/--The topology on a linearly ordered commutative group with a zero element adjoined.
A subset U is open if 0 ∉ U or if there is an invertible element γ₀ such that {γ | γ < γ₀} ⊆ U. -/
protected def topological_space : topological_space Γ₀ :=
topological_space.mk_of_nhds (nhds_fun Γ₀)
local attribute [instance] linear_ordered_comm_group_with_zero.topological_space
/--The neighbourhoods {γ | γ < γ₀} of 0 form a directed set indexed by the invertible elements γ₀.-/
@[nolint]
lemma directed_lt : directed (≥) (λ (γ₀ : units Γ₀), principal {γ : Γ₀ | γ < ↑γ₀}) :=
begin
intros γ₁ γ₂,
use min γ₁ γ₂,
split,
{ change principal {γ : Γ₀ | γ < ↑(min γ₁ γ₂)} ≤ principal {γ : Γ₀ | γ < ↑γ₁},
rw [principal_mono, coe_min],
intros x x_in,
calc x < min ↑γ₁ ↑γ₂ : x_in
... ≤ γ₁ : min_le_left _ _ },
{ change principal {γ : Γ₀ | γ < ↑(min γ₁ γ₂)} ≤ principal {γ : Γ₀ | γ < ↑γ₂},
rw [principal_mono, coe_min],
intros x x_in,
calc x < min ↑γ₁ ↑γ₂ : x_in
... ≤ γ₂ : min_le_right _ _ }
end
-- We need two auxilliary lemmas to show that nhds_fun accurately describes the neighbourhoods
-- coming from the topology (that is defined in terms of nhds_fun).
/--At all points of a linearly ordered commutative group with a zero element adjoined,
the pure filter is smaller than the filter given by nhds_fun.-/
private lemma pure_le_nhds_fun : pure ≤ nhds_fun Γ₀ :=
λ x, by { by_cases hx : x = 0; simp [hx, nhds_fun] }
/--For every point Γ₀, and every “neighbourhood” s of it (described by nhds_fun), there is a
smaller “neighbourhood” t ⊆ s, such that s is a “neighbourhood“ of all the points in t.-/
private lemma nhds_fun_ok : ∀ (x : Γ₀) (s ∈ nhds_fun Γ₀ x),
(∃ t ∈ nhds_fun Γ₀ x, t ⊆ s ∧ ∀ y ∈ t, s ∈ nhds_fun Γ₀ y) :=
begin
intros x U U_in,
by_cases hx : x = 0,
{ simp [hx, nhds_fun] at U_in ⊢,
rw [mem_infi (directed_lt Γ₀) ⟨1⟩, mem_Union] at U_in,
cases U_in with γ₀ h,
use {γ : Γ₀ | γ < ↑γ₀},
rw mem_principal_sets at h,
split,
{ apply mem_infi_sets γ₀,
rw mem_principal_sets},
{ refine ⟨h, _⟩,
intros y y_in,
by_cases hy : y = 0 ; simp [hy, h y_in],
{ apply mem_infi_sets γ₀,
rwa mem_principal_sets } } },
{ simp [hx, nhds_fun] at U_in ⊢,
use {x},
refine ⟨mem_singleton _, singleton_subset_iff.2 U_in, _⟩,
intros y y_in,
rw mem_singleton_iff at y_in,
rw y_in,
simpa [hx] }
end
variables {Γ₀}
/--The neighbourhood filter of an invertible element consists of all sets containing that element.-/
@[simp] lemma nhds_coe (γ : units Γ₀) : 𝓝 (γ : Γ₀) = pure (γ : Γ₀) :=
calc 𝓝 (γ : Γ₀) = nhds_fun Γ₀ γ : nhds_mk_of_nhds (nhds_fun Γ₀) γ (pure_le_nhds_fun Γ₀) (nhds_fun_ok Γ₀)
... = pure (γ : Γ₀) : if_neg (group_with_zero.unit_ne_zero γ)
/--The neighbourhood filter of a nonzero element consists of all sets containing that element.-/
@[simp] lemma nhds_of_ne_zero (γ : Γ₀) (h : γ ≠ 0) :
𝓝 γ = pure γ :=
nhds_coe (group_with_zero.mk₀ _ h)
/--If γ is an invertible element of a linearly ordered group with zero element adjoined,
then {γ} is a neighbourhood of γ.-/
lemma singleton_nhds_of_units (γ : units Γ₀) : ({γ} : set Γ₀) ∈ 𝓝 (γ : Γ₀) :=
by simp
/--If γ is a nonzero element of a linearly ordered group with zero element adjoined,
then {γ} is a neighbourhood of γ.-/
lemma singleton_nhds_of_ne_zero (γ : Γ₀) (h : γ ≠ 0) : ({γ} : set Γ₀) ∈ 𝓝 (γ : Γ₀) :=
by simp [h]
/--If U is a neighbourhood of 0 in a linearly ordered group with zero element adjoined,
then there exists an invertible element γ₀ such that {γ | γ < γ₀} ⊆ U.
-/
lemma nhds_zero_mem (U : set Γ₀) : U ∈ 𝓝 (0 : Γ₀) ↔ ∃ γ₀ : units Γ₀, {γ : Γ₀ | γ < γ₀} ⊆ U :=
begin
rw nhds_mk_of_nhds (nhds_fun Γ₀) 0 (pure_le_nhds_fun Γ₀) (nhds_fun_ok Γ₀),
simp [nhds_fun],
rw mem_infi (directed_lt Γ₀) ⟨1⟩,
{ split,
{ rintro ⟨_, ⟨γ₀, rfl⟩, H⟩,
rw mem_principal_sets at H,
use [γ₀, H] },
{ rintro ⟨γ₀, H⟩,
rw mem_Union,
use γ₀,
rwa mem_principal_sets } }
end
/--If γ is an invertible element of a linearly ordered group with zero element adjoined,
then {x | x < γ} is a neighbourhood of 0.-/
lemma nhds_zero_of_units (γ : units Γ₀) : {x : Γ₀ | x < γ} ∈ 𝓝 (0 : Γ₀) :=
by { rw nhds_zero_mem, use γ }
/--If γ is a nonzero element of a linearly ordered group with zero element adjoined,
then {x | x < γ} is a neighbourhood of 0.-/
lemma nhds_zero_of_ne_zero (γ : Γ₀) (h : γ ≠ 0) : {x : Γ₀ | x < γ} ∈ 𝓝 (0 : Γ₀) :=
nhds_zero_of_units (group_with_zero.mk₀ _ h)
variable (Γ₀)
/--The topology on a linearly ordered group with zero element adjoined
is compatible with the order structure.-/
lemma ordered_topology : ordered_topology Γ₀ :=
{ is_closed_le' :=
begin
show is_open {p : Γ₀ × Γ₀ | ¬p.fst ≤ p.snd},
simp only [not_le],
rw is_open_iff_mem_nhds,
rintros ⟨a,b⟩ hab,
change b < a at hab,
have ha : a ≠ 0 := ne_zero_of_lt hab,
rw [nhds_prod_eq, mem_prod_iff],
by_cases hb : b = 0,
{ subst b,
use [{a}, singleton_nhds_of_ne_zero _ ha, {x : Γ₀ | x < a}, nhds_zero_of_ne_zero _ ha],
intros p p_in,
cases mem_prod.1 p_in with h1 h2,
rw mem_singleton_iff at h1,
change p.2 < p.1,
rwa h1 },
{ use [{a}, singleton_nhds_of_ne_zero _ ha, {b}, singleton_nhds_of_ne_zero _ hb],
intros p p_in,
cases mem_prod.1 p_in with h1 h2,
rw mem_singleton_iff at h1 h2,
change p.2 < p.1,
rwa [h1, h2] }
end }
local attribute [instance] ordered_topology
/--The topology on a linearly ordered group with zero element adjoined is T₂ (aka Hausdorff).-/
lemma t2_space : t2_space Γ₀ := ordered_topology.to_t2_space
local attribute [instance] t2_space
/--The topology on a linearly ordered group with zero element adjoined is T₃ (aka regular).-/
lemma regular_space : regular_space Γ₀ :=
begin
haveI : t1_space Γ₀ := t2_space.t1_space,
split,
intros s x s_closed x_not_in_s,
by_cases hx : x = 0,
{ refine ⟨s, _, subset.refl _, _⟩,
{ subst x,
rw is_open_iff_mem_nhds,
intros y hy,
by_cases hy' : y = 0, { subst y, contradiction },
simpa [hy'] },
{ rw inf_eq_bot_iff,
use -s,
simp only [exists_prop, mem_principal_sets],
split,
exact mem_nhds_sets (by rwa is_open_compl_iff) (by rwa mem_compl_iff),
exact ⟨s, subset.refl s, by simp⟩ } },
{ simp only [inf_eq_bot_iff, exists_prop, mem_principal_sets],
exact ⟨-{x}, is_open_compl_iff.mpr is_closed_singleton, by rwa subset_compl_singleton_iff,
{x}, singleton_nhds_of_ne_zero x hx, -{x}, by simp [subset.refl]⟩ }
end
/--The filter basis around the 0 element of a linearly ordered group with zero element adjoined.-/
def zero_filter_basis : filter_basis Γ₀ :=
{ sets := range (λ γ : units Γ₀, {x : Γ₀ | x < γ}),
ne_empty := range_ne_empty _,
directed := begin
intros s t hs ht,
rw mem_range at hs ht,
rcases hs with ⟨γs, rfl⟩,
rcases ht with ⟨γt, rfl⟩,
simp only [exists_prop, mem_range],
rcases directed_lt Γ₀ γs γt with ⟨γ, hs, ht⟩,
change principal {g : Γ₀ | g < ↑γ} ≤ principal {g : Γ₀ | g < ↑γt} at ht,
change principal {g : Γ₀ | g < ↑γ} ≤ principal {g : Γ₀ | g < ↑γs} at hs,
rw [le_principal_iff, mem_principal_sets] at hs ht,
use [{x : Γ₀ | x < γ}, γ, rfl, subset_inter_iff.mpr ⟨hs, ht⟩]
end}
variable {Γ₀}
-- TODO: Generalise the following definition into something like filter_basis.pure.
/--The filter basis around nonzero elements of
a linearly ordered group with zero element adjoined.-/
@[nolint]
def ne_zero_filter_basis (x : Γ₀) : filter_basis Γ₀ :=
{ sets := ({({x} : set Γ₀)} : set (set Γ₀)),
ne_empty := by simp,
directed := by finish }
variable (Γ₀)
/--The neighbourhood basis of a linearly ordered group with zero element adjoined.-/
def nhds_basis : nhds_basis Γ₀ :=
{ B := λ x, if h : x = 0 then zero_filter_basis Γ₀ else ne_zero_filter_basis x,
is_nhds := begin
intro x,
ext s,
split_ifs with hx,
{ subst x,
rw nhds_zero_mem,
simp [zero_filter_basis, filter_basis.mem_filter, filter_basis.mem_iff],
split,
{ rintros ⟨γ₀, h⟩,
use [{x : Γ₀ | x < ↑γ₀}, γ₀, h] },
{ rintros ⟨_, ⟨γ₀, rfl⟩, h⟩,
exact ⟨γ₀, h⟩ } },
{ simp [hx, filter_basis.mem_filter, filter_basis.mem_iff, ne_zero_filter_basis], }
end }
local attribute [instance] nhds_basis
lemma mem_nhds_basis_zero {U : set Γ₀} :
U ∈ nhds_basis.B (0 : Γ₀) ↔ ∃ γ : units Γ₀, U = {x : Γ₀ | x < γ } :=
begin
dsimp [nhds_basis, zero_filter_basis],
simp only [dif_pos],
convert iff.rfl,
simp [eq_comm]
end
lemma mem_nhds_basis_ne_zero {U : set Γ₀} {γ₀ : Γ₀} (h : γ₀ ≠ 0) :
U ∈ nhds_basis.B γ₀ ↔ U = {γ₀} :=
begin
dsimp [nhds_basis],
simp only [dif_neg h],
dsimp [filter_basis.has_mem, ne_zero_filter_basis γ₀],
exact set.mem_singleton_iff
end
variable {Γ₀}
-- until the end of this section, all linearly ordered commutative groups will be endowed with
-- the discrete topology
variables (α : Type*) [linear_ordered_comm_group α]
/--The discrete topology on a linearly ordered commutative group.-/
@[nolint] def discrete_ordered_comm_group : topological_space α := ⊥
local attribute [instance] discrete_ordered_comm_group
lemma ordered_comm_group_is_discrete : discrete_topology α := ⟨rfl⟩
local attribute [instance] ordered_comm_group_is_discrete
lemma comap_coe_nhds (γ : units Γ₀) : 𝓝 γ = comap coe (𝓝 (γ : Γ₀)) :=
begin
rw [nhds_discrete, filter.comap_pure (λ _ _ h, units.ext h) γ],
change comap coe (pure (γ : Γ₀)) = comap coe (𝓝 ↑γ),
rw ← nhds_coe γ,
end
lemma tendsto_zero {α : Type*} {F : filter α} {f : α → Γ₀} :
tendsto f F (𝓝 (0 : Γ₀)) ↔ ∀ γ₀ : units Γ₀, { x : α | f x < γ₀ } ∈ F :=
begin
rw nhds_basis.tendsto_into,
simp only [mem_nhds_basis_zero, exists_imp_distrib],
split ; intro h,
{ intro γ₀,
exact h {γ | γ < ↑γ₀} γ₀ rfl },
{ rintros _ γ₀ rfl,
exact h γ₀ }
end
lemma mem_nhds_zero {s} :
s ∈ 𝓝 (0 : Γ₀) ↔ ∃ γ : units Γ₀, { x : Γ₀ | x < γ } ⊆ s :=
begin
rw nhds_basis.mem_nhds_iff,
simp only [exists_prop, mem_nhds_basis_zero],
split,
{ rintros ⟨_, ⟨⟨γ, rfl⟩, h⟩⟩,
exact ⟨γ, h⟩ },
{ rintros ⟨γ, h⟩,
exact ⟨{x : Γ₀ | x < γ}, ⟨γ, rfl⟩, h⟩ }
end
lemma mem_nhds_coe {s} {γ : Γ₀} (h : γ ≠ 0) :
s ∈ 𝓝 γ ↔ γ ∈ s :=
begin
rw nhds_basis.mem_nhds_iff,
simp only [exists_prop, mem_nhds_basis_ne_zero _ h, h],
split,
{ rintros ⟨_, rfl, h₂⟩,
rwa singleton_subset_iff at h₂ },
{ intro h,
use [{γ}, rfl],
rwa singleton_subset_iff },
end
lemma tendsto_nonzero {α : Type*} {F : filter α} {f : α → Γ₀} {γ₀ : Γ₀} (h : γ₀ ≠ 0) :
tendsto f F (𝓝 (γ₀ : Γ₀)) ↔ { x : α | f x = γ₀ } ∈ F :=
begin
rw nhds_basis.tendsto_into,
simp only [mem_nhds_basis_ne_zero _ h, forall_eq],
convert iff.rfl,
ext s,
exact mem_singleton_iff.symm
end
/--A linearly ordered commutative group with zero Γ₀ is a topological monoid
if it is endowed with the following topology:
A subset U ⊆ Γ₀ is open if 0 ∉ U or if there is an invertible γ₀ ∈ Γ₀ such that {γ | γ < γ₀} ⊆ U.
-/
instance : topological_monoid Γ₀ :=
⟨begin
rw continuous_iff_continuous_at,
rintros ⟨x, y⟩,
by_cases hx : x = 0; by_cases hy : y = 0,
all_goals {
try {subst x}, try {subst y},
intros U U_in,
rw nhds_prod_eq,
try { simp only [_root_.mul_zero, _root_.zero_mul] at U_in},
rw mem_nhds_zero at U_in <|> rw [mem_nhds_coe] at U_in,
rw mem_map,
rw mem_prod_same_iff <|> rw mem_prod_iff,
try { cases U_in with γ hγ } },
{ cases linear_ordered_structure.exists_square_le γ with γ₀ hγ₀,
simp only [mem_nhds_zero, exists_prop],
refine ⟨{x : Γ₀ | x < ↑γ₀}, ⟨γ₀, subset.refl _⟩, _⟩,
rw set.prod_subset_iff,
intros x x_in y y_in,
apply hγ,
change x*y < γ,
have := mul_lt_mul' x_in y_in,
refine lt_of_lt_of_le this _,
exact_mod_cast hγ₀ },
{ simp only [set.prod_subset_iff, mem_nhds_zero, mem_nhds_coe hy, exists_prop],
use [{x : Γ₀ | x < γ*y⁻¹}, γ * (group_with_zero.mk₀ y hy)⁻¹, subset.refl _,
{(group_with_zero.mk₀ y hy)}, mem_singleton y],
intros x x_in y' y'_in,
rw mem_singleton_iff at y'_in,
rw y'_in,
apply hγ,
change x * y < γ,
simpa [hy] using mul_lt_right' y x_in hy, },
{ simp only [set.prod_subset_iff, mem_nhds_zero, mem_nhds_coe hx, exists_prop],
use [{(group_with_zero.mk₀ x hx)}, mem_singleton _, {y : Γ₀ | y < γ*x⁻¹},
γ * (group_with_zero.mk₀ x hx)⁻¹, subset.refl _],
intros x' x'_in y y_in,
rw mem_singleton_iff at x'_in,
rw x'_in,
apply hγ,
change x * y < γ,
rw mul_comm,
simpa [hx] using mul_lt_right' x y_in hx, },
{ simp [mem_nhds_coe, hx, hy],
use [{x}, mem_singleton _, {y}, mem_singleton _],
rw set.prod_subset_iff,
intros x' x'_in y' y'_in,
rw mem_singleton_iff at *,
rw [x'_in, y'_in],
simpa using U_in },
{ assume H, simp at H, tauto }
end⟩
end linear_ordered_comm_group_with_zero
|
5ab457375d69db6b5ea4e0ad78fa47fb878a8388 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/linear_pmap_auto.lean | b099747be3d1a10f1213a2d8a56d4fefe0928f3e | [] | 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 | 17,409 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.basic
import Mathlib.PostPort
universes u v w l u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# Partially defined linear maps
A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. We define
a `semilattice_inf_bot` instance on this this, and define three operations:
* `mk_span_singleton` defines a partial linear map defined on the span of a singleton.
* `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their
domains, and returns the unique partial linear map on `f.domain ⊔ g.domain` that
extends both `f` and `g`.
* `Sup` takes a `directed_on (≤)` set of partial linear maps, and returns the unique
partial linear map on the `Sup` of their domains that extends all these maps.
Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem
and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s
is bounded above.
Another possible use (not yet in `mathlib`) would be the theory of unbounded linear operators.
-/
/-- A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. -/
structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E]
(F : Type w) [add_comm_group F] [module R F]
where
domain : submodule R E
to_fun : linear_map R (↥domain) F
namespace linear_pmap
protected instance has_coe_to_fun {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] :
has_coe_to_fun (linear_pmap R E F) :=
has_coe_to_fun.mk (fun (f : linear_pmap R E F) => ↥(domain f) → F)
fun (f : linear_pmap R E F) => ⇑(to_fun f)
@[simp] theorem to_fun_eq_coe {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (x : ↥(domain f)) :
coe_fn (to_fun f) x = coe_fn f x :=
rfl
@[simp] theorem map_zero {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) : coe_fn f 0 = 0 :=
linear_map.map_zero (to_fun f)
theorem map_add {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (x : ↥(domain f))
(y : ↥(domain f)) : coe_fn f (x + y) = coe_fn f x + coe_fn f y :=
linear_map.map_add (to_fun f) x y
theorem map_neg {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (x : ↥(domain f)) :
coe_fn f (-x) = -coe_fn f x :=
linear_map.map_neg (to_fun f) x
theorem map_sub {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (x : ↥(domain f))
(y : ↥(domain f)) : coe_fn f (x - y) = coe_fn f x - coe_fn f y :=
linear_map.map_sub (to_fun f) x y
theorem map_smul {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (c : R)
(x : ↥(domain f)) : coe_fn f (c • x) = c • coe_fn f x :=
linear_map.map_smul (to_fun f) c x
@[simp] theorem mk_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (p : submodule R E) (f : linear_map R (↥p) F)
(x : ↥p) : coe_fn (mk p f) x = coe_fn f x :=
rfl
/-- The unique `linear_pmap` on `R ∙ x` that sends `x` to `y`. This version works for modules
over rings, and requires a proof of `∀ c, c • x = 0 → c • y = 0`. -/
def mk_span_singleton' {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (x : E) (y : F)
(H : ∀ (c : R), c • x = 0 → c • y = 0) : linear_pmap R E F :=
mk (submodule.span R (singleton x))
(linear_map.mk (fun (z : ↥(submodule.span R (singleton x))) => classical.some sorry • y) sorry
sorry)
@[simp] theorem domain_mk_span_singleton {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] (x : E) (y : F)
(H : ∀ (c : R), c • x = 0 → c • y = 0) :
domain (mk_span_singleton' x y H) = submodule.span R (singleton x) :=
rfl
@[simp] theorem mk_span_singleton_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] (x : E) (y : F)
(H : ∀ (c : R), c • x = 0 → c • y = 0) (c : R) (h : c • x ∈ domain (mk_span_singleton' x y H)) :
coe_fn (mk_span_singleton' x y H) { val := c • x, property := h } = c • y :=
sorry
/-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`.
This version works for modules over division rings. -/
def mk_span_singleton {K : Type u_1} {E : Type u_2} {F : Type u_3} [division_ring K]
[add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x ≠ 0) :
linear_pmap K E F :=
mk_span_singleton' x y sorry
/-- Projection to the first coordinate as a `linear_pmap` -/
protected def fst {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (p : submodule R E) (p' : submodule R F) :
linear_pmap R (E × F) E :=
mk (submodule.prod p p')
(linear_map.comp (linear_map.fst R E F) (submodule.subtype (submodule.prod p p')))
@[simp] theorem fst_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (p : submodule R E) (p' : submodule R F)
(x : ↥(submodule.prod p p')) : coe_fn (linear_pmap.fst p p') x = prod.fst ↑x :=
rfl
/-- Projection to the second coordinate as a `linear_pmap` -/
protected def snd {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (p : submodule R E) (p' : submodule R F) :
linear_pmap R (E × F) F :=
mk (submodule.prod p p')
(linear_map.comp (linear_map.snd R E F) (submodule.subtype (submodule.prod p p')))
@[simp] theorem snd_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (p : submodule R E) (p' : submodule R F)
(x : ↥(submodule.prod p p')) : coe_fn (linear_pmap.snd p p') x = prod.snd ↑x :=
rfl
protected instance has_neg {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : Neg (linear_pmap R E F) :=
{ neg := fun (f : linear_pmap R E F) => mk (domain f) (-to_fun f) }
@[simp] theorem neg_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (x : ↥(domain (-f))) :
coe_fn (-f) x = -coe_fn f x :=
rfl
protected instance has_le {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : HasLessEq (linear_pmap R E F) :=
{ LessEq :=
fun (f g : linear_pmap R E F) =>
domain f ≤ domain g ∧
∀ {x : ↥(domain f)} {y : ↥(domain g)}, ↑x = ↑y → coe_fn f x = coe_fn g y }
theorem eq_of_le_of_domain_eq {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {f : linear_pmap R E F} {g : linear_pmap R E F}
(hle : f ≤ g) (heq : domain f = domain g) : f = g :=
sorry
/-- Given two partial linear maps `f`, `g`, the set of points `x` such that
both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/
def eq_locus {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3}
[add_comm_group F] [module R F] (f : linear_pmap R E F) (g : linear_pmap R E F) :
submodule R E :=
submodule.mk
(set_of
fun (x : E) =>
∃ (hf : x ∈ domain f),
∃ (hg : x ∈ domain g),
coe_fn f { val := x, property := hf } = coe_fn g { val := x, property := hg })
sorry sorry sorry
protected instance has_inf {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : has_inf (linear_pmap R E F) :=
has_inf.mk
fun (f g : linear_pmap R E F) =>
mk (eq_locus f g) (linear_map.comp (to_fun f) (submodule.of_le sorry))
protected instance has_bot {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : has_bot (linear_pmap R E F) :=
has_bot.mk (mk ⊥ 0)
protected instance inhabited {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : Inhabited (linear_pmap R E F) :=
{ default := ⊥ }
protected instance semilattice_inf_bot {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] :
semilattice_inf_bot (linear_pmap R E F) :=
semilattice_inf_bot.mk ⊥ LessEq (order_bot.lt._default LessEq) sorry sorry sorry sorry has_inf.inf
sorry sorry sorry
theorem le_of_eq_locus_ge {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {f : linear_pmap R E F} {g : linear_pmap R E F}
(H : domain f ≤ eq_locus f g) : f ≤ g :=
sorry
theorem domain_mono {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] : strict_mono domain :=
fun (f g : linear_pmap R E F) (hlt : f < g) =>
lt_of_le_of_ne (and.left (and.left hlt))
fun (heq : domain f = domain g) => ne_of_lt hlt (eq_of_le_of_domain_eq (le_of_lt hlt) heq)
/-- Given two partial linear maps that agree on the intersection of their domains,
`f.sup g h` is the unique partial linear map on `f.domain ⊔ g.domain` that agrees
with `f` and `g`. -/
protected def sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (g : linear_pmap R E F)
(h : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) :
linear_pmap R E F :=
mk (domain f ⊔ domain g) (classical.some (sup_aux f g h))
@[simp] theorem domain_sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (g : linear_pmap R E F)
(h : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) :
domain (linear_pmap.sup f g h) = domain f ⊔ domain g :=
rfl
theorem sup_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {f : linear_pmap R E F} {g : linear_pmap R E F}
(H : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) (x : ↥(domain f))
(y : ↥(domain g)) (z : ↥(domain (linear_pmap.sup f g H))) (hz : ↑x + ↑y = ↑z) :
coe_fn (linear_pmap.sup f g H) z = coe_fn f x + coe_fn g y :=
classical.some_spec (sup_aux f g H) x y z hz
protected theorem left_le_sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (g : linear_pmap R E F)
(h : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) :
f ≤ linear_pmap.sup f g h :=
sorry
protected theorem right_le_sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F)
(g : linear_pmap R E F)
(h : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) :
g ≤ linear_pmap.sup f g h :=
sorry
protected theorem sup_le {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {f : linear_pmap R E F} {g : linear_pmap R E F}
{h : linear_pmap R E F}
(H : ∀ (x : ↥(domain f)) (y : ↥(domain g)), ↑x = ↑y → coe_fn f x = coe_fn g y) (fh : f ≤ h)
(gh : g ≤ h) : linear_pmap.sup f g H ≤ h :=
sorry
/-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/
theorem sup_h_of_disjoint {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (g : linear_pmap R E F)
(h : disjoint (domain f) (domain g)) (x : ↥(domain f)) (y : ↥(domain g)) (hxy : ↑x = ↑y) :
coe_fn f x = coe_fn g y :=
sorry
/-- Glue a collection of partially defined linear maps to a linear map defined on `Sup`
of these submodules. -/
protected def Sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (c : set (linear_pmap R E F))
(hc : directed_on LessEq c) : linear_pmap R E F :=
mk (Sup (domain '' c)) (classical.some (Sup_aux c hc))
protected theorem le_Sup {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {c : set (linear_pmap R E F)}
(hc : directed_on LessEq c) {f : linear_pmap R E F} (hf : f ∈ c) : f ≤ linear_pmap.Sup c hc :=
classical.some_spec (Sup_aux c hc) f hf
protected theorem Sup_le {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {c : set (linear_pmap R E F)}
(hc : directed_on LessEq c) {g : linear_pmap R E F}
(hg : ∀ (f : linear_pmap R E F), f ∈ c → f ≤ g) : linear_pmap.Sup c hc ≤ g :=
sorry
end linear_pmap
namespace linear_map
/-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/
def to_pmap {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3}
[add_comm_group F] [module R F] (f : linear_map R E F) (p : submodule R E) :
linear_pmap R E F :=
linear_pmap.mk p (comp f (submodule.subtype p))
@[simp] theorem to_pmap_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_map R E F) (p : submodule R E)
(x : ↥p) : coe_fn (to_pmap f p) x = coe_fn f ↑x :=
rfl
/-- Compose a linear map with a `linear_pmap` -/
def comp_pmap {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3}
[add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G]
(g : linear_map R F G) (f : linear_pmap R E F) : linear_pmap R E G :=
linear_pmap.mk (linear_pmap.domain f) (comp g (linear_pmap.to_fun f))
@[simp] theorem comp_pmap_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E]
[module R E] {F : Type u_3} [add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G]
[module R G] (g : linear_map R F G) (f : linear_pmap R E F)
(x : ↥(linear_pmap.domain (comp_pmap g f))) :
coe_fn (comp_pmap g f) x = coe_fn g (coe_fn f x) :=
rfl
end linear_map
namespace linear_pmap
/-- Restrict codomain of a `linear_pmap` -/
def cod_restrict {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] (f : linear_pmap R E F) (p : submodule R F)
(H : ∀ (x : ↥(domain f)), coe_fn f x ∈ p) : linear_pmap R E ↥p :=
mk (domain f) (linear_map.cod_restrict p (to_fun f) H)
/-- Compose two `linear_pmap`s -/
def comp {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3}
[add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G]
(g : linear_pmap R F G) (f : linear_pmap R E F)
(H : ∀ (x : ↥(domain f)), coe_fn f x ∈ domain g) : linear_pmap R E G :=
linear_map.comp_pmap (to_fun g) (cod_restrict f (domain g) H)
/-- `f.coprod g` is the partially defined linear map defined on `f.domain × g.domain`,
and sending `p` to `f p.1 + g p.2`. -/
def coprod {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3}
[add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G]
(f : linear_pmap R E G) (g : linear_pmap R F G) : linear_pmap R (E × F) G :=
mk (submodule.prod (domain f) (domain g))
(to_fun (comp f (linear_pmap.fst (domain f) (domain g)) sorry) +
to_fun (comp g (linear_pmap.snd (domain f) (domain g)) sorry))
@[simp] theorem coprod_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E]
{F : Type u_3} [add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G]
(f : linear_pmap R E G) (g : linear_pmap R F G) (x : ↥(domain (coprod f g))) :
coe_fn (coprod f g) x =
coe_fn f { val := prod.fst ↑x, property := and.left (subtype.property x) } +
coe_fn g { val := prod.snd ↑x, property := and.right (subtype.property x) } :=
rfl
end Mathlib |
968461e95245b54cf2bae3171aa7485d61c2010f | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/special_functions/bernstein.lean | b30ec1e65c458d21dae9670e593ad74d482fd024 | [
"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 | 12,890 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import ring_theory.polynomial.bernstein
import topology.continuous_function.polynomial
/-!
# Bernstein approximations and Weierstrass' theorem
We prove that the Bernstein approximations
```
∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k)
```
for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity.
Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D.
The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic,
and relies on Bernoulli's theorem,
which gives bounds for how quickly the observed frequencies in a
Bernoulli trial approach the underlying probability.
The proof here does not directly rely on Bernoulli's theorem,
but can also be given a probabilistic account.
* Consider a weighted coin which with probability `x` produces heads,
and with probability `1-x` produces tails.
* The value of `bernstein n k x` is the probability that
such a coin gives exactly `k` heads in a sequence of `n` tosses.
* If such an appearance of `k` heads results in a payoff of `f(k / n)`,
the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff.
* The main estimate in the proof bounds the probability that
the observed frequency of heads differs from `x` by more than some `δ`,
obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`.
* This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the
payoff function `f`.
(You don't need to think in these terms to follow the proof below: it's a giant `calc` block!)
This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`,
although we defer an abstract statement of this until later.
-/
noncomputable theory
open_locale classical
open_locale big_operators
open_locale bounded_continuous_function
open_locale unit_interval
/--
The Bernstein polynomials, as continuous functions on `[0,1]`.
-/
def bernstein (n ν : ℕ) : C(I, ℝ) :=
(bernstein_polynomial ℝ n ν).to_continuous_map_on I
@[simp] lemma bernstein_apply (n ν : ℕ) (x : I) :
bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) :=
begin
dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map,
bernstein_polynomial],
simp,
end
lemma bernstein_nonneg {n ν : ℕ} {x : I} :
0 ≤ bernstein n ν x :=
begin
simp only [bernstein_apply],
exact mul_nonneg
(mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _))
(pow_nonneg (by unit_interval) _),
end
/-!
We now give a slight reformulation of `bernstein_polynomial.variance`.
-/
namespace bernstein
/--
Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval.
-/
def z {n : ℕ} (k : fin (n+1)) : I :=
⟨(k : ℝ) / n,
begin
cases n,
{ norm_num },
{ have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _),
have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k),
rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁],
norm_cast,
simp [h₂], },
end⟩
local postfix `/ₙ`:90 := z
lemma probability (n : ℕ) (x : I) :
∑ k : fin (n+1), bernstein n k x = 1 :=
begin
have := bernstein_polynomial.sum ℝ n,
apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this,
simp [alg_hom.map_sum, finset.sum_range] at this,
exact this,
end
lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) :
∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n :=
begin
have h' : (n : ℝ) ≠ 0 := ne_of_gt h,
apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h',
apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h',
dsimp,
conv_lhs { simp only [finset.sum_mul, z], },
conv_rhs { rw div_mul_cancel _ h', },
have := bernstein_polynomial.variance ℝ n,
apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this,
simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this,
convert this using 1,
{ congr' 1, funext k,
rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc],
congr' 1,
field_simp [h],
ring, },
{ ring, },
end
end bernstein
open bernstein
local postfix `/ₙ`:2000 := z
/--
The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials,
given by `∑ k, f (k/n) * bernstein n k x`.
-/
def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) :=
∑ k : fin (n+1), f k/ₙ • bernstein n k
/-!
We now set up some of the basic machinery of the proof that the Bernstein approximations
converge uniformly.
A key player is the set `S f ε h n x`,
for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`.
This is the set of points `k` in `fin (n+1)` such that
`k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`,
chosen so `|f x - f y| < ε/2` when `|x - y| < δ`.
We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`.
-/
namespace bernstein_approximation
@[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) :
bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x :=
by simp [bernstein_approximation]
/--
The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`.
-/
def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h)
/--
The set of points `k` so `k/n` is within `δ` of `x`.
-/
def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) :=
{ k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset
/--
If `k ∈ S`, then `f(k/n)` is close to `f x`.
-/
lemma lt_of_mem_S
{f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) :
|f k/ₙ - f x| < ε/2 :=
begin
apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h),
simpa [S] using m,
end
/--
If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`.
This particular formulation will be helpful later.
-/
lemma le_of_mem_S_compl
{f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) :
(1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 :=
begin
simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m,
field_simp,
erw [le_div_iff (pow_pos f.modulus_pos 2), one_mul],
apply sq_le_sq,
rw abs_eq_self.mpr (le_of_lt f.modulus_pos),
rw [dist_comm] at m,
exact m,
end
end bernstein_approximation
open bernstein_approximation
open bounded_continuous_function
open filter
open_locale topological_space
/--
The Bernstein approximations
```
∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k)
```
for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity.
This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D,
and reproduced on wikipedia.
-/
theorem bernstein_approximation_uniform (f : C(I, ℝ)) :
tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) :=
begin
simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm],
intros ε h,
let δ := δ f ε h,
have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ∥f∥ * δ ^ (-2 : ℤ)),
filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0],
intros n nh npos',
have npos : 0 < (n:ℝ) := by exact_mod_cast npos',
-- Two easy inequalities we'll need later:
have w₁ : 0 ≤ 2 * ∥f∥ := mul_nonneg (by norm_num) (norm_nonneg f),
have w₂ : 0 ≤ 2 * ∥f∥ * δ^(-2 : ℤ) := mul_nonneg w₁ pow_minus_two_nonneg,
-- As `[0,1]` is compact, it suffices to check the inequality pointwise.
rw (continuous_map.norm_lt_iff _ h),
intro x,
-- The idea is to split up the sum over `k` into two sets,
-- `S`, where `x - k/n < δ`, and its complement.
let S := S f ε h n x,
calc
|(bernstein_approximation n f - f) x|
= |bernstein_approximation n f x - f x|
: rfl
... = |bernstein_approximation n f x - f x * 1|
: by rw mul_one
... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)|
: by rw bernstein.probability
... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x|
: by simp [bernstein_approximation, finset.mul_sum, sub_mul]
... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x|
: finset.abs_sum_le_sum_abs _ _
... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x
: by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg]
... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x +
∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x
: (S.sum_add_sum_compl _).symm
-- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks.
... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _
... = ε : add_halves ε,
{ -- We now work on the terms in `S`: uniform continuity and `bernstein.probability`
-- quickly give us a bound.
calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x
≤ ∑ k in S, ε/2 * bernstein n k x
: finset.sum_le_sum
(λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m))
bernstein_nonneg))
... = ε/2 * ∑ k in S, bernstein n k x
: by rw finset.mul_sum
-- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`,
-- so that we can use `bernstein.probability`.
... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x
: mul_le_mul_of_nonneg_left
(finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg))
(le_of_lt (half_pos h))
... = ε/2 : by rw [bernstein.probability, mul_one] },
{ -- We now turn to working on `Sᶜ`: we control the difference term just using `∥f∥`,
-- and then insert a `δ^(-2) * (x - k/n)^2` factor
-- (which is at least one because we are not in `S`).
calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x
≤ ∑ k in Sᶜ, (2 * ∥f∥) * bernstein n k x
: finset.sum_le_sum
(λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _)
bernstein_nonneg)
... = (2 * ∥f∥) * ∑ k in Sᶜ, bernstein n k x
: by rw finset.mul_sum
... ≤ (2 * ∥f∥) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x
: mul_le_mul_of_nonneg_left
(finset.sum_le_sum (λ k m, begin
conv_lhs { rw ←one_mul (bernstein _ _ _), },
exact mul_le_mul_of_nonneg_right
(le_of_mem_S_compl m) bernstein_nonneg,
end)) w₁
-- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)`
... ≤ (2 * ∥f∥) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x
: mul_le_mul_of_nonneg_left
(finset.sum_le_univ_sum_of_nonneg
(λ k, mul_nonneg
(mul_nonneg pow_minus_two_nonneg (sq_nonneg _))
bernstein_nonneg)) w₁
... = (2 * ∥f∥) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x
: by conv_rhs {
rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], }
-- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound
... = (2 * ∥f∥) * δ^(-2 : ℤ) * x * (1-x) / n
: by { rw variance npos, ring, }
... ≤ (2 * ∥f∥) * δ^(-2 : ℤ) / n
: (div_le_div_right npos).mpr
begin
apply mul_nonneg_le_one_le w₂,
apply mul_nonneg_le_one_le w₂ (le_refl _),
all_goals { unit_interval, },
end
... < ε/2 : nh, }
end
|
95e3081833fef3da57abc3ff16203a4324975e84 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/calculus/specific_functions.lean | d55ef2521e7f690f64502e9ec67901f0775d100a | [
"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 | 23,005 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn
-/
import analysis.calculus.iterated_deriv
import analysis.inner_product_space.euclidean_dist
import measure_theory.function.locally_integrable
import measure_theory.integral.set_integral
/-!
# Infinitely smooth bump function
In this file we construct several infinitely smooth functions with properties that an analytic
function cannot have:
* `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by
`x ↦ exp (-1/x)` for `x > 0`;
* `real.smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given
by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`;
* `f : cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is
a bundled smooth function such that
- `f` is equal to `1` in `metric.closed_ball c f.r`;
- `support f = metric.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `cont_diff_bump_of_inner` contains the data required to construct the
function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available
through `coe_fn`.
* If `f : cont_diff_bump_of_inner c` and `μ` is a measure on the domain of `f`, then `f.normed μ`
is a smooth bump function with integral `1` w.r.t. `μ`.
* `f : cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a
bundled smooth function such that
- `f` is equal to `1` in `euclidean.closed_ball c f.r`;
- `support f = euclidean.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `cont_diff_bump` contains the data required to construct the function: real
numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.
-/
noncomputable theory
open_locale classical topological_space
open polynomial real filter set function
/-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0`. It is a basic building block to construct smooth partitions of unity. Its main property
is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two
behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in
`exp_neg_inv_glue.smooth`. -/
def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹)
namespace exp_neg_inv_glue
/-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive
derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`,
where `P_aux n` is computed inductively. -/
noncomputable def P_aux : ℕ → polynomial ℝ
| 0 := 1
| (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n)
/-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/
def f_aux (n : ℕ) (x : ℝ) : ℝ :=
if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)
/-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/
lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue :=
begin
ext x,
by_cases h : x ≤ 0,
{ simp [exp_neg_inv_glue, f_aux, h] },
{ simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] }
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
(given in this statement in unfolded form) is the `n+1`-th auxiliary function, since
the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/
lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) :
has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n))
((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
have A : ∀ k : ℕ, 2 * (k + 1) - 1 = 2 * k + 1 := λ k, rfl,
convert (((P_aux n).has_deriv_at x).mul
(((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div
(has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1,
field_simp [hx, P_aux],
-- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff`
cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; ring_exp
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
is the `n+1`-th auxiliary function. -/
lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) :
has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq,
filter_upwards [lt_mem_nhds hx] with _ hy,
simp [f_aux, hy.not_le]
end
/-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit
is `0`, to be able to apply general differentiability extension theorems. This limit is checked in
this lemma. -/
lemma f_aux_limit (n : ℕ) :
tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0) :=
begin
have A : tendsto (λx, (P_aux n).eval x) (𝓝[>] 0) (𝓝 ((P_aux n).eval 0)) :=
(P_aux n).continuous_within_at,
have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0),
{ convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top,
ext x,
field_simp },
convert A.mul B;
simp [mul_div_assoc]
end
/-- Deduce from the limiting behavior at `0` of its derivative and general differentiability
extension theorems that the auxiliary function `f_aux n` is differentiable at `0`,
with derivative `0`. -/
lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 :=
begin
-- we check separately differentiability on the left and on the right
have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0,
{ apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr,
{ assume y hy,
simp at hy,
simp [f_aux, hy] },
{ simp [f_aux, le_refl] } },
have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0,
{ have diff : differentiable_on ℝ (f_aux n) (Ioi 0) :=
λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within,
{ refine (f_aux_limit (n+1)).congr' _,
apply mem_of_superset self_mem_nhds_within (λx hx, _),
simp [(f_aux_deriv_pos n x hx).deriv] },
{ have : f_aux n 0 = 0, by simp [f_aux, le_refl],
simp only [continuous_within_at, this],
refine (f_aux_limit n).congr' _,
apply mem_of_superset self_mem_nhds_within (λx hx, _),
have : ¬(x ≤ 0), by simpa using hx,
simp [f_aux, this] } },
simpa using A.union B,
end
/-- At every point, the auxiliary function `f_aux n` has a derivative which is
equal to `f_aux (n+1)`. -/
lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x :=
begin
-- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done
-- in `f_aux_deriv_pos`, and for `x = 0`, done in
-- `f_aux_deriv_zero`.
rcases lt_trichotomy x 0 with hx|hx|hx,
{ have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx],
rw this,
apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq,
filter_upwards [gt_mem_nhds hx] with _ hy,
simp [f_aux, hy.le] },
{ have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl],
rw [hx, this],
exact f_aux_deriv_zero n },
{ have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)),
by simp [f_aux, not_le_of_gt hx],
rw this,
exact f_aux_deriv_pos n x hx },
end
/-- The successive derivatives of the auxiliary function `f_aux 0` are the
functions `f_aux n`, by induction. -/
lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n :=
begin
induction n with n IH,
{ simp },
{ simp [iterated_deriv_succ, IH],
ext x,
exact (f_aux_has_deriv_at n x).deriv }
end
/-- The function `exp_neg_inv_glue` is smooth. -/
protected theorem cont_diff {n} : cont_diff ℝ n exp_neg_inv_glue :=
begin
rw ← f_aux_zero_eq,
apply cont_diff_of_differentiable_iterated_deriv (λ m hm, _),
rw f_aux_iterated_deriv m,
exact λ x, (f_aux_has_deriv_at m x).differentiable_at
end
/-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/
lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 :=
by simp [exp_neg_inv_glue, hx]
/-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/
lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x :=
by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos]
/-- The function exp_neg_inv_glue` is nonnegative. -/
lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x :=
begin
cases le_or_gt x 0,
{ exact ge_of_eq (zero_of_nonpos h) },
{ exact le_of_lt (pos_of_pos h) }
end
end exp_neg_inv_glue
/-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`,
`f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/
def real.smooth_transition (x : ℝ) : ℝ :=
exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))
namespace real
namespace smooth_transition
variables {x : ℝ}
open exp_neg_inv_glue
lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) :=
((@zero_lt_one ℝ _ _).lt_or_lt x).elim
(λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _))
(λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx))
lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 :=
(div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero]
lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 :=
by rw [smooth_transition, zero_of_nonpos h, zero_div]
@[simp] protected lemma zero : smooth_transition 0 = 0 :=
zero_of_nonpos le_rfl
@[simp] protected lemma one : smooth_transition 1 = 1 :=
one_of_one_le le_rfl
lemma le_one (x : ℝ) : smooth_transition x ≤ 1 :=
(div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _)
lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x :=
div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le
lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 :=
(div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h
lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x :=
div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x)
protected lemma cont_diff {n} : cont_diff ℝ n smooth_transition :=
exp_neg_inv_glue.cont_diff.div
(exp_neg_inv_glue.cont_diff.add $ exp_neg_inv_glue.cont_diff.comp $
cont_diff_const.sub cont_diff_id) $
λ x, (pos_denom x).ne'
protected lemma cont_diff_at {x n} : cont_diff_at ℝ n smooth_transition x :=
smooth_transition.cont_diff.cont_diff_at
protected lemma continuous : continuous smooth_transition :=
(@smooth_transition.cont_diff 0).continuous
end smooth_transition
end real
variables {E X : Type*}
/-- `f : cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a
bundled smooth function such that
- `f` is equal to `1` in `metric.closed_ball c f.r`;
- `support f = metric.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `cont_diff_bump_of_inner` contains the data required to construct the function:
real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through
`coe_fn`. -/
structure cont_diff_bump_of_inner (c : E) :=
(r R : ℝ)
(r_pos : 0 < r)
(r_lt_R : r < R)
namespace cont_diff_bump_of_inner
lemma R_pos {c : E} (f : cont_diff_bump_of_inner c) : 0 < f.R := f.r_pos.trans f.r_lt_R
instance (c : E) : inhabited (cont_diff_bump_of_inner c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩
variables [inner_product_space ℝ E] [normed_add_comm_group X] [normed_space ℝ X]
variables {c : E} (f : cont_diff_bump_of_inner c) {x : E} {n : ℕ∞}
/-- The function defined by `f : cont_diff_bump_of_inner c`. Use automatic coercion to
function instead. -/
def to_fun (f : cont_diff_bump_of_inner c) : E → ℝ :=
λ x, real.smooth_transition ((f.R - dist x c) / (f.R - f.r))
instance : has_coe_to_fun (cont_diff_bump_of_inner c) (λ _, E → ℝ) := ⟨to_fun⟩
protected lemma «def» (x : E) : f x = real.smooth_transition ((f.R - dist x c) / (f.R - f.r)) :=
rfl
protected lemma sub (x : E) : f (c - x) = f (c + x) :=
by simp_rw [f.def, dist_self_sub_left, dist_self_add_left]
protected lemma neg (f : cont_diff_bump_of_inner (0 : E)) (x : E) : f (- x) = f x :=
by simp_rw [← zero_sub, f.sub, zero_add]
open real (smooth_transition) real.smooth_transition metric
lemma one_of_mem_closed_ball (hx : x ∈ closed_ball c f.r) :
f x = 1 :=
one_of_one_le $ (one_le_div (sub_pos.2 f.r_lt_R)).2 $ sub_le_sub_left hx _
lemma nonneg : 0 ≤ f x := nonneg _
/-- A version of `cont_diff_bump_of_inner.nonneg` with `x` explicit -/
lemma nonneg' (x : E) : 0 ≤ f x :=
f.nonneg
lemma le_one : f x ≤ 1 := le_one _
lemma pos_of_mem_ball (hx : x ∈ ball c f.R) : 0 < f x :=
pos_of_pos $ div_pos (sub_pos.2 hx) (sub_pos.2 f.r_lt_R)
lemma lt_one_of_lt_dist (h : f.r < dist x c) : f x < 1 :=
lt_one_of_lt_one $ (div_lt_one (sub_pos.2 f.r_lt_R)).2 $ sub_lt_sub_left h _
lemma zero_of_le_dist (hx : f.R ≤ dist x c) : f x = 0 :=
zero_of_nonpos $ div_nonpos_of_nonpos_of_nonneg (sub_nonpos.2 hx) (sub_nonneg.2 f.r_lt_R.le)
lemma support_eq : support (f : E → ℝ) = metric.ball c f.R :=
begin
ext x,
suffices : f x ≠ 0 ↔ dist x c < f.R, by simpa [mem_support],
cases lt_or_le (dist x c) f.R with hx hx,
{ simp [hx, (f.pos_of_mem_ball hx).ne'] },
{ simp [hx.not_lt, f.zero_of_le_dist hx] }
end
lemma tsupport_eq : tsupport f = closed_ball c f.R :=
by simp_rw [tsupport, f.support_eq, closure_ball _ f.R_pos.ne']
protected lemma has_compact_support [finite_dimensional ℝ E] : has_compact_support f :=
by simp_rw [has_compact_support, f.tsupport_eq, is_compact_closed_ball]
lemma eventually_eq_one_of_mem_ball (h : x ∈ ball c f.r) :
f =ᶠ[𝓝 x] 1 :=
((is_open_lt (continuous_id.dist continuous_const) continuous_const).eventually_mem h).mono $
λ z hz, f.one_of_mem_closed_ball (le_of_lt hz)
lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 :=
f.eventually_eq_one_of_mem_ball (mem_ball_self f.r_pos)
/-- `cont_diff_bump` is `𝒞ⁿ` in all its arguments. -/
protected lemma _root_.cont_diff_at.cont_diff_bump {c g : X → E}
{f : ∀ x, cont_diff_bump_of_inner (c x)} {x : X}
(hc : cont_diff_at ℝ n c x) (hr : cont_diff_at ℝ n (λ x, (f x).r) x)
(hR : cont_diff_at ℝ n (λ x, (f x).R) x)
(hg : cont_diff_at ℝ n g x) : cont_diff_at ℝ n (λ x, f x (g x)) x :=
begin
rcases eq_or_ne (g x) (c x) with hx|hx,
{ have : (λ x, f x (g x)) =ᶠ[𝓝 x] (λ x, 1),
{ have : dist (g x) (c x) < (f x).r, { simp_rw [hx, dist_self, (f x).r_pos] },
have := continuous_at.eventually_lt (hg.continuous_at.dist hc.continuous_at) hr.continuous_at
this,
exact eventually_of_mem this
(λ x hx, (f x).one_of_mem_closed_ball (mem_set_of_eq.mp hx).le) },
exact cont_diff_at_const.congr_of_eventually_eq this },
{ refine real.smooth_transition.cont_diff_at.comp x _,
refine ((hR.sub $ hg.dist hc hx).div (hR.sub hr) (sub_pos.mpr (f x).r_lt_R).ne') }
end
lemma _root_.cont_diff.cont_diff_bump {c g : X → E} {f : ∀ x, cont_diff_bump_of_inner (c x)}
(hc : cont_diff ℝ n c) (hr : cont_diff ℝ n (λ x, (f x).r)) (hR : cont_diff ℝ n (λ x, (f x).R))
(hg : cont_diff ℝ n g) : cont_diff ℝ n (λ x, f x (g x)) :=
by { rw [cont_diff_iff_cont_diff_at] at *, exact λ x, (hc x).cont_diff_bump (hr x) (hR x) (hg x) }
protected lemma cont_diff : cont_diff ℝ n f :=
cont_diff_const.cont_diff_bump cont_diff_const cont_diff_const cont_diff_id
protected lemma cont_diff_at : cont_diff_at ℝ n f x :=
f.cont_diff.cont_diff_at
protected lemma cont_diff_within_at {s : set E} : cont_diff_within_at ℝ n f s x :=
f.cont_diff_at.cont_diff_within_at
protected lemma continuous : continuous f :=
cont_diff_zero.mp f.cont_diff
open measure_theory
variables [measurable_space E] {μ : measure E}
/-- A bump function normed so that `∫ x, f.normed μ x ∂μ = 1`. -/
protected def normed (μ : measure E) : E → ℝ :=
λ x, f x / ∫ x, f x ∂μ
lemma normed_def {μ : measure E} (x : E) : f.normed μ x = f x / ∫ x, f x ∂μ :=
rfl
lemma nonneg_normed (x : E) : 0 ≤ f.normed μ x :=
div_nonneg f.nonneg $ integral_nonneg f.nonneg'
lemma cont_diff_normed {n : ℕ∞} : cont_diff ℝ n (f.normed μ) :=
f.cont_diff.div_const
lemma continuous_normed : continuous (f.normed μ) :=
f.continuous.div_const
lemma normed_sub (x : E) : f.normed μ (c - x) = f.normed μ (c + x) :=
by simp_rw [f.normed_def, f.sub]
lemma normed_neg (f : cont_diff_bump_of_inner (0 : E)) (x : E) : f.normed μ (- x) = f.normed μ x :=
by simp_rw [f.normed_def, f.neg]
variables [borel_space E] [finite_dimensional ℝ E] [is_locally_finite_measure μ]
protected lemma integrable : integrable f μ :=
f.continuous.integrable_of_has_compact_support f.has_compact_support
protected lemma integrable_normed : integrable (f.normed μ) μ :=
f.integrable.div_const _
variables [μ .is_open_pos_measure]
lemma integral_pos : 0 < ∫ x, f x ∂μ :=
begin
refine (integral_pos_iff_support_of_nonneg f.nonneg' f.integrable).mpr _,
rw [f.support_eq],
refine is_open_ball.measure_pos _ (nonempty_ball.mpr f.R_pos)
end
lemma integral_normed : ∫ x, f.normed μ x ∂μ = 1 :=
begin
simp_rw [cont_diff_bump_of_inner.normed, div_eq_mul_inv, mul_comm (f _), ← smul_eq_mul,
integral_smul],
exact inv_mul_cancel (f.integral_pos.ne')
end
lemma support_normed_eq : support (f.normed μ) = metric.ball c f.R :=
by simp_rw [cont_diff_bump_of_inner.normed, support_div, f.support_eq,
support_const f.integral_pos.ne', inter_univ]
lemma tsupport_normed_eq : tsupport (f.normed μ) = metric.closed_ball c f.R :=
by simp_rw [tsupport, f.support_normed_eq, closure_ball _ f.R_pos.ne']
lemma has_compact_support_normed : has_compact_support (f.normed μ) :=
by simp_rw [has_compact_support, f.tsupport_normed_eq, is_compact_closed_ball]
variable (μ)
lemma integral_normed_smul (z : X) [complete_space X] : ∫ x, f.normed μ x • z ∂μ = z :=
by simp_rw [integral_smul_const, f.integral_normed, one_smul]
end cont_diff_bump_of_inner
/-- `f : cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is
a bundled smooth function such that
- `f` is equal to `1` in `euclidean.closed_ball c f.r`;
- `support f = euclidean.ball c f.R`;
- `0 ≤ f x ≤ 1` for all `x`.
The structure `cont_diff_bump` contains the data required to construct the function: real
numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.-/
structure cont_diff_bump [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
(c : E)
extends cont_diff_bump_of_inner (to_euclidean c)
namespace cont_diff_bump
variables [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {c x : E}
(f : cont_diff_bump c)
/-- The function defined by `f : cont_diff_bump c`. Use automatic coercion to function
instead. -/
def to_fun (f : cont_diff_bump c) : E → ℝ := f.to_cont_diff_bump_of_inner ∘ to_euclidean
instance : has_coe_to_fun (cont_diff_bump c) (λ _, E → ℝ) := ⟨to_fun⟩
instance (c : E) : inhabited (cont_diff_bump c) := ⟨⟨default⟩⟩
lemma R_pos : 0 < f.R := f.to_cont_diff_bump_of_inner.R_pos
lemma coe_eq_comp : ⇑f = f.to_cont_diff_bump_of_inner ∘ to_euclidean := rfl
lemma one_of_mem_closed_ball (hx : x ∈ euclidean.closed_ball c f.r) :
f x = 1 :=
f.to_cont_diff_bump_of_inner.one_of_mem_closed_ball hx
lemma nonneg : 0 ≤ f x := f.to_cont_diff_bump_of_inner.nonneg
lemma le_one : f x ≤ 1 := f.to_cont_diff_bump_of_inner.le_one
lemma pos_of_mem_ball (hx : x ∈ euclidean.ball c f.R) : 0 < f x :=
f.to_cont_diff_bump_of_inner.pos_of_mem_ball hx
lemma lt_one_of_lt_dist (h : f.r < euclidean.dist x c) : f x < 1 :=
f.to_cont_diff_bump_of_inner.lt_one_of_lt_dist h
lemma zero_of_le_dist (hx : f.R ≤ euclidean.dist x c) : f x = 0 :=
f.to_cont_diff_bump_of_inner.zero_of_le_dist hx
lemma support_eq : support (f : E → ℝ) = euclidean.ball c f.R :=
by rw [euclidean.ball_eq_preimage, ← f.to_cont_diff_bump_of_inner.support_eq,
← support_comp_eq_preimage, coe_eq_comp]
lemma tsupport_eq : tsupport f = euclidean.closed_ball c f.R :=
by rw [tsupport, f.support_eq, euclidean.closure_ball _ f.R_pos.ne']
protected lemma has_compact_support : has_compact_support f :=
by simp_rw [has_compact_support, f.tsupport_eq, euclidean.is_compact_closed_ball]
lemma eventually_eq_one_of_mem_ball (h : x ∈ euclidean.ball c f.r) :
f =ᶠ[𝓝 x] 1 :=
to_euclidean.continuous_at (f.to_cont_diff_bump_of_inner.eventually_eq_one_of_mem_ball h)
lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 :=
f.eventually_eq_one_of_mem_ball $ euclidean.mem_ball_self f.r_pos
protected lemma cont_diff {n} :
cont_diff ℝ n f :=
f.to_cont_diff_bump_of_inner.cont_diff.comp (to_euclidean : E ≃L[ℝ] _).cont_diff
protected lemma cont_diff_at {n} :
cont_diff_at ℝ n f x :=
f.cont_diff.cont_diff_at
protected lemma cont_diff_within_at {s n} :
cont_diff_within_at ℝ n f s x :=
f.cont_diff_at.cont_diff_within_at
lemma exists_tsupport_subset {s : set E} (hs : s ∈ 𝓝 c) :
∃ f : cont_diff_bump c, tsupport f ⊆ s :=
let ⟨R, h0, hR⟩ := euclidean.nhds_basis_closed_ball.mem_iff.1 hs
in ⟨⟨⟨R / 2, R, half_pos h0, half_lt_self h0⟩⟩, by rwa tsupport_eq⟩
lemma exists_closure_subset {R : ℝ} (hR : 0 < R)
{s : set E} (hs : is_closed s) (hsR : s ⊆ euclidean.ball c R) :
∃ f : cont_diff_bump c, f.R = R ∧ s ⊆ euclidean.ball c f.r :=
begin
rcases euclidean.exists_pos_lt_subset_ball hR hs hsR with ⟨r, hr, hsr⟩,
exact ⟨⟨⟨r, R, hr.1, hr.2⟩⟩, rfl, hsr⟩
end
end cont_diff_bump
open finite_dimensional metric
/-- If `E` is a finite dimensional normed space over `ℝ`, then for any point `x : E` and its
neighborhood `s` there exists an infinitely smooth function with the following properties:
* `f y = 1` in a neighborhood of `x`;
* `f y = 0` outside of `s`;
* moreover, `tsupport f ⊆ s` and `f` has compact support;
* `f y ∈ [0, 1]` for all `y`.
This lemma is a simple wrapper around lemmas about bundled smooth bump functions, see
`cont_diff_bump`. -/
lemma exists_cont_diff_bump_function_of_mem_nhds [normed_add_comm_group E] [normed_space ℝ E]
[finite_dimensional ℝ E] {x : E} {s : set E} (hs : s ∈ 𝓝 x) :
∃ f : E → ℝ, f =ᶠ[𝓝 x] 1 ∧ (∀ y, f y ∈ Icc (0 : ℝ) 1) ∧ cont_diff ℝ ⊤ f ∧
has_compact_support f ∧ tsupport f ⊆ s :=
let ⟨f, hf⟩ := cont_diff_bump.exists_tsupport_subset hs in
⟨f, f.eventually_eq_one, λ y, ⟨f.nonneg, f.le_one⟩, f.cont_diff,
f.has_compact_support, hf⟩
|
ab048866e3fb7b3d0f74e5ddb6aef00b069db19d | 94e33a31faa76775069b071adea97e86e218a8ee | /test/json.lean | fcaf548e4fb4b5b86ce56513d45e79411770f5fc | [
"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 | 2,467 | lean | import data.json
import data.int.basic
run_cmd do
let j := json.of_int 2,
z ← of_json native.float j,
guard (z = 2)
run_cmd do
j ← json.parse "2.0",
tactic.success_if_fail_with_msg (of_json ℤ j) "number must be integral"
run_cmd do
let j := json.of_int (-1),
tactic.success_if_fail_with_msg (of_json ℕ j) "must be non-negative"
@[derive [decidable_eq, non_null_json_serializable]]
structure my_type (yval : bool) :=
(x : nat)
(f : fin x)
(y : bool)
(h : y = yval)
run_cmd do
let actual := to_json (my_type.mk 37 2 tt rfl),
let expected := json.object [("x", json.of_int 37), ("f", json.of_int 2), ("y", json.of_bool tt)],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":true}"),
x ← of_json (my_type tt) j,
guard (x = ⟨37, 2, tt, rfl⟩)
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":true,\"z\":true}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "unexpected fields [z]"
run_cmd do
some j ← pure (json.parse "{\"x\":37}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "field f is required"
run_cmd do
let j := json.object [("x", to_json 37), ("x", to_json 37)],
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "duplicate x field"
run_cmd do
let j := json.null,
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "object expected, got null"
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":false}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "condition does not hold"
@[derive [decidable_eq, non_null_json_serializable]]
structure no_fields (n : ℕ) : Type
run_cmd do
let actual := to_json (@no_fields.mk 37),
let expected := json.object [],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{}"),
of_json (@no_fields 37) j
@[derive [decidable_eq, non_null_json_serializable]]
structure has_default : Type :=
(x : ℕ := 2)
(y : fin x.succ := 3 * fin.of_nat x)
(z : ℕ := 3)
run_cmd do
e ← of_json has_default (json.object []),
guard (e = {})
run_cmd do
let actual := to_json (has_default.mk 2 1 3),
let expected := json.object [("x", json.of_int 2), ("y", json.of_int 1), ("z", json.of_int 3)],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{\"x\":1,\"z\":3}"),
of_json has_default j
run_cmd do
some j ← pure (json.parse "{\"y\":2}"),
v ← of_json has_default j,
guard (v = {y := 2})
|
d1b7e9b3354dafbd00f8a7d527a274da789faa19 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/functor.lean | fdbe2b16c8862eadda8be6a1573aa9aa139005d5 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,635 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison
Defines a functor between categories.
(As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised
by the underlying function on objects, the name is capitalised.)
Introduces notations
`C ⥤ D` for the type of all functors from `C` to `D`.
(I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.)
-/
import tactic.reassoc_axiom
import tactic.monotonicity
namespace category_theory
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v v₁ v₂ v₃ u u₁ u₂ u₃
/--
`functor C D` represents a functor between categories `C` and `D`.
To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`.
The axiom `map_id` expresses preservation of identities, and
`map_comp` expresses functoriality.
See https://stacks.math.columbia.edu/tag/001B.
-/
structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :
Type (max v₁ v₂ u₁ u₂) :=
(obj [] : C → D)
(map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y)))
(map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously)
(map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously)
-- A functor is basically a function, so give ⥤ a similar precedence to → (25).
-- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`.
infixr ` ⥤ `:26 := functor -- type as \func --
restate_axiom functor.map_id'
attribute [simp] functor.map_id
restate_axiom functor.map_comp'
attribute [reassoc, simp] functor.map_comp
namespace functor
section
variables (C : Type u₁) [category.{v₁} C]
/-- `𝟭 C` is the identity functor on a category `C`. -/
protected def id : C ⥤ C :=
{ obj := λ X, X,
map := λ _ _ f, f }
notation `𝟭` := functor.id -- Type this as `\sb1`
instance : inhabited (C ⥤ C) := ⟨functor.id C⟩
variable {C}
@[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl
@[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl
end
section
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
`F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`).
-/
def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E :=
{ obj := λ X, G.obj (F.obj X),
map := λ _ _ f, G.map (F.map f) }
infixr ` ⋙ `:80 := comp
@[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl
@[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) :
(F ⋙ G).map f = G.map (F.map f) := rfl
-- These are not simp lemmas because rewriting along equalities between functors
-- is not necessarily a good idea.
-- Natural isomorphisms are also provided in `whiskering.lean`.
protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl
protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl
@[simp] lemma map_dite (F : C ⥤ D) {X Y : C} {P : Prop} [decidable P]
(f : P → (X ⟶ Y)) (g : ¬P → (X ⟶ Y)) :
F.map (if h : P then f h else g h) = if h : P then F.map (f h) else F.map (g h) :=
by { split_ifs; refl, }
end
@[mono] lemma monotone {α β : Type*} [preorder α] [preorder β] (F : α ⥤ β) :
monotone F.obj :=
λ a b h, le_of_hom (F.map (hom_of_le h))
end functor
end category_theory
|
128275e2344bda284923d550d6df2159574493be | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/analysis/calculus/local_extr.lean | efdf9cb714937ddd3ce2486b0f1397314bba37da | [
"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 | 16,310 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.local_extr
import analysis.calculus.deriv
/-!
# Local extrema of smooth functions
## Main definitions
In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`.
This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields.
This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or
[Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions).
## Main statements
For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`,
and `(f)deriv` instead of `has_fderiv`.
* `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum
of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent
cone of `s` at `a`.
* `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both
`y` and `-y` belong to the positive tangent cone, then `f' y = 0`.
* `is_local_max.has_fderiv_at_eq_zero` :
[Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)),
the derivative of a differentiable function at a local extremum point equals zero.
* `exists_has_deriv_at_eq_zero` :
[Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous
on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`.
## Implementation notes
For each mathematical fact we prove several versions of its formalization:
* for maxima and minima;
* using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`.
For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible
due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions.
## References
* [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points));
* [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem);
* [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone);
## Tags
local extremum, Fermat's Theorem, Rolle's Theorem
-/
universes u v
open filter set
open_locale topological_space classical
section vector_space
variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E}
{f' : E →L[ℝ] ℝ}
/-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at`
is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at`
as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/
def pos_tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧
(tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) :=
begin
rintros s t hst y ⟨c, d, hd, hc, hcd⟩,
exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩
end
lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) :
y - x ∈ pos_tangent_cone_at s x :=
begin
let c := λn:ℕ, (2:ℝ)^n,
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩,
show x + d n ∈ segment x y,
{ rw segment_eq_image,
refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩,
{ rw inv_nonneg, apply pow_nonneg, norm_num },
{ apply inv_le_one, apply one_le_pow_of_one_le, norm_num },
{ simp only [d, sub_smul, smul_sub, one_smul], abel } },
show tendsto c at_top at_top,
{ exact tendsto_pow_at_top_at_top_of_one_lt one_lt_two },
show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)),
{ have : (λ (n : ℕ), c n • d n) = (λn, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ :=
eq_univ_iff_forall.2
begin
assume x,
rw [← add_sub_cancel x a],
exact mem_pos_tangent_cone_at_of_segment_subset (subset_univ _)
end
/-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
f' y ≤ 0 :=
begin
rcases hy with ⟨c, d, hd, hc, hcd⟩,
have hc' : tendsto (λ n, ∥c n∥) at_top at_top,
from tendsto_at_top_mono (λ n, le_abs_self _) hc,
refine le_of_tendsto (hf.lim at_top hd hc' hcd) _,
replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)),
from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd),
by rwa tendsto_principal⟩,
rw [add_zero] at hd,
replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h),
replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))),
filter_upwards [h, hc],
simp only [mem_set_of_eq, smul_eq_mul, mem_preimage, subset_def],
assume n hnf hn,
exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf)
end
/-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y ≤ 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $
by simpa using h.has_fderiv_within_at_nonpos hf hy'
/-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) :
0 ≤ f' y :=
by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy
/-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `0 ≤ f' y`. -/
lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) :
(0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/
lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a)
(hy' : -y ∈ pos_tangent_cone_at s a) :
f' y = 0 :=
by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy'
/-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a)
{y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) :
(fderiv_within ℝ f s a : E → ℝ) y = 0 :=
if hf : differentiable_within_at ℝ f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
begin
ext y,
apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at;
rw pos_tangent_cone_at_univ; apply mem_univ
end
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) :
has_fderiv_at f f' a → f' = 0 :=
h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 :=
h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero
end vector_space
section real
variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ}
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
by simpa using continuous_linear_map.ext_iff.1
(h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1
/-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg
/-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 :=
if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) :
has_deriv_at f f' a → f' = 0 :=
h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero
/-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 :=
h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero
end real
section Rolle
variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b)
include hab hfc hfI
/-- A continuous function on a closed interval with `f a = f b` takes either its maximum
or its minimum value at a point in the interior of the interval. -/
lemma exists_Ioo_extr_on_Icc : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c :=
begin
have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab),
-- Consider absolute min and max points
obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x,
from compact_Icc.exists_forall_le ne hfc,
obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C,
from compact_Icc.exists_forall_ge ne hfc,
by_cases hc : f c = f a,
{ by_cases hC : f C = f a,
{ have : ∀ x ∈ Icc a b, f x = f a,
from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx),
-- `f` is a constant, so we can take any point in `Ioo a b`
rcases dense hab with ⟨c', hc'⟩,
refine ⟨c', hc', or.inl _⟩,
assume x hx,
rw [mem_set_of_eq, this x hx, ← hC],
exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ },
{ refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] } },
{ refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩,
exacts [λ h, by rw h, λ h, by rw [h, hfI]] }
end
/-- A continuous function on a closed interval with `f a = f b` has a local extremum at some
point of the corresponding open interval. -/
lemma exists_local_extr_Ioo : ∃ c ∈ Ioo a b, is_local_extr f c :=
let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI
in ⟨c, cmem, hc.is_local_extr $ mem_nhds_sets_iff.2 ⟨Ioo a b, Ioo_subset_Icc_self, is_open_Ioo, cmem⟩⟩
/-- Rolle's Theorem `has_deriv_at` version -/
lemma exists_has_deriv_at_eq_zero (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) :
∃ c ∈ Ioo a b, f' c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩
/-- Rolle's Theorem `deriv` version -/
lemma exists_deriv_eq_zero : ∃ c ∈ Ioo a b, deriv f c = 0 :=
let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in
⟨c, cmem, hc.deriv_eq_zero⟩
omit hfc hfI
variables {f f'}
lemma exists_has_deriv_at_eq_zero' {l : ℝ}
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l))
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) :
∃ c ∈ Ioo a b, f' c = 0 :=
begin
have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at,
have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb,
obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c,
{ apply exists_local_extr_Ioo _ hab hcont,
rw eq_lim_at_right_extend_from_Ioo hab hfb,
exact eq_lim_at_left_extend_from_Ioo hab hfa },
use [c, hc],
apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc),
rw eventually_eq_iff_exists_mem,
exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩
end
lemma exists_deriv_eq_zero' {l : ℝ}
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) :
∃ c ∈ Ioo a b, deriv f c = 0 :=
classical.by_cases
(assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x,
show ∃ c ∈ Ioo a b, deriv f c = 0,
from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at))
(assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x,
have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h },
let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩)
end Rolle
|
31ec7fc697c3f5bea780c9aa1b0d5358c034d8d8 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/category_theory/monad/equiv_mon.lean | 267f30b02f34f485e307cd26391461e0f7f4bc24 | [
"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 | 3,285 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.monad.bundled
import category_theory.monoidal.End
import category_theory.monoidal.internal
import category_theory.category.Cat
/-!
# The equivalence between `Monad C` and `Mon_ (C ⥤ C)`.
A monad "is just" a monoid in the category of endofunctors.
# Definitions/Theorems
1. `to_Mon` associates a monoid object in `C ⥤ C` to any monad on `C`.
2. `Monad_to_Mon` is the functorial version of `to_Mon`.
3. `of_Mon` associates a monad on `C` to any monoid object in `C ⥤ C`.
4. `Monad_Mon_equiv` is the equivalence between `Monad C` and `Mon_ (C ⥤ C)`.
-/
namespace category_theory
open category
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u} [category.{v} C]
namespace Monad
local attribute [instance, reducible] endofunctor_monoidal_category
/-- To every `Monad C` we associated a monoid object in `C ⥤ C`.-/
@[simps]
def to_Mon : Monad C → Mon_ (C ⥤ C) := λ M,
{ X := M.func,
one := η_ _,
mul := μ_ _ }
variable (C)
/-- Passing from `Monad C` to `Mon_ (C ⥤ C)` is functorial. -/
@[simps]
def Monad_to_Mon : Monad C ⥤ Mon_ (C ⥤ C) :=
{ obj := to_Mon,
map := λ _ _ f, { hom := f.to_nat_trans } }
variable {C}
/-- To every monoid object in `C ⥤ C` we associate a `Monad C`. -/
@[simps]
def of_Mon : Mon_ (C ⥤ C) → Monad C := λ M,
{ func := M.X,
str :=
{ η := M.one,
μ := M.mul,
assoc' := begin
intro X,
rw [←nat_trans.hcomp_id_app, ←nat_trans.comp_app],
simp,
end,
left_unit' := begin
intro X,
rw [←nat_trans.id_hcomp_app, ←nat_trans.comp_app, M.mul_one],
refl,
end,
right_unit' := begin
intro X,
rw [←nat_trans.hcomp_id_app, ←nat_trans.comp_app, M.one_mul],
refl,
end } }
variable (C)
/-- Passing from `Mon_ (C ⥤ C)` to `Monad C` is functorial. -/
@[simps]
def Mon_to_Monad : Mon_ (C ⥤ C) ⥤ Monad C :=
{ obj := of_Mon,
map := λ _ _ f,
{ app_η' := begin
intro X,
erw [←nat_trans.comp_app, f.one_hom],
refl,
end,
app_μ' := begin
intro X,
erw [←nat_trans.comp_app, f.mul_hom],
finish,
end,
..f.hom } }
variable {C}
/-- Isomorphism of functors used in `Monad_Mon_equiv` -/
@[simps]
def of_to_mon_end_iso : Mon_to_Monad C ⋙ Monad_to_Mon C ≅ 𝟭 _ :=
{ hom := { app := λ _, { hom := 𝟙 _ } },
inv := { app := λ _, { hom := 𝟙 _ } } }
/-- Isomorphism of functors used in `Monad_Mon_equiv` -/
@[simps]
def to_of_mon_end_iso : Monad_to_Mon C ⋙ Mon_to_Monad C ≅ 𝟭 _ :=
{ hom := { app := λ _, { app := λ _, 𝟙 _ } },
inv := { app := λ _, { app := λ _, 𝟙 _ } } }
variable (C)
/-- Oh, monads are just monoids in the category of endofunctors (equivalence of categories). -/
@[simps]
def Monad_Mon_equiv : (Monad C) ≌ (Mon_ (C ⥤ C)) :=
{ functor := Monad_to_Mon _,
inverse := Mon_to_Monad _,
unit_iso := to_of_mon_end_iso.symm,
counit_iso := of_to_mon_end_iso }
-- Sanity check
example (A : Monad C) {X : C} : ((Monad_Mon_equiv C).unit_iso.app A).hom.app X = 𝟙 _ := rfl
end Monad
end category_theory
|
79204d8b2b6b21566d6d7d73d630901074cd7f38 | 0b3933727d99a2f351f5dbe6e24716bb786a6649 | /src/sesh/ren_sub.lean | 118fd55653b3b75e194ce0db4945cbd9dbf2b995 | [] | no_license | Vtec234/lean-sesh | 1e770858215279f65aba92b4782b483ab4f09353 | d11d7bb0599406e27d3a4d26242aec13d639ecf7 | refs/heads/master | 1,587,497,515,696 | 1,558,362,223,000 | 1,558,362,223,000 | 169,809,439 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,252 | lean | /- Introduces renaming and substitution on terms and values. -/
import sesh.term
/- The type of renaming functions which transport indices
from one precontext to another. -/
def ren_fn (γ δ) := Π (A: tp), γ ∋ A → δ ∋ A
namespace ren_fn
open debrujin_idx
/- A renaming function which moves every index/variable up once. -/
@[reducible]
def lift_once {γ: precontext} (B: tp): ren_fn γ (B::γ) := (λ A, @SVar γ A B)
@[reducible]
def lift_over (γ: precontext) (A B: tp): ren_fn (A::γ) (A::B::γ)
| _ (ZVar _ _) := ZVar _ _
| _ (SVar _ x) := SVar _ (SVar _ x)
@[reducible]
def lift_over_two (γ: precontext) (A B C: tp): ren_fn (A::B::γ) (A::B::C::γ)
| _ (ZVar _ _) := ZVar _ _
| _ (SVar _ (ZVar _ _)) := SVar _ (ZVar _ _)
| _ (SVar _ (SVar _ x)) := SVar _ (SVar _ (SVar _ x))
/- The extended ren_fn is identical, but has an extended precontext in the type. -/
def ext {γ δ} (ρ: ren_fn γ δ) (A: tp): ren_fn (A::γ) (A::δ)
| _ (ZVar _ B) := (ZVar _ B)
| B (SVar C x) := SVar C (ρ B x)
@[simp] lemma ext_zvar {γ δ} {ρ: ren_fn γ δ} {A: tp}
: ext ρ A _ (ZVar _ A) = (ZVar _ A) := by refl
@[unfold_] lemma ext_svar {γ δ} {ρ: ren_fn γ δ} {A B: tp} {x: γ ∋ B}
: ext ρ A B (SVar A x) = SVar A (ρ B x) := by refl
end ren_fn
namespace term
/- Applies the renaming ρ to a term M. The resulting term
is the same one and has the same type, but its context
is Γ times the identity matrix. This has the effect of
simply appending one or more zero-resourced bindings to
Γ, and since we treat those as non-existent, the context
is essentially the same. -/
def rename: Π {γ δ: precontext} {Γ: context γ} {A: tp}
(ρ: ren_fn γ δ)
(Δ: context δ)
(M: term Γ A)
(h: auto_param (Δ = Γ ⊛ (λ B x, matrix.identity δ B $ ρ B x)) ``solve_context),
term Δ A
/- In most cases we have to carry through a proof
that the context of the resulting term is the right
one. In cases where variable bindings are introduced,
the body under the binder also has to be `convert`ed
by constructing a proof that the lifted context is still
the right one. -/
| _ _ _ _ ρ _ (Var Γ x _) h := Var _ (ρ _ x)
| _ _ _ _ ρ _ (Abs e) h := Abs (rename (ρ.ext _) _ e)
| _ _ _ _ ρ _ (App _ M N _) h := App _ (rename ρ _ M) (rename ρ _ N)
| _ _ _ _ _ _ (Unit _ _) h := Unit _
| _ _ _ _ ρ _ (LetUnit _ M N _) h := LetUnit _ (rename ρ _ M) (rename ρ _ N)
| _ _ _ _ ρ _ (Pair _ M N _) h := Pair _ (rename ρ _ M) (rename ρ _ N)
| _ δ _ _ ρ _ (LetPair Γ M N _) h := LetPair
_
(rename ρ _ M)
(rename ((ρ.ext _).ext _) _ N)
| _ δ _ _ ρ _ (Case Γ L M N _) h := Case
_
(rename ρ _ L)
(rename (ρ.ext _) _ M)
(rename (ρ.ext _) _ N)
| _ _ _ _ ρ _ (Send _ M N _) h := Send _ (rename ρ _ M) (rename ρ _ N)
| _ _ _ _ ρ _ (Inl B e) h := Inl B (rename ρ _ e)
| _ _ _ _ ρ _ (Inr A e) h := Inr A (rename ρ _ e)
| _ _ _ _ ρ _ (Fork e) h := Fork (rename ρ _ e)
| _ _ _ _ ρ _ (Recv e) h := Recv (rename ρ _ e)
| _ _ _ _ ρ _ (Wait e) h := Wait (rename ρ _ e)
def lift_once {γ: precontext} {Γ: context γ} {A: tp}
(M: term Γ A)
(B: tp)
: term (⟦0⬝B⟧::Γ) A :=
rename (ren_fn.lift_once B) _ M
end term
namespace value
lemma rename:
∀ {γ δ}
{Γ: context γ} {A: tp}
{V: term Γ A}
(h: value V)
(ρ: ren_fn γ δ),
value (term.rename ρ _ V (by solve_context))
| _ _ _ _ _ (VVar _ x _) ρ := VVar _ (ρ _ x)
| _ _ _ _ _ (VAbs M) ρ :=
VAbs $ term.rename (ρ.ext _) _ M
| _ _ _ _ _ (VUnit _ _) ρ := VUnit _
| _ _ _ _ _ (VPair _ _ hM hN) ρ :=
VPair
_ (by solve_context)
(hM.rename ρ)
(hN.rename ρ)
| _ _ _ _ _ (VInl B hM) ρ := VInl B (hM.rename ρ)
| _ _ _ _ _ (VInr B hM) ρ := VInr B (hM.rename ρ)
end value
/- For every variable x in γ, (σ _ x) where (σ: sub_fn Ξ) returns
the term which should be substituted into that variable. The
resource requirements of that term can be extracted out of
the matrix Ξ. -/
def sub_fn {γ δ} (Ξ: matrix γ δ) :=
Π (A: tp) (x: γ ∋ A), term (Ξ A x) A
namespace sub_fn
open debrujin_idx
open term
/- Extends the substitution given by Ξ into one over contexts extended with T. -/
def ext {γ δ} {Ξ: matrix γ δ} (σ: sub_fn Ξ) (A: tp)
: sub_fn (Ξ.ext A)
| _ (ZVar _ A) := Var _ (ZVar _ A)
| B (SVar _ x) := rename (ren_fn.lift_once A) _ (σ B x)
end sub_fn
namespace term
open debrujin_idx
/- Applies simultaneous substitution, replacing all variables
in a term with whatever the matrix Ξ contains. -/
def subst
: Π {γ δ} {Γ: context γ} {Ξ: matrix γ δ} {A}
(σ: sub_fn Ξ)
(Δ: context δ)
(M: term Γ A)
(h: auto_param (Δ = Γ ⊛ Ξ) ``solve_context),
term Δ A
| _ _ _ _ _ σ _ (Var _ x _) _ := cast (by solve_context) $ σ _ x
| _ _ _ _ _ σ _ (Abs M) _ := Abs $ subst (σ.ext _) _ M
| _ _ _ _ _ σ _ (App _ M N _) _ := App _ (subst σ _ M) (subst σ _ N)
| _ _ _ _ _ σ _ (Unit _ _) _ := Unit _
| _ _ _ _ _ σ _ (LetUnit _ M N _) _ := LetUnit _ (subst σ _ M) (subst σ _ N)
| _ _ _ _ _ σ _ (Pair _ M N _) _ := Pair _ (subst σ _ M) (subst σ _ N)
| _ _ Γ Ξ _ σ _ (LetPair _ M N _) _ :=
LetPair
_
(subst σ _ M)
(subst ((σ.ext _).ext _) _ N)
| _ _ _ _ _ σ _ (Case _ L M N _) _ := Case
_
(subst σ _ L)
(subst (σ.ext _) _ M)
(subst (σ.ext _) _ N)
| _ _ _ _ _ σ _ (Send _ M N _) _ := Send _ (subst σ _ M) (subst σ _ N)
| _ _ _ _ _ σ _ (Inl B M) _ := Inl B (subst σ _ M)
| _ _ _ _ _ σ _ (Inr A M) _ := Inr A (subst σ _ M)
| _ _ _ _ _ σ _ (Fork M) _ := Fork (subst σ _ M)
| _ _ _ _ _ σ _ (Recv M) _ := Recv (subst σ _ M)
| _ _ _ _ _ σ _ (Wait M) _ := Wait (subst σ _ M)
def ssub_mat {γ} (Γ: context γ) (A: tp)
: matrix (A::γ) γ
| _ (ZVar _ _) := Γ
| B (SVar _ x) := matrix.identity γ B x
def ssub_sub {γ} {A: tp} (Γ: context γ) (M: term Γ A)
: sub_fn (ssub_mat Γ A)
| _ (ZVar _ _) := M
| _ (SVar _ x) := Var _ x (begin unfold ssub_mat, simp end)
def ssubst {γ} {Γ Γ': context γ} {A B: tp} {π: mult}
(Δ: context γ)
(e: term (⟦π⬝B⟧::Γ) A) -- The term being sub'd into requires π Bs
(s: term Γ' B) -- The sub'd term requires Γ'
(_: auto_param (Δ = Γ + π•Γ') ``solve_context)
-------------------
: term Δ A := subst (ssub_sub Γ' s) _ e
(begin
simp with unfold_, unfold ssub_mat, solve_context,
end)
def dsub_mat {γ} (Γ₁ Γ₂: context γ) (A B: tp)
: matrix (A::B::γ) γ
| _ (ZVar _ _) := Γ₁
| _ (SVar _ $ ZVar _ _) := Γ₂
| C (SVar _ $ SVar _ x) := matrix.identity γ C x
def dsub_sub {γ} {A B: tp} (Γ₁ Γ₂: context γ) (M: term Γ₁ A) (N: term Γ₂ B)
: sub_fn (dsub_mat Γ₁ Γ₂ A B)
| _ (ZVar _ _) := M
| _ (SVar _ $ ZVar _ _) := N
| _ (SVar _ $ SVar _ x) := Var _ x (begin unfold dsub_mat, simp end)
def dsubst {γ} {Γ Γ₁ Γ₂: context γ} {A B₁ B₂: tp} {π₁ π₂: mult}
(Δ: context γ)
(e: term (⟦π₁⬝B₁⟧::⟦π₂⬝B₂⟧::Γ) A)
(s₁: term Γ₁ B₁)
(s₂: term Γ₂ B₂)
(_: auto_param (Δ = Γ + π₁•Γ₁ + π₂•Γ₂) ``solve_context)
----------------
: term Δ A :=
subst (dsub_sub Γ₁ Γ₂ s₁ s₂) _ e
(begin
simp with unfold_, unfold dsub_mat, solve_context,
end)
end term
|
d58b261aeb90cb33e4bdeb055df5cc59ed2d7965 | c062f1c97fdef9ac746f08754e7d766fd6789aa9 | /algebra/lattice/basic.lean | 41469946a55028971c061a3514fc3e3cb57bc003 | [] | no_license | emberian/library_dev | 00c7a985b21bdebe912f4127a363f2874e1e7555 | f3abd7db0238edc18a397540e361a1da2f51503c | refs/heads/master | 1,624,153,474,804 | 1,490,147,180,000 | 1,490,147,180,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,711 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy.
-/
import ..order
universes u v w
/- TODO: automatic construction of dual definitions / theorems -/
namespace lattice
reserve infixl ` ⊓ `:70
reserve infixl ` ⊔ `:65
class has_top (α : Type u) := (top : α)
class has_bot (α : Type u) := (bot : α)
class has_sup (α : Type u) := (sup : α → α → α)
class has_inf (α : Type u) := (inf : α → α → α)
class has_imp (α : Type u) := (imp : α → α → α) /- Better name -/
def top {α : Type u} [has_top α] : α := has_top.top α
def bot {α : Type u} [has_bot α] : α := has_bot.bot α
def sup {α : Type u} [has_sup α] : α → α → α := has_sup.sup
def inf {α : Type u} [has_inf α] : α → α → α := has_inf.inf
def imp {α : Type u} [has_imp α] : α → α → α := has_imp.imp
infix ⊔ := sup
infix ⊓ := inf
notation `⊤` := top
notation `⊥` := bot
class order_top (α : Type u) extends has_top α, weak_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables {α : Type u} [order_top α] {a : α}
lemma le_top : a ≤ top :=
order_top.le_top a
lemma top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_antisymm le_top h
lemma eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨take eq, eq^.symm ▸ le_refl ⊤, top_unique⟩
end order_top
class order_bot (α : Type u) extends has_bot α, weak_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables {α : Type u} [order_bot α] {a : α}
lemma bot_le : ⊥ ≤ a := order_bot.bot_le a
lemma bot_unique (h : a ≤ ⊥) : a = ⊥ :=
le_antisymm h bot_le
lemma eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨take eq, eq^.symm ▸ le_refl ⊥, bot_unique⟩
end order_bot
class semilattice_sup (α : Type u) extends has_sup α, weak_order α :=
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
section semilattice_sup
variables {α : Type u} [semilattice_sup α] {a b c d : α}
lemma le_sup_left : a ≤ a ⊔ b :=
semilattice_sup.le_sup_left a b
lemma le_sup_right : b ≤ a ⊔ b :=
semilattice_sup.le_sup_right a b
lemma sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
semilattice_sup.sup_le a b c
lemma le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b :=
le_trans h le_sup_left
lemma le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b :=
le_trans h le_sup_right
lemma sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩,
take ⟨h₁, h₂⟩, sup_le h₁ h₂⟩
lemma sup_of_le_left (h : b ≤ a) : a ⊔ b = a :=
le_antisymm (sup_le (le_refl _) h) le_sup_left
lemma sup_of_le_right (h : a ≤ b) : a ⊔ b = b :=
le_antisymm (sup_le h (le_refl _)) le_sup_right
lemma sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d :=
sup_le (le_sup_left_of_le h₁) (le_sup_right_of_le h₂)
lemma le_of_sup_eq (h : a ⊔ b = b) : a ≤ b :=
h ▸ le_sup_left
@[simp]
lemma sup_idem : a ⊔ a = a :=
sup_of_le_left (le_refl _)
lemma sup_comm : a ⊔ b = b ⊔ a :=
have ∀{a b : α}, a ⊔ b ≤ b ⊔ a,
from take a b, sup_le le_sup_right le_sup_left,
le_antisymm this this
instance semilattice_sup_to_is_commutative [semilattice_sup α] : is_commutative α sup :=
⟨@sup_comm _ _⟩
lemma sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) :=
le_antisymm
(sup_le (sup_le le_sup_left (le_sup_right_of_le le_sup_left)) (le_sup_right_of_le le_sup_right))
(sup_le (le_sup_left_of_le le_sup_left) (sup_le (le_sup_left_of_le le_sup_right) le_sup_right))
instance semilattice_sup_to_is_associative [semilattice_sup α] : is_associative α sup :=
⟨@sup_assoc _ _⟩
end semilattice_sup
class semilattice_inf (α : Type u) extends has_inf α, weak_order α :=
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
section semilattice_inf
variables {α : Type u} [semilattice_inf α] {a b c d : α}
lemma inf_le_left : a ⊓ b ≤ a :=
semilattice_inf.inf_le_left a b
lemma inf_le_right : a ⊓ b ≤ b :=
semilattice_inf.inf_le_right a b
lemma le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c :=
semilattice_inf.le_inf a b c
lemma inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_left h
lemma inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_right h
lemma le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c :=
⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩,
take ⟨h₁, h₂⟩, le_inf h₁ h₂⟩
lemma inf_of_le_left (h : a ≤ b) : a ⊓ b = a :=
le_antisymm inf_le_left (le_inf (le_refl _) h)
lemma inf_of_le_right (h : b ≤ a) : a ⊓ b = b :=
le_antisymm inf_le_right (le_inf h (le_refl _))
lemma inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d :=
le_inf (inf_le_left_of_le h₁) (inf_le_right_of_le h₂)
lemma le_of_inf_eq (h : a ⊓ b = a) : a ≤ b :=
h ▸ inf_le_right
@[simp]
lemma inf_idem : a ⊓ a = a :=
inf_of_le_left (le_refl _)
lemma inf_comm : a ⊓ b = b ⊓ a :=
have ∀{a b : α}, a ⊓ b ≤ b ⊓ a,
from take a b, le_inf inf_le_right inf_le_left,
le_antisymm this this
instance semilattice_inf_to_is_commutative [semilattice_inf α] : is_commutative α inf :=
⟨@inf_comm _ _⟩
lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) :=
le_antisymm
(le_inf (inf_le_left_of_le inf_le_left) (le_inf (inf_le_left_of_le inf_le_right) inf_le_right))
(le_inf (le_inf inf_le_left (inf_le_right_of_le inf_le_left)) (inf_le_right_of_le inf_le_right))
instance semilattice_inf_to_is_associative [semilattice_inf α] : is_associative α inf :=
⟨@inf_assoc _ _⟩
end semilattice_inf
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
section semilattice_sup_top
variables {α : Type u} [semilattice_sup_top α] {a : α}
@[simp]
lemma top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp]
lemma sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
section semilattice_sup_bot
variables {α : Type u} [semilattice_sup_bot α] {a b : α}
@[simp]
lemma bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp]
lemma sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp]
lemma sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by simp [eq_bot_iff, sup_le_iff]
end semilattice_sup_bot
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
section semilattice_inf_top
variables {α : Type u} [semilattice_inf_top α] {a b : α}
@[simp]
lemma top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp]
lemma inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp]
lemma inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by simp [eq_top_iff, le_inf_iff]
end semilattice_inf_top
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
section semilattice_inf_bot
variables {α : Type u} [semilattice_inf_bot α] {a : α}
@[simp]
lemma bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp]
lemma inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/- Lattices -/
class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α
section lattice
variables {α : Type u} [lattice α] {a b c d : α}
/- Distributivity laws -/
/- TODO: better names? -/
lemma sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) :=
sup_le (le_inf le_sup_left le_sup_left) $
le_inf (inf_le_left_of_le le_sup_right) (inf_le_right_of_le le_sup_right)
lemma le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) :=
le_inf (sup_le inf_le_left inf_le_left) $
sup_le (le_sup_left_of_le inf_le_right) (le_sup_right_of_le inf_le_right)
lemma inf_sup_self : a ⊓ (a ⊔ b) = a :=
le_antisymm inf_le_left (le_inf (le_refl a) le_sup_left)
lemma sup_inf_self : a ⊔ (a ⊓ b) = a :=
le_antisymm (sup_le (le_refl a) inf_le_left) le_sup_left
end lattice
/- Lattices derived from linear orders -/
instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α :=
{ o with
sup := max,
le_sup_left := le_max_left,
le_sup_right := le_max_right,
sup_le := take a b c, max_le,
inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := take a b c, le_min }
end lattice
|
29fac275c9bbda9aef92d201015cc401cb1871eb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/group_power/basic.lean | 281fa0372ef7eed776e90808c9faf0db9f8e87cc | [
"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 | 12,048 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.divisibility.basic
import algebra.group.commute
import algebra.group.type_tags
/-!
# Power operations on monoids and groups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The power operation on monoids and groups.
We separate this from group, because it depends on `ℕ`,
which in turn depends on other parts of algebra.
This module contains lemmas about `a ^ n` and `n • a`, where `n : ℕ` or `n : ℤ`.
Further lemmas can be found in `algebra.group_power.lemmas`.
The analogous results for groups with zero can be found in `algebra.group_with_zero.power`.
## Notation
- `a ^ n` is used as notation for `has_pow.pow a n`; in this file `n : ℕ` or `n : ℤ`.
- `n • a` is used as notation for `has_smul.smul n a`; in this file `n : ℕ` or `n : ℤ`.
## Implementation details
We adopt the convention that `0^0 = 1`.
-/
universes u v w x y z u₁ u₂
variables {α : Type*} {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z}
{R : Type u₁} {S : Type u₂}
/-!
### Commutativity
First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about
`pow` and/or `nsmul` and will be useful later in this file.
-/
section has_pow
variables [has_pow M ℕ]
@[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) :
a ^ (if P then b else c) = if P then a ^ b else a ^ c :=
by split_ifs; refl
@[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) :
(if P then a else b) ^ c = if P then a ^ c else b ^ c :=
by split_ifs; refl
end has_pow
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp, to_additive one_nsmul]
theorem pow_one (a : M) : a^1 = a :=
by rw [pow_succ, pow_zero, mul_one]
/-- Note that most of the lemmas about powers of two refer to it as `sq`. -/
@[to_additive two_nsmul, nolint to_additive_doc]
theorem pow_two (a : M) : a^2 = a * a :=
by rw [pow_succ, pow_one]
alias pow_two ← sq
theorem pow_three' (a : M) : a^3 = a * a * a := by rw [pow_succ', pow_two]
theorem pow_three (a : M) : a^3 = a * (a * a) := by rw [pow_succ, pow_two]
@[to_additive]
theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n
@[to_additive add_nsmul]
theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one],
rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]]
@[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) :
a ^ (if P then 1 else 0) = if P then a else 1 :=
by simp
-- the attributes are intentionally out of order. `smul_zero` proves `nsmul_zero`.
@[to_additive nsmul_zero, simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 :=
by induction n with n ih; [exact pow_zero _, rw [pow_succ, ih, one_mul]]
@[to_additive mul_nsmul']
theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n :=
begin
induction n with n ih,
{ rw [nat.mul_zero, pow_zero, pow_zero] },
{ rw [nat.mul_succ, pow_add, pow_succ', ih] }
end
@[to_additive nsmul_left_comm]
lemma pow_right_comm (a : M) (m n : ℕ) : (a^m)^n = (a^n)^m :=
by rw [←pow_mul, nat.mul_comm, pow_mul]
@[to_additive mul_nsmul]
theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [nat.mul_comm, pow_mul]
@[to_additive nsmul_add_sub_nsmul]
theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n :=
by rw [←pow_add, nat.add_comm, nat.sub_add_cancel h]
@[to_additive sub_nsmul_nsmul_add]
theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n :=
by rw [←pow_add, nat.sub_add_cancel h]
/-- If `x ^ n = 1`, then `x ^ m` is the same as `x ^ (m % n)` -/
@[to_additive nsmul_eq_mod_nsmul "If `n • x = 0`, then `m • x` is the same as `(m % n) • x`"]
lemma pow_eq_pow_mod {M : Type*} [monoid M] {x : M} (m : ℕ) {n : ℕ} (h : x ^ n = 1) :
x ^ m = x ^ (m % n) :=
begin
have t := congr_arg (λ a, x ^ a) ((nat.add_comm _ _).trans (nat.mod_add_div _ _)).symm,
dsimp at t,
rw [t, pow_add, pow_mul, h, one_pow, one_mul],
end
@[to_additive bit0_nsmul]
theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
@[to_additive bit1_nsmul]
theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
@[to_additive]
theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m :=
commute.pow_pow_self a m n
@[to_additive]
lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n :=
nat.rec_on n (by simp only [pow_zero, one_mul]) $ λ n ihn,
by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm]
@[to_additive bit0_nsmul']
theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n :=
by rw [pow_bit0, (commute.refl a).mul_pow]
@[to_additive bit1_nsmul']
theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a :=
by rw [bit1, pow_succ', pow_bit0']
@[to_additive]
lemma pow_mul_pow_eq_one {a b : M} (n : ℕ) (h : a * b = 1) :
a ^ n * b ^ n = 1 :=
begin
induction n with n hn,
{ simp },
{ calc a ^ n.succ * b ^ n.succ = a ^ n * a * (b * b ^ n) : by rw [pow_succ', pow_succ]
... = a ^ n * (a * b) * b ^ n : by simp only [mul_assoc]
... = 1 : by simp [h, hn] }
end
lemma dvd_pow {x y : M} (hxy : x ∣ y) :
∀ {n : ℕ} (hn : n ≠ 0), x ∣ y^n
| 0 hn := (hn rfl).elim
| (n + 1) hn := by { rw pow_succ, exact hxy.mul_right _ }
alias dvd_pow ← has_dvd.dvd.pow
lemma dvd_pow_self (a : M) {n : ℕ} (hn : n ≠ 0) : a ∣ a^n :=
dvd_rfl.pow hn
end monoid
/-!
### Commutative (additive) monoid
-/
section comm_monoid
variables [comm_monoid M] [add_comm_monoid A]
@[to_additive nsmul_add]
theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n :=
(commute.all a b).mul_pow n
/-- The `n`th power map on a commutative monoid for a natural `n`, considered as a morphism of
monoids. -/
@[to_additive "Multiplication by a natural `n` on a commutative additive
monoid, considered as a morphism of additive monoids.", simps]
def pow_monoid_hom (n : ℕ) : M →* M :=
{ to_fun := (^ n),
map_one' := one_pow _,
map_mul' := λ a b, mul_pow a b n }
-- the below line causes the linter to complain :-/
-- attribute [simps] pow_monoid_hom nsmul_add_monoid_hom
end comm_monoid
section div_inv_monoid
variable [div_inv_monoid G]
open int
@[simp, to_additive one_zsmul]
theorem zpow_one (a : G) : a ^ (1:ℤ) = a :=
by { convert pow_one a using 1, exact zpow_coe_nat a 1 }
@[to_additive two_zsmul]
theorem zpow_two (a : G) : a ^ (2 : ℤ) = a * a :=
by { convert pow_two a using 1, exact zpow_coe_nat a 2 }
@[to_additive neg_one_zsmul]
theorem zpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ :=
(zpow_neg_succ_of_nat x 0).trans $ congr_arg has_inv.inv (pow_one x)
@[to_additive]
theorem zpow_neg_coe_of_pos (a : G) : ∀ {n : ℕ}, 0 < n → a ^ -(n:ℤ) = (a ^ n)⁻¹
| (n+1) _ := zpow_neg_succ_of_nat _ _
end div_inv_monoid
section division_monoid
variables [division_monoid α] {a b : α}
@[simp, to_additive] lemma inv_pow (a : α) : ∀ n : ℕ, (a⁻¹) ^ n = (a ^ n)⁻¹
| 0 := by rw [pow_zero, pow_zero, inv_one]
| (n + 1) := by rw [pow_succ', pow_succ, inv_pow, mul_inv_rev]
-- the attributes are intentionally out of order. `smul_zero` proves `zsmul_zero`.
@[to_additive zsmul_zero, simp] lemma one_zpow : ∀ (n : ℤ), (1 : α) ^ n = 1
| (n : ℕ) := by rw [zpow_coe_nat, one_pow]
| -[1+ n] := by rw [zpow_neg_succ_of_nat, one_pow, inv_one]
@[simp, to_additive neg_zsmul] lemma zpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := div_inv_monoid.zpow_neg' _ _
| 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp }
| -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_inv, ← zpow_coe_nat], refl }
@[to_additive neg_one_zsmul_add]
lemma mul_zpow_neg_one (a b : α) : (a * b) ^ (-1 : ℤ) = b ^ (-1 : ℤ) * a ^ (-1 : ℤ) :=
by simp_rw [zpow_neg_one, mul_inv_rev]
@[to_additive zsmul_neg] lemma inv_zpow (a : α) : ∀ n : ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, inv_pow]
| -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_pow]
@[simp, to_additive zsmul_neg']
lemma inv_zpow' (a : α) (n : ℤ) : a⁻¹ ^ n = a ^ (-n) := by rw [inv_zpow, zpow_neg]
@[to_additive nsmul_zero_sub]
lemma one_div_pow (a : α) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by simp_rw [one_div, inv_pow]
@[to_additive zsmul_zero_sub]
lemma one_div_zpow (a : α) (n : ℤ) : (1 / a) ^ n = 1 / a ^ n := by simp_rw [one_div, inv_zpow]
@[to_additive add_commute.zsmul_add]
protected lemma commute.mul_zpow (h : commute a b) : ∀ (i : ℤ), (a * b) ^ i = a ^ i * b ^ i
| (n : ℕ) := by simp [h.mul_pow n]
| -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev]
end division_monoid
section division_comm_monoid
variables [division_comm_monoid α]
@[to_additive zsmul_add] lemma mul_zpow (a b : α) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n :=
(commute.all a b).mul_zpow
@[simp, to_additive nsmul_sub] lemma div_pow (a b : α) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_pow, inv_pow]
@[simp, to_additive zsmul_sub] lemma div_zpow (a b : α) (n : ℤ) : (a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_zpow, inv_zpow]
/-- The `n`-th power map (for an integer `n`) on a commutative group, considered as a group
homomorphism. -/
@[to_additive "Multiplication by an integer `n` on a commutative additive group, considered as an
additive group homomorphism.", simps]
def zpow_group_hom (n : ℤ) : α →* α :=
{ to_fun := (^ n),
map_one' := one_zpow n,
map_mul' := λ a b, mul_zpow a b n }
end division_comm_monoid
section group
variables [group G] [group H] [add_group A] [add_group B]
@[to_additive sub_nsmul] lemma pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ :=
eq_mul_inv_of_mul_eq $ by rw [←pow_add, nat.sub_add_cancel h]
@[to_additive] lemma pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
(commute.refl a).inv_left.pow_pow _ _
@[to_additive sub_nsmul_neg]
lemma inv_pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a⁻¹^(m - n) = (a^m)⁻¹ * a^n :=
by rw [pow_sub a⁻¹ h, inv_pow, inv_pow, inv_inv]
end group
lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) :
a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, nat.sub_add_cancel h]⟩
lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) :
multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl
lemma of_add_zsmul [sub_neg_monoid A] (x : A) (n : ℤ) :
multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl
lemma of_mul_pow [monoid A] (x : A) (n : ℕ) :
additive.of_mul (x ^ n) = n • (additive.of_mul x) := rfl
lemma of_mul_zpow [div_inv_monoid G] (x : G) (n : ℤ) :
additive.of_mul (x ^ n) = n • additive.of_mul x :=
rfl
@[simp, to_additive]
lemma semiconj_by.zpow_right [group G] {a x y : G} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := by simp [zpow_coe_nat, h.pow_right n]
| -[1+n] := by simp [(h.pow_right n.succ).inv_right]
namespace commute
variables [group G] {a b : G}
@[simp, to_additive] lemma zpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.zpow_right m
@[simp, to_additive] lemma zpow_left (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.zpow_right m).symm
@[to_additive]
lemma zpow_zpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.zpow_left m).zpow_right n
variables (a) (m n : ℤ)
@[simp, to_additive] lemma self_zpow : commute a (a ^ n) := (commute.refl a).zpow_right n
@[simp, to_additive] lemma zpow_self : commute (a ^ n) a := (commute.refl a).zpow_left n
@[simp, to_additive] lemma zpow_zpow_self : commute (a ^ m) (a ^ n) :=
(commute.refl a).zpow_zpow m n
end commute
|
cc3b72972b58b9a71b3f74593f998c0d3c031065 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/group_theory/submonoid.lean | 3e180374c873a7b05516c266f90e0790a44bb8ba | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 10,303 | 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
-/
import algebra.big_operators
import data.finset
import tactic.subtype_instance
variables {α : Type*} [monoid α] {s : set α}
variables {β : Type*} [add_monoid β] {t : set β}
/-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/
class is_submonoid (s : set α) : Prop :=
(one_mem : (1:α) ∈ s)
(mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s)
/-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/
class is_add_submonoid (s : set β) : Prop :=
(zero_mem : (0:β) ∈ s)
(add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s)
attribute [to_additive is_add_submonoid] is_submonoid
attribute [to_additive is_add_submonoid.zero_mem] is_submonoid.one_mem
attribute [to_additive is_add_submonoid.add_mem] is_submonoid.mul_mem
attribute [to_additive is_add_submonoid.mk] is_submonoid.mk
instance additive.is_add_submonoid
(s : set α) : ∀ [is_submonoid s], @is_add_submonoid (additive α) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem additive.is_add_submonoid_iff
{s : set α} : @is_add_submonoid (additive α) _ s ↔ is_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩
instance multiplicative.is_submonoid
(s : set β) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative β) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem multiplicative.is_submonoid_iff
{s : set β} : @is_submonoid (multiplicative β) _ s ↔ is_add_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩
section powers
def powers (x : α) : set α := {y | ∃ n:ℕ, x^n = y}
def multiples (x : β) : set β := {y | ∃ n:ℕ, add_monoid.smul n x = y}
attribute [to_additive multiples] powers
lemma powers.one_mem {x : α} : (1 : α) ∈ powers x := ⟨0, pow_zero _⟩
lemma multiples.zero_mem {x : β} : (0 : β) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩
attribute [to_additive multiples.zero_mem] powers.one_mem
lemma powers.self_mem {x : α} : x ∈ powers x := ⟨1, pow_one _⟩
lemma multiples.self_mem {x : β} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩
attribute [to_additive multiples.self_mem] powers.self_mem
instance powers.is_submonoid (x : α) : is_submonoid (powers x) :=
{ one_mem := ⟨0, by simp⟩,
mul_mem := λ x₁ x₂ ⟨n₁, hn₁⟩ ⟨n₂, hn₂⟩, ⟨n₁ + n₂, by simp [pow_add, *]⟩ }
instance multiples.is_add_submonoid (x : β) : is_add_submonoid (multiples x) :=
multiplicative.is_submonoid_iff.1 $ powers.is_submonoid _
attribute [to_additive multiples.is_add_submonoid] powers.is_submonoid
lemma is_submonoid.pow_mem {a : α} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s
| 0 := is_submonoid.one_mem s
| (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem
lemma is_add_submonoid.smul_mem {a : β} [is_add_submonoid t] :
∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t :=
@is_submonoid.pow_mem (multiplicative β) _ _ _ _
attribute [to_additive is_add_submonoid.smul_mem] is_submonoid.pow_mem
lemma is_submonoid.power_subset {a : α} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s :=
assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h
lemma is_add_submonoid.multiple_subset {a : β} [is_add_submonoid t] :
a ∈ t → multiples a ⊆ t :=
@is_submonoid.power_subset (multiplicative β) _ _ _ _
attribute [to_additive is_add_submonoid.multiple_subset] is_add_submonoid.multiple_subset
end powers
namespace is_submonoid
@[to_additive is_add_submonoid.list_sum_mem]
lemma list_prod_mem [is_submonoid s] : ∀{l : list α}, (∀x∈l, x ∈ s) → l.prod ∈ s
| [] h := one_mem s
| (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)
@[to_additive is_add_submonoid.multiset_sum_mem]
lemma multiset_prod_mem {α} [comm_monoid α] (s : set α) [is_submonoid s] (m : multiset α) :
(∀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
@[to_additive is_add_submonoid.finset_sum_mem]
lemma finset_prod_mem {α β} [comm_monoid α] (s : set α) [is_submonoid s] (f : β → α) :
∀(t : finset β), (∀b∈t, f b ∈ s) → t.prod f ∈ s
| ⟨m, hm⟩ hs :=
begin
refine multiset_prod_mem s _ _,
simp,
rintros a b hb rfl,
exact hs _ hb
end
end is_submonoid
instance subtype.monoid {s : set α} [is_submonoid s] : monoid s :=
by subtype_instance
attribute [to_additive subtype.add_monoid._proof_1] subtype.monoid._proof_1
attribute [to_additive subtype.add_monoid._proof_2] subtype.monoid._proof_2
attribute [to_additive subtype.add_monoid._proof_3] subtype.monoid._proof_3
attribute [to_additive subtype.add_monoid._proof_4] subtype.monoid._proof_4
attribute [to_additive subtype.add_monoid._proof_5] subtype.monoid._proof_5
attribute [to_additive subtype.add_monoid] subtype.monoid
@[simp, to_additive is_add_submonoid.coe_zero]
lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : α) = 1 := rfl
@[simp, to_additive is_add_submonoid.coe_add]
lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : α) = a * b := rfl
@[simp] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : α) = a ^ n :=
by induction n; simp [*, pow_succ]
@[simp] lemma is_add_submonoid.smul_coe {β : Type*} [add_monoid β] {s : set β}
[is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : β) = add_monoid.smul n a :=
by induction n; [refl, simp [*, succ_smul]]
attribute [to_additive is_add_submonoid.smul_coe] is_submonoid.coe_pow
namespace monoid
inductive in_closure (s : set α) : α → Prop
| basic {a : α} : a ∈ s → in_closure a
| one : in_closure 1
| mul {a b : α} : in_closure a → in_closure b → in_closure (a * b)
def closure (s : set α) : set α := {a | in_closure s a }
instance closure.is_submonoid (s : set α) : is_submonoid (closure s) :=
{ one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul }
theorem subset_closure {s : set α} : s ⊆ closure s :=
assume a, in_closure.basic
theorem closure_subset {s t : set α} [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]
theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
theorem closure_singleton {x : α} : closure ({x} : set α) = 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
theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) :
(∃l:list α, (∀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
theorem mem_closure_union_iff {α : Type*} [comm_monoid α] {s t : set α} {x : α} :
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
namespace add_monoid
def closure (s : set β) : set β := @monoid.closure (multiplicative β) _ s
attribute [to_additive add_monoid.closure] monoid.closure
instance closure.is_add_submonoid (s : set β) : is_add_submonoid (closure s) :=
multiplicative.is_submonoid_iff.1 $ monoid.closure.is_submonoid s
attribute [to_additive add_monoid.closure.is_add_submonoid] monoid.closure.is_submonoid
theorem subset_closure {s : set β} : s ⊆ closure s :=
monoid.subset_closure
attribute [to_additive add_monoid.subset_closure] monoid.subset_closure
theorem closure_subset {s t : set β} [is_add_submonoid t] : s ⊆ t → closure s ⊆ t :=
monoid.closure_subset
attribute [to_additive add_monoid.closure_subset] monoid.closure_subset
theorem closure_mono {s t : set β} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
attribute [to_additive add_monoid.closure_mono] monoid.closure_mono
theorem closure_singleton {x : β} : closure ({x} : set β) = multiples x :=
monoid.closure_singleton
attribute [to_additive add_monoid.closure_singleton] monoid.closure_singleton
theorem exists_list_of_mem_closure {s : set β} {a : β} :
a ∈ closure s → ∃l:list β, (∀x∈l, x ∈ s) ∧ l.sum = a :=
monoid.exists_list_of_mem_closure
attribute [to_additive add_monoid.exists_list_of_mem_closure] monoid.exists_list_of_mem_closure
@[elab_as_eliminator]
theorem in_closure.rec_on {s : set β} {C : β → Prop}
{a : β} (H : a ∈ closure s)
(H1 : ∀ {a : β}, a ∈ s → C a) (H2 : C 0)
(H3 : ∀ {a b : β}, a ∈ closure s → b ∈ closure s → C a → C b → C (a + b)) :
C a :=
monoid.in_closure.rec_on H (λ _, H1) H2 (λ _ _, H3)
theorem mem_closure_union_iff {β : Type*} [add_comm_monoid β] {s t : set β} {x : β} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y + z = x :=
monoid.mem_closure_union_iff
end add_monoid
|
26bed9618b8dc7dde1d73b2b1005bd59ebdbd423 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/structInstError.lean | efe13498db8bdb6eaa34c462743f9ba33327fd65 | [
"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 | 109 | lean | structure Foo where
x : Nat
b : Bool
#check { x := 10, b := true }
#check { x := 10, b := true : Foo }
|
6d65d72fa50fc65ceaac2a3fc3fdf74002c0bc24 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/geometry/euclidean/circumcenter.lean | bb4fbc109bac0e3fbed23878c184ac388177734b | [
"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,609 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import geometry.euclidean.basic
import linear_algebra.affine_space.finite_dimensional
import tactic.derive_fintype
/-!
# Circumcenter and circumradius
This file proves some lemmas on points equidistant from a set of
points, and defines the circumradius and circumcenter of a simplex.
There are also some definitions for use in calculations where it is
convenient to work with affine combinations of vertices together with
the circumcenter.
## Main definitions
* `circumcenter` and `circumradius` are the circumcenter and
circumradius of a simplex.
## References
* https://en.wikipedia.org/wiki/Circumscribed_circle
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace euclidean_geometry
open inner_product_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
open affine_subspace
/-- `p` is equidistant from two points in `s` if and only if its
`orthogonal_projection` is. -/
lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
dist p1 p3 = dist p2 p3 ↔
dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) :=
begin
rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg,
←mul_self_inj_of_nonneg dist_nonneg dist_nonneg,
dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
p3 hp1,
dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
p3 hp2],
simp
end
/-- `p` is equidistant from a set of points in `s` if and only if its
`orthogonal_projection` is. -/
lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) :
set.pairwise ps (λ p1 p2, dist p1 p = dist p2 p) ↔
(set.pairwise ps (λ p1 p2, dist p1 (orthogonal_projection s p) =
dist p2 (orthogonal_projection s p))) :=
⟨λ h p1 hp1 p2 hp2 hne,
(dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h hp1 hp2 hne),
λ h p1 hp1 p2 hp2 hne,
(dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h hp1 hp2 hne)⟩
/-- There exists `r` such that `p` has distance `r` from all the
points of a set of points in `s` if and only if there exists (possibly
different) `r` such that its `orthogonal_projection` has that distance
from all the points in that set. -/
lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) :
(∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔
∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r :=
begin
have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p,
simp_rw set.pairwise_eq_iff_exists_eq at h,
exact h
end
/-- The induction step for the existence and uniqueness of the
circumcenter. Given a nonempty set of points in a nonempty affine
subspace whose direction is complete, such that there is a unique
(circumcenter, circumradius) pair for those points in that subspace,
and a point `p` not in that subspace, there is a unique (circumcenter,
circumradius) pair for the set with `p` added, in the span of the
subspace with `p` added. -/
lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P}
[complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P}
(hps : ps ⊆ s) (hp : p ∉ s)
(hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) :
∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧
∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd :=
begin
haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps),
rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩,
simp only [prod.fst, prod.snd] at hcc hcr hcccru,
let x := dist cc (orthogonal_projection s p),
let y := dist p (orthogonal_projection s p),
have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp,
let ycc₂ := (x * x + y * y - cr * cr) / (2 * y),
let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc,
let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂),
use (cc₂, cr₂),
simp only [prod.fst, prod.snd],
have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p,
{ simp },
split,
{ split,
{ refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)),
rw direction_affine_span,
exact submodule.smul_mem _ _
(vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (orthogonal_projection_mem _))) },
{ intros p1 hp1,
rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))],
cases hp1,
{ rw hp1,
rw [hpo,
dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd
(orthogonal_projection_mem p) hcc _ _
(vsub_orthogonal_projection_mem_direction_orthogonal s p),
←dist_eq_norm_vsub V p, dist_comm _ cc],
field_simp [hy0],
ring },
{ rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
_ (hps hp1),
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk,
hcr _ hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V,
real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0,
abs_mul_abs_self] } } },
{ rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩,
simp only [prod.fst, prod.snd] at hcc₃ hcr₃,
obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ :
∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0,
{ rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ },
have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r :=
⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩,
rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'',
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃',
cases hcr₃' with cr₃' hcr₃',
have hu := hcccru (cc₃', cr₃'),
simp only [prod.fst, prod.snd] at hu,
replace hu := hu ⟨hcc₃', hcr₃'⟩,
rw prod.ext_iff at hu,
simp only [prod.fst, prod.snd] at hu,
cases hu with hucc hucr,
substs hucc hucr,
have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)),
{ cases hnps with p0 hp0,
have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl,
rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃'',
←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)),
dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
_ (hps hp0),
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', hcr p0 hp0,
dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p,
real.norm_eq_abs, ←mul_assoc, mul_comm _ (|t₃|), ←mul_assoc, abs_mul_abs_self],
ring },
replace hcr₃ := hcr₃ p (set.mem_insert _ _),
rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd
(orthogonal_projection_mem p) hcc₃' _ _
(vsub_orthogonal_projection_mem_direction_orthogonal s p),
dist_comm, ←dist_eq_norm_vsub V p,
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃,
change x * x + _ * (y * y) = _ at hcr₃,
rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) =
x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃,
have ht₃ : t₃ = ycc₂ / y,
{ field_simp [←hcr₃, hy0],
ring },
subst ht₃,
change cc₃ = cc₂ at hcc₃'',
congr',
rw hcr₃val,
congr' 2,
field_simp [hy0],
ring }
end
/-- Given a finite nonempty affinely independent family of points,
there is a unique (circumcenter, circumradius) pair for those points
in the affine subspace they span. -/
lemma _root_.affine_independent.exists_unique_dist_eq {ι : Type*} [hne : nonempty ι] [fintype ι]
{p : ι → P} (ha : affine_independent ℝ p) :
∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧
∀ i, dist (p i) cccr.fst = cccr.snd :=
begin
unfreezingI { induction hn : fintype.card ι with m hm generalizing ι },
{ exfalso,
have h := fintype.card_pos_iff.2 hne,
rw hn at h,
exact lt_irrefl 0 h },
{ cases m,
{ rw fintype.card_eq_one_iff at hn,
cases hn with i hi,
haveI : unique ι := ⟨⟨i⟩, hi⟩,
use (p i, 0),
simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton],
split,
{ simp_rw [hi default],
use rfl,
intro i1,
rw hi i1,
exact dist_self _ },
{ rintros ⟨cc, cr⟩,
simp only [prod.fst, prod.snd],
rintros ⟨rfl, hdist⟩,
rw hi default,
congr',
rw ←hdist default,
exact dist_self _ } },
{ have i := hne.some,
let ι2 := {x // x ≠ i},
have hc : fintype.card ι2 = m + 1,
{ rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)),
{ rw finset.filter_not,
simp_rw eq_comm,
rw [finset.filter_eq, if_pos (finset.mem_univ _),
finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ,
hn],
simp },
{ simp } },
haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _),
have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := ha.subtype _,
replace hm := hm ha2 hc,
have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)),
{ change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)),
rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq],
congr' with j,
simp [classical.em] },
change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)),
conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } },
dsimp only,
rw hr,
change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm,
conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } },
rw ←affine_span_insert_affine_span,
refine exists_unique_dist_eq_of_insert
(set.range_nonempty _)
(subset_span_points ℝ _)
_
hm,
convert ha.not_mem_affine_span_diff i set.univ,
change set.range (λ i2 : {x | x ≠ i}, p i2) = _,
rw ←set.image_eq_range,
congr' with j, simp, refl } }
end
end euclidean_geometry
namespace affine
namespace simplex
open finset affine_subspace euclidean_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The pair (circumcenter, circumradius) of a simplex. -/
def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) :=
s.independent.exists_unique_dist_eq.some
/-- The property satisfied by the (circumcenter, circumradius) pair. -/
lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) :
(s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧
∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧
(∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧
∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) :=
s.independent.exists_unique_dist_eq.some_spec
/-- The circumcenter of a simplex. -/
def circumcenter {n : ℕ} (s : simplex ℝ P n) : P :=
s.circumcenter_circumradius.fst
/-- The circumradius of a simplex. -/
def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ :=
s.circumcenter_circumradius.snd
/-- The circumcenter lies in the affine span. -/
lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) :
s.circumcenter ∈ affine_span ℝ (set.range s.points) :=
s.circumcenter_circumradius_unique_dist_eq.1.1
/-- All points have distance from the circumcenter equal to the
circumradius. -/
@[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) :
∀ i, dist (s.points i) s.circumcenter = s.circumradius :=
s.circumcenter_circumradius_unique_dist_eq.1.2
/-- All points have distance to the circumcenter equal to the
circumradius. -/
@[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) :
∀ i, dist s.circumcenter (s.points i) = s.circumradius :=
begin
intro i,
rw dist_comm,
exact dist_circumcenter_eq_circumradius _ _
end
/-- Given a point in the affine span from which all the points are
equidistant, that point is the circumcenter. -/
lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
(hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
p = s.circumcenter :=
begin
have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r),
simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h,
exact h.1
end
/-- Given a point in the affine span from which all the points are
equidistant, that distance is the circumradius. -/
lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
(hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
r = s.circumradius :=
begin
have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r),
simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h,
exact h.2
end
/-- The circumradius is non-negative. -/
lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius :=
s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg
/-- The circumradius of a simplex with at least two points is
positive. -/
lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius :=
begin
refine lt_of_le_of_ne s.circumradius_nonneg _,
intro h,
have hr := s.dist_circumcenter_eq_circumradius,
simp_rw [←h, dist_eq_zero] at hr,
have h01 := s.independent.injective.ne (dec_trivial : (0 : fin (n + 2)) ≠ 1),
simpa [hr] using h01
end
/-- The circumcenter of a 0-simplex equals its unique point. -/
lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) :
s.circumcenter = s.points i :=
begin
have h := s.circumcenter_mem_affine_span,
rw [set.range_unique, mem_affine_span_singleton] at h,
rw h,
congr
end
/-- The circumcenter of a 1-simplex equals its centroid. -/
lemma circumcenter_eq_centroid (s : simplex ℝ P 1) :
s.circumcenter = finset.univ.centroid ℝ s.points :=
begin
have hr : set.pairwise set.univ
(λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) =
dist (s.points j) (finset.univ.centroid ℝ s.points)),
{ intros i hi j hj hij,
rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i),
dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub,
←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)],
fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num },
rw set.pairwise_eq_iff_exists_eq at hr,
cases hr with r hr,
exact (s.eq_circumcenter_of_dist_eq
(centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2))
(λ i, hr i (set.mem_univ _))).symm
end
/-- The orthogonal projection of a point `p` onto the hyperplane spanned by the simplex's points. -/
def orthogonal_projection_span {n : ℕ} (s : simplex ℝ P n) :
P →ᵃ[ℝ] affine_span ℝ (set.range s.points) :=
orthogonal_projection (affine_span ℝ (set.range s.points))
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector is a
multiple of the result of subtracting a point's orthogonal projection
from that point. -/
lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection
{n : ℕ} (s : simplex ℝ P n) {p1 : P} (p2 : P) (r : ℝ)
(hp : p1 ∈ affine_span ℝ (set.range s.points)) :
s.orthogonal_projection_span (r • (p2 -ᵥ s.orthogonal_projection_span p2 : V) +ᵥ p1) =
⟨p1, hp⟩ :=
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _
lemma coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : ℕ} {r₁ : ℝ}
(s : simplex ℝ P n) {p p₁o : P} (hp₁o : p₁o ∈ affine_span ℝ (set.range s.points)) :
↑(s.orthogonal_projection_span (r₁ • (p -ᵥ ↑(s.orthogonal_projection_span p)) +ᵥ p₁o)) = p₁o :=
congr_arg coe (orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ hp₁o)
lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {n : ℕ}
(s : simplex ℝ P n) {p1 : P}
(p2 : P) (hp1 : p1 ∈ affine_span ℝ (set.range s.points)) :
dist p1 p2 * dist p1 p2 =
dist p1 (s.orthogonal_projection_span p2) * dist p1 (s.orthogonal_projection_span p2) +
dist p2 (s.orthogonal_projection_span p2) * dist p2 (s.orthogonal_projection_span p2) :=
begin
rw [pseudo_metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _,
dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (s.orthogonal_projection_span p2) p2,
norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero],
exact submodule.inner_right_of_mem_orthogonal
(vsub_orthogonal_projection_mem_direction p2 hp1)
(orthogonal_projection_vsub_mem_direction_orthogonal _ p2),
end
lemma dist_circumcenter_sq_eq_sq_sub_circumradius {n : ℕ} {r : ℝ} (s : simplex ℝ P n)
{p₁ : P}
(h₁ : ∀ (i : fin (n + 1)), dist (s.points i) p₁ = r)
(h₁' : ↑((s.orthogonal_projection_span) p₁) = s.circumcenter)
(h : s.points 0 ∈ affine_span ℝ (set.range s.points)) :
dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius :=
begin
rw [dist_comm, ←h₁ 0,
s.dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h],
simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius],
end
/-- If there exists a distance that a point has from all vertices of a
simplex, the orthogonal projection of that point onto the subspace
spanned by that simplex is its circumcenter. -/
lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n)
{p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) :
↑(s.orthogonal_projection_span p) = s.circumcenter :=
begin
change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr,
conv at hr { congr, funext, rw ←set.forall_range_iff },
rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr,
cases hr with r hr,
exact s.eq_circumcenter_of_dist_eq
(orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)),
end
/-- If a point has the same distance from all vertices of a simplex,
the orthogonal projection of that point onto the subspace spanned by
that simplex is its circumcenter. -/
lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
{r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
↑(s.orthogonal_projection_span p) = s.circumcenter :=
s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩
/-- The orthogonal projection of the circumcenter onto a face is the
circumcenter of that face. -/
lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))}
{m : ℕ} (h : fs.card = m + 1) :
↑((s.face h).orthogonal_projection_span s.circumcenter) = (s.face h).circumcenter :=
begin
have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r,
{ use s.circumradius,
simp [face_points] },
exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr
end
/-- Two simplices with the same points have the same circumcenter. -/
lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n}
(h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter :=
begin
have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) :=
h ▸ s₁.circumcenter_mem_affine_span,
have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius,
{ intro i,
have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _,
rw [←h, set.mem_range] at hi,
rcases hi with ⟨j, hj⟩,
rw [←hj, s₁.dist_circumcenter_eq_circumradius j] },
exact s₂.eq_circumcenter_of_dist_eq hs hr
end
omit V
/-- An index type for the vertices of a simplex plus its circumcenter.
This is for use in calculations where it is convenient to work with
affine combinations of vertices together with the circumcenter. (An
equivalent form sometimes used in the literature is placing the
circumcenter at the origin and working with vectors for the vertices.) -/
@[derive fintype]
inductive points_with_circumcenter_index (n : ℕ)
| point_index : fin (n + 1) → points_with_circumcenter_index
| circumcenter_index : points_with_circumcenter_index
open points_with_circumcenter_index
instance points_with_circumcenter_index_inhabited (n : ℕ) :
inhabited (points_with_circumcenter_index n) :=
⟨circumcenter_index⟩
/-- `point_index` as an embedding. -/
def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n :=
⟨λ i, point_index i, λ _ _ h, by injection h⟩
/-- The sum of a function over `points_with_circumcenter_index`. -/
lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ}
(f : points_with_circumcenter_index n → α) :
∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index :=
begin
have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)),
{ ext x,
refine ⟨λ h, _, λ _, mem_univ _⟩,
cases x with i,
{ exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) },
{ exact mem_insert_self _ _ } },
change _ = ∑ i, f (point_index_embedding n i) + _,
rw [add_comm, h, ←sum_map, sum_insert],
simp_rw [finset.mem_map, not_exists],
intros x hx h,
injection h
end
include V
/-- The vertices of a simplex plus its circumcenter. -/
def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P
| (point_index i) := s.points i
| circumcenter_index := s.circumcenter
/-- `points_with_circumcenter`, applied to a `point_index` value,
equals `points` applied to that value. -/
@[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) :
s.points_with_circumcenter (point_index i) = s.points i :=
rfl
/-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the
circumcenter. -/
@[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) :
s.points_with_circumcenter circumcenter_index = s.circumcenter :=
rfl
omit V
/-- The weights for a single vertex of a simplex, in terms of
`points_with_circumcenter`. -/
def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ
| (point_index j) := if j = i then 1 else 0
| circumcenter_index := 0
/-- `point_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) :
∑ j, point_weights_with_circumcenter i j = 1 :=
begin
convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)),
{ ext j,
cases j ; simp [point_weights_with_circumcenter] },
{ simp }
end
include V
/-- A single vertex, in terms of `points_with_circumcenter`. -/
lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n)
(i : fin (n + 1)) :
s.points i =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (point_weights_with_circumcenter i) :=
begin
rw ←points_with_circumcenter_point,
symmetry,
refine affine_combination_of_eq_one_of_eq_zero _ _ _
(mem_univ _)
(by simp [point_weights_with_circumcenter])
_,
intros i hi hn,
cases i,
{ have h : i_1 ≠ i := λ h, hn (h ▸ rfl),
simp [point_weights_with_circumcenter, h] },
{ refl }
end
omit V
/-- The weights for the centroid of some vertices of a simplex, in
terms of `points_with_circumcenter`. -/
def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1)))
: points_with_circumcenter_index n → ℝ
| (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0
| circumcenter_index := 0
/-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is
nonempty. -/
@[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))}
(h : fs.nonempty) :
∑ i, centroid_weights_with_circumcenter fs i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero,
←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h,
set.sum_indicator_subset _ fs.subset_univ],
rcongr
end
include V
/-- The centroid of some vertices of a simplex, in terms of
`points_with_circumcenter`. -/
lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n)
(fs : finset (fin (n + 1))) :
fs.centroid ℝ s.points =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (centroid_weights_with_circumcenter fs) :=
begin
simp_rw [centroid_def, affine_combination_apply,
weighted_vsub_of_point_apply, sum_points_with_circumcenter,
centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul,
add_zero, centroid_weights,
set.sum_indicator_subset_of_eq_zero
(function.const (fin (n + 1)) ((card fs : ℝ)⁻¹))
(λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty))
fs.subset_univ
(λ i, zero_smul ℝ _),
set.indicator_apply],
congr,
end
omit V
/-- The weights for the circumcenter of a simplex, in terms of
`points_with_circumcenter`. -/
def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ
| (point_index i) := 0
| circumcenter_index := 1
/-- `circumcenter_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) :
∑ i, circumcenter_weights_with_circumcenter n i = 1 :=
begin
convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)),
{ ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] },
{ simp }
end
include V
/-- The circumcenter of a simplex, in terms of
`points_with_circumcenter`. -/
lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P n) :
s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) :=
begin
rw ←points_with_circumcenter_eq_circumcenter,
symmetry,
refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _,
rintros ⟨i⟩ hi hn ; tauto
end
omit V
/-- The weights for the reflection of the circumcenter in an edge of a
simplex. This definition is only valid with `i₁ ≠ i₂`. -/
def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) :
points_with_circumcenter_index n → ℝ
| (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0
| circumcenter_index := -1
/-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)}
(h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter,
sum_ite, sum_const, filter_or, filter_eq'],
rw card_union_eq,
{ simp },
{ simpa only [if_true, mem_univ, disjoint_singleton] using h }
end
include V
/-- The reflection of the circumcenter of a simplex in an edge, in
terms of `points_with_circumcenter`. -/
lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) :
reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) :=
begin
have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2,
{ simp [h] },
-- Making the next line a separate definition helps the elaborator:
set W : affine_subspace ℝ P := affine_span ℝ (s.points '' {i₁, i₂}) with W_def,
have h_faces : ↑(orthogonal_projection W s.circumcenter)
= ↑((s.face hc).orthogonal_projection_span s.circumcenter),
{ apply eq_orthogonal_projection_of_eq_subspace,
simp },
rw [euclidean_geometry.reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc,
circumcenter_eq_centroid, s.face_centroid_eq_centroid hc,
centroid_eq_affine_combination_of_points_with_circumcenter,
circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V,
affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub,
weighted_vsub_apply, sum_points_with_circumcenter],
simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul,
centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter,
reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero,
apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero],
convert sum_const_zero,
norm_num
end
end simplex
end affine
namespace euclidean_geometry
open affine affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- Given a nonempty affine subspace, whose direction is complete,
that contains a set of points, those points are cospherical if and
only if they are equidistant from some point in that subspace. -/
lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s)
[nonempty s] [complete_space s.direction] :
cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
begin
split,
{ rintro ⟨c, hcr⟩,
rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr,
exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ },
{ exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ }
end
/-- Given a nonempty affine subspace, whose direction is
finite-dimensional, that contains a set of points, those points are
cospherical if and only if they are equidistant from some point in
that subspace. -/
lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] :
cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
cospherical_iff_exists_mem_of_complete h
/-- All n-simplices among cospherical points in an n-dimensional
subspace have the same circumradius. -/
lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : finrank ℝ s.direction = n) (hc : cospherical ps) :
∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r :=
begin
rw cospherical_iff_exists_mem_of_finite_dimensional h at hc,
rcases hc with ⟨c, hc, r, hcr⟩,
use r,
intros sx hsxps,
have hsx : affine_span ℝ (set.range sx.points) = s,
{ refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one
(span_points_subset_coe_of_subset_coe (hsxps.trans h)) _,
simp [hd] },
have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc,
exact (sx.eq_circumradius_of_dist_eq
hc
(λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm
end
/-- Two n-simplices among cospherical points in an n-dimensional
subspace have the same circumradius. -/
lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumradius = sx₂.circumradius :=
begin
rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in n-space have the same
circumradius. -/
lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : finrank ℝ V = n) (hc : cospherical ps) :
∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r :=
begin
haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty,
rw [←finrank_top, ←direction_top ℝ V P] at hd,
refine exists_circumradius_eq_of_cospherical_subset _ hd hc,
exact set.subset_univ _
end
/-- Two n-simplices among cospherical points in n-space have the same
circumradius. -/
lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumradius = sx₂.circumradius :=
begin
rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in an n-dimensional
subspace have the same circumcenter. -/
lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : finrank ℝ s.direction = n) (hc : cospherical ps) :
∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c :=
begin
rw cospherical_iff_exists_mem_of_finite_dimensional h at hc,
rcases hc with ⟨c, hc, r, hcr⟩,
use c,
intros sx hsxps,
have hsx : affine_span ℝ (set.range sx.points) = s,
{ refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one
(span_points_subset_coe_of_subset_coe (hsxps.trans h)) _,
simp [hd] },
have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc,
exact (sx.eq_circumcenter_of_dist_eq
hc
(λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm
end
/-- Two n-simplices among cospherical points in an n-dimensional
subspace have the same circumcenter. -/
lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumcenter = sx₂.circumcenter :=
begin
rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in n-space have the same
circumcenter. -/
lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : finrank ℝ V = n) (hc : cospherical ps) :
∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c :=
begin
haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty,
rw [←finrank_top, ←direction_top ℝ V P] at hd,
refine exists_circumcenter_eq_of_cospherical_subset _ hd hc,
exact set.subset_univ _
end
/-- Two n-simplices among cospherical points in n-space have the same
circumcenter. -/
lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumcenter = sx₂.circumcenter :=
begin
rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- Suppose all distances from `p₁` and `p₂` to the points of a
simplex are equal, and that `p₁` and `p₂` lie in the affine span of
`p` with the vertices of that simplex. Then `p₁` and `p₂` are equal
or reflections of each other in the affine span of the vertices of the
simplex. -/
lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ}
(hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points)))
(hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points)))
(h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) :
p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ :=
begin
let span_s := affine_span ℝ (set.range s.points),
have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁,
have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂,
rw [←affine_span_insert_affine_span,
mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂,
obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁,
obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂,
obtain rfl : ↑(s.orthogonal_projection_span p₁) = p₁o,
{ subst hp₁, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₁o },
rw h₁' at hp₁,
obtain rfl : ↑(s.orthogonal_projection_span p₂) = p₂o,
{ subst hp₂, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₂o },
rw h₂' at hp₂,
have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _),
have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter =
r * r - s.circumradius * s.circumradius :=
s.dist_circumcenter_sq_eq_sq_sub_circumradius h₁ h₁' h,
have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter =
r * r - s.circumradius * s.circumradius :=
s.dist_circumcenter_sq_eq_sq_sub_circumradius h₂ h₂' h,
rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter,
dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_mul_norm,
←real_inner_self_eq_norm_mul_norm, real_inner_smul_left, real_inner_smul_left,
real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁,
by_cases hp : p = s.orthogonal_projection_span p,
{ rw simplex.orthogonal_projection_span at hp,
rw [hp₁, hp₂, ←hp],
simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] },
{ have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0,
by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp,
rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁,
rw [hp₁, hp₂],
cases hd₁,
{ left,
rw hd₁ },
{ right,
rw [hd₁,
reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span,
neg_smul] } }
end
end euclidean_geometry
|
c77ee5f667ac1746c3364762ec0356da503480cc | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/tactic/lint/type_classes.lean | 586d6810d95f430e5ee958a82bb2ee8d8e2b03ce | [
"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 | 23,251 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner
-/
import tactic.lint.basic
/-!
# Linters about type classes
This file defines several linters checking the correct usage of type classes
and the appropriate definition of instances:
* `instance_priority` ensures that blanket instances have low priority.
* `has_inhabited_instances` checks that every type has an `inhabited` instance.
* `impossible_instance` checks that there are no instances which can never apply.
* `incorrect_type_class_argument` checks that only type classes are used in
instance-implicit arguments.
* `dangerous_instance` checks for instances that generate subproblems with metavariables.
* `fails_quickly` checks that type class resolution finishes quickly.
* `class_structure` checks that every `class` is a structure, i.e. `@[class] def` is forbidden.
* `has_coe_variable` checks that there is no instance of type `has_coe α t`.
* `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized
to `[nonempty α]`.
* `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used
in the statement, and could thus be removed by using `classical` in the proof.
* `linter.has_coe_to_fun` checks whether necessary `has_coe_to_fun` instances are declared.
* `linter.check_reducibility` checks whether non-instances with a class as type are reducible.
-/
open tactic
/-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions
and binders (or any other element that can be pretty printed).
`l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by
`get_pi_binders`. -/
meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do
fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b),
return $ fs.to_string_aux tt
/-- checks whether an instance that always applies has priority ≥ 1000. -/
private meta def instance_priority (d : declaration) : tactic (option string) := do
let nm := d.to_name,
b ← is_instance nm,
/- return `none` if `d` is not an instance -/
if ¬ b then return none else do
(is_persistent, prio) ← has_attribute `instance nm,
/- return `none` if `d` is has low priority -/
if prio < 1000 then return none else do
(_, tp) ← open_pis d.type,
tp ← whnf tp transparency.none,
let (fn, args) := tp.get_app_fn_args,
cls ← get_decl fn.const_name,
let (pi_args, _) := cls.type.pi_binders,
guard (args.length = pi_args.length),
/- List all the arguments of the class that block type-class inference from firing
(if they are metavariables). These are all the arguments except instance-arguments and
out-params. -/
let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩,
if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param
then none else some e,
let always_applies := relevant_args.all expr.is_local_constant ∧ relevant_args.nodup,
if always_applies then return $ some "set priority below 1000" else return none
/--
There are places where typeclass arguments are specified with implicit `{}` brackets instead of
the usual `[]` brackets. This is done when the instances can be inferred because they are implicit
arguments to the type of one of the other arguments. When they can be inferred from these other
arguments, it is faster to use this method than to use type class inference.
For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α`
and `β` are `semiring`s as `{rα : semiring α} {rβ : semiring β}` rather than the usual
`[semiring α] [semiring β]`.
-/
library_note "implicit instance arguments"
/--
Certain instances always apply during type-class resolution. For example, the instance
`add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class
resolution problems of the form `add_group _`, and type-class inference will then do an
exhaustive search to find a commutative group. These instances take a long time to fail.
Other instances will only apply if the goal has a certain shape. For example
`int.add_group : add_group ℤ` or
`add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances
will fail quickly, and when they apply, they are almost the desired instance.
For this reason, we want the instances of the second type (that only apply in specific cases) to
always have higher priority than the instances of the first type (that always apply).
See also #1561.
Therefore, if we create an instance that always applies, we set the priority of these instances to
100 (or something similar, which is below the default value of 1000).
-/
library_note "lower instance priority"
/-- A linter object for checking instance priorities of instances that always apply.
This is in the default linter set. -/
@[linter] meta def linter.instance_priority : linter :=
{ test := instance_priority,
no_errors_found := "All instance priorities are good.",
errors_found := "DANGEROUS INSTANCE PRIORITIES.
The following instances always apply, and therefore should have a priority < 1000.
If you don't know what priority to choose, use priority 100.
See note [lower instance priority] for instructions to change the priority.",
auto_decls := tt }
/-- Reports declarations of types that do not have an associated `inhabited` instance. -/
private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do
tt ← pure d.is_trusted | pure none,
ff ← has_attribute' `reducible d.to_name | pure none,
ff ← has_attribute' `class d.to_name | pure none,
(_, ty) ← open_pis d.type,
ty ← whnf ty,
if ty = `(Prop) then pure none else do
`(Sort _) ← whnf ty | pure none,
insts ← attribute.get_instances `instance,
insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i,
let inhabited_insts := insts_tys.filter (λ i,
i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique),
let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name),
if d.to_name ∈ inhabited_tys then
pure none
else
pure "inhabited instance missing"
/-- A linter for missing `inhabited` instances. -/
@[linter]
meta def linter.has_inhabited_instance : linter :=
{ test := has_inhabited_instance,
auto_decls := ff,
no_errors_found := "No types have missing inhabited instances.",
errors_found := "TYPES ARE MISSING INHABITED INSTANCES:",
is_fast := ff }
attribute [nolint has_inhabited_instance] pempty
/-- Checks whether an instance can never be applied. -/
private meta def impossible_instance (d : declaration) : tactic (option string) := do
tt ← is_instance d.to_name | return none,
(binders, _) ← get_pi_binders_nondep d.type,
let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit,
_ :: _ ← return bad_arguments | return none,
(λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments
/-- A linter object for `impossible_instance`. -/
@[linter] meta def linter.impossible_instance : linter :=
{ test := impossible_instance,
auto_decls := tt,
no_errors_found := "All instances are applicable.",
errors_found := "IMPOSSIBLE INSTANCES FOUND.
These instances have an argument that cannot be found during type-class resolution, and " ++
"therefore can never succeed. Either mark the arguments with square brackets (if it is a " ++
"class), or don't make it an instance." }
/-- Checks whether an instance can never be applied. -/
private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do
(binders, _) ← get_pi_binders d.type,
let instance_arguments := binders.indexes_values $
λ b : binder, b.info = binder_info.inst_implicit,
/- the head of the type should either unfold to a class, or be a local constant.
A local constant is allowed, because that could be a class when applied to the
proper arguments. -/
bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do
(_, head) ← open_pis b.type,
if head.get_app_fn.is_local_constant then return ff else do
bnot <$> is_class head),
_ :: _ ← return bad_arguments | return none,
(λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments
/-- A linter object for `incorrect_type_class_argument`. -/
@[linter] meta def linter.incorrect_type_class_argument : linter :=
{ test := incorrect_type_class_argument,
auto_decls := tt,
no_errors_found := "All declarations have correct type-class arguments.",
errors_found := "INCORRECT TYPE-CLASS ARGUMENTS.
Some declarations have non-classes between [square brackets]:" }
/-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable
arguments. -/
private meta def dangerous_instance (d : declaration) : tactic (option string) := do
tt ← is_instance d.to_name | return none,
(local_constants, target) ← open_pis d.type,
let instance_arguments := local_constants.indexes_values $
λ e : expr, e.local_binding_info = binder_info.inst_implicit,
let bad_arguments := local_constants.indexes_values $ λ x,
!target.has_local_constant x &&
(x.local_binding_info ≠ binder_info.inst_implicit) &&
instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x),
let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩,
_ :: _ ← return bad_arguments | return none,
(λ s, some $ "The following arguments become metavariables. " ++ s) <$>
print_arguments bad_arguments
/-- A linter object for `dangerous_instance`. -/
@[linter] meta def linter.dangerous_instance : linter :=
{ test := dangerous_instance,
no_errors_found := "No dangerous instances.",
errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new " ++
"type-class problem which will have metavariables.
Possible solution: remove the instance attribute or make it a local instance instead.
Currently this linter does not check whether the metavariables only occur in arguments marked " ++
"with `out_param`, in which case this linter gives a false positive.",
auto_decls := tt }
/-- Auxilliary definition for `find_nondep` -/
meta def find_nondep_aux : list expr → expr_set → tactic expr_set
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
find_nondep_aux hs $ r.union type.list_local_consts'
/-- Finds all hypotheses that don't occur in the target or other hypotheses. -/
meta def find_nondep : tactic (list expr) := do
ctx ← local_context,
tgt ← target,
lconsts ← find_nondep_aux ctx tgt.list_local_consts',
return $ ctx.filter $ λ e, !lconsts.contains e
/--
Tests whether type-class inference search will end quickly on certain unsolvable
type-class problems. This is to detect loops or very slow searches, which are problematic
(recall that normal type-class search often creates unsolvable subproblems, which have to fail
quickly for type-class inference to perform well.
We create these type-class problems by taking an instance, and removing the last hypothesis that
doesn't appear in the goal (or a later hypothesis). Note: this argument is necessarily an
instance-implicit argument if it passes the `linter.incorrect_type_class_argument`.
This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error
message that it cannot find an instance. It fails if the tactic takes too long, or if any other
error message is raised (usually a maximum depth in the search).
-/
meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := retrieve $ do
tt ← is_instance d.to_name | return none,
let e := d.type,
g ← mk_meta_var e,
set_goals [g],
intros,
l@(_::_) ← find_nondep | return none, -- if all arguments occur in the goal, this instance is ok
clear l.ilast,
reset_instance_cache,
state ← read,
let state_msg := "\nState:\n" ++ to_string state,
tgt ← target >>= instantiate_mvars,
sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ mk_instance tgt |
return none, /- it's ok if type-class inference can find an instance with fewer hypotheses.
This happens a lot for `has_sizeof` and `has_well_founded`, but can also happen if there is a
noncomputable instance with fewer assumptions. -/
return $ if "tactic.mk_instance failed to generate instance for".is_prefix_of msg then none else
some $ (++ state_msg) $
if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg
/--
A linter object for `fails_quickly`.
We currently set the number of steps in the type-class search pretty high.
Some instances take quite some time to fail, and we seem to run against the caching issue in
https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/odd.20repeated.20type.20class.20search
-/
@[linter] meta def linter.fails_quickly : linter :=
{ test := fails_quickly 10000,
auto_decls := tt,
no_errors_found := "No type-class searches timed out.",
errors_found := "TYPE CLASS SEARCHES TIMED OUT.
The following instances are part of a loop, or an excessively long search.
It is common that the loop occurs in a different class than the one flagged below,
but usually an instance that is part of the loop is also flagged.
To debug:
(1) run `scripts/mk_all.sh` and create a file with `import all` and
`set_option trace.class_instances true`
(2) Recreate the state shown in the error message. You can do this easily by copying the type of
the instance (the output of `#check @my_instance`), turning this into an example and removing the
last argument in square brackets. Prove the example using `by apply_instance`.
For example, if `additive.topological_add_group` raises an error, run
```
example {G : Type*} [topological_space G] [group G] : topological_add_group (additive G) :=
by apply_instance
```
(3) What error do you get?
(3a) If the error is \"tactic.mk_instance failed to generate instance\",
there might be nothing wrong. But it might take unreasonably long for the type-class inference to
fail. Check the trace to see if type-class inference takes any unnecessary long unexpected turns.
If not, feel free to increase the value in the definition of the linter `fails_quickly`.
(3b) If the error is \"maximum class-instance resolution depth has been reached\" there is almost
certainly a loop in the type-class inference. Find which instance causes the type-class inference to
go astray, and fix that instance.",
is_fast := ff }
/-- Checks that all uses of the `@[class]` attribute apply to structures or inductive types.
This is future-proofing for lean 4, which no longer supports `@[class] def`. -/
private meta def class_structure (n : name) : tactic (option string) := do
is_class ← has_attribute' `class n,
if is_class then do
env ← get_env,
pure $ if env.is_inductive n then none else
"is a non-structure or inductive type marked @[class]"
else pure none
/-- A linter object for `class_structure`. -/
@[linter] meta def linter.class_structure : linter :=
{ test := λ d, class_structure d.to_name,
auto_decls := tt,
no_errors_found := "All classes are structures.",
errors_found := "USE OF @[class] def IS DISALLOWED:" }
/--
Tests whether there is no instance of type `has_coe α t` where `α` is a variable,
or `has_coe t α` where `α` does not occur in `t`.
See note [use has_coe_t].
-/
private meta def has_coe_variable (d : declaration) : tactic (option string) := do
tt ← is_instance d.to_name | return none,
`(has_coe %%a %%b) ← return d.type.pi_codomain | return none,
if a.is_var then
return $ some $ "illegal instance, first argument is variable"
else if b.is_var ∧ ¬ b.occurs a then
return $ some $ "illegal instance, second argument is variable not occurring in first argument"
else
return none
/-- A linter object for `has_coe_variable`. -/
@[linter] meta def linter.has_coe_variable : linter :=
{ test := has_coe_variable,
auto_decls := tt,
no_errors_found := "No invalid `has_coe` instances.",
errors_found := "INVALID `has_coe` INSTANCES.
Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." }
/-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused
elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/
private meta def inhabited_nonempty (d : declaration) : tactic (option string) :=
do tt ← is_prop d.type | return none,
(binders, _) ← get_pi_binders_nondep d.type,
let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited,
if inhd_binders.length = 0 then return none
else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$>
print_arguments inhd_binders
/-- A linter object for `inhabited_nonempty`. -/
@[linter] meta def linter.inhabited_nonempty : linter :=
{ test := inhabited_nonempty,
auto_decls := ff,
no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`.",
errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." }
/-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _`
hypothesis that is unused lsewhere in the type.
In this case, that hypothesis can be replaced with `classical` in the proof.
Theorems in the `decidable` namespace are exempt from the check. -/
private meta def decidable_classical (d : declaration) : tactic (option string) :=
do tt ← is_prop d.type | return none,
ff ← pure $ (`decidable).is_prefix_of d.to_name | return none,
(binders, _) ← get_pi_binders_nondep d.type,
let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq
∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel
∨ pr.2.type.is_app_of `decidable,
if deceq_binders.length = 0 then return none
else (λ s, some $ "The following `decidable` hypotheses should be replaced with
`classical` in the proof. " ++ s) <$>
print_arguments deceq_binders
/-- A linter object for `decidable_classical`. -/
@[linter] meta def linter.decidable_classical : linter :=
{ test := decidable_classical,
auto_decls := ff,
no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`.",
errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." }
/- The file `logic/basic.lean` emphasizes the differences between what holds under classical
and non-classical logic. It makes little sense to make all these lemmas classical, so we add them
to the list of lemmas which are not checked by the linter `decidable_classical`. -/
attribute [nolint decidable_classical] dec_em dec_em' not.decidable_imp_symm
private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) :=
retrieve $ do
tt ← return d.is_trusted | pure none,
mk_meta_var d.type >>= set_goals ∘ pure,
args ← unfreezing intros,
expr.sort _ ← target | pure none,
let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args,
some coe_fn_inst ←
try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none,
some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ←
try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none,
tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none,
set_bool_option `pp.all true,
trans_inst_1 ← pp trans_inst_1,
trans_inst_2 ← pp trans_inst_2,
pure $ format.to_string $
"`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++
trans_inst_1.group.indent 2 ++
format.line ++ "and" ++
trans_inst_2.group.indent 2
/-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/
@[linter] meta def linter.has_coe_to_fun : linter :=
{ test := has_coe_to_fun_linter,
auto_decls := tt,
no_errors_found := "has_coe_to_fun is used correctly",
errors_found := "INVALID/MISSING `has_coe_to_fun` instances.
You should add a `has_coe_to_fun` instance for the following types.
See Note [function coercion]." }
/--
Checks whether an instance contains a semireducible non-instance with a class as
type in its value. We add some restrictions to get not too many false positives:
* We only consider classes with an `add` or `mul` field, since those classes are most likely to
occur as a field to another class, and be an extension of another class.
* We only consider instances of type-valued classes and non-instances that are definitions.
* We currently ignore declarations `foo` that have a `foo._main` declaration. We could look inside,
or at the generated equation lemmas, but it's unlikely that there are many problematic instances
defined using the equation compiler.
-/
meta def check_reducible_non_instances (d : declaration) : tactic (option string) := do
tt ← is_instance d.to_name | return none,
ff ← is_prop d.type | return none,
env ← get_env,
-- We only check if the class of the instance contains an `add` or a `mul` field.
let cls := d.type.pi_codomain.get_app_fn.const_name,
some constrs ← return $ env.structure_fields cls | return none,
tt ← return $ constrs.mem `add || constrs.mem `mul | return none,
l ← d.value.list_constant.mfilter $ λ nm, do {
d ← env.get nm,
ff ← is_instance nm | return ff,
tt ← is_class d.type | return ff,
tt ← return d.is_definition | return ff,
-- We only check if the class of the non-instance contains an `add` or a `mul` field.
let cls := d.type.pi_codomain.get_app_fn.const_name,
some constrs ← return $ env.structure_fields cls | return ff,
tt ← return $ constrs.mem `add || constrs.mem `mul | return ff,
ff ← has_attribute' `reducible nm | return ff,
return tt },
if l.empty then return none else
-- we currently ignore declarations that have a `foo._main` declaration.
if l.to_list = [d.to_name ++ `_main] then return none else
return $ some $ "This instance contains the declarations " ++ to_string l.to_list ++
", which are semireducible non-instances."
/-- A linter that checks whether an instance contains a semireducible non-instance. -/
@[linter]
meta def linter.check_reducibility : linter :=
{ test := check_reducible_non_instances,
auto_decls := ff,
no_errors_found :=
"All non-instances are reducible.",
errors_found := "THE FOLLOWING INSTANCES MIGHT NOT REDUCE.
These instances contain one or more declarations that are not instances and are also not marked
`@[reducible]`. This means that type-class inference cannot unfold these declarations, " ++
"which might mean that type-class inference cannot infer that two instances are definitionally " ++
"equal. This can cause unexpected errors when this class occurs " ++
"as an *argument* to a type-class problem. See note [reducible non-instances].",
is_fast := tt }
|
f4b1223d3ba6355aba9a876dd675a56e2712765d | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Init/Prelude.lean | db8c0b245d26d0b31c0ef19e3996047581eeaeeb | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 76,266 | 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
universe u v w
@[inline] def id {α : Sort u} (a : α) : α := a
/- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=
fun x => f (g x)
abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=
fun x => a
set_option checkBinderAnnotations false in
@[reducible] def inferInstance {α : Sort u} [i : α] : α := i
set_option checkBinderAnnotations false in
@[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PUnit : Sort u where
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
inductive True : Prop where
| intro : True
inductive False : Prop
inductive Empty : Type
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PEmpty : Sort u where
def Not (a : Prop) : Prop := a → False
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=
False.elim (h₂ h₁)
inductive Eq {α : Sort u} (a : α) : α → Prop where
| refl {} : Eq a a
@[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=
Eq.rec (motive := fun α _ => motive α) m h
@[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a
@[simp] theorem id_eq (a : α) : Eq (id a) a := rfl
theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=
Eq.ndrec h₂ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=
h ▸ rfl
theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c :=
h₂ ▸ h₁
@[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=
Eq.rec (motive := fun α _ => α) a h
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=
h ▸ rfl
theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) :=
h₁ ▸ h₂ ▸ rfl
theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) :=
h ▸ rfl
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where
| refl {} : HEq a a
@[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a :=
HEq.refl a
theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=
have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=
fun α β a b h₁ =>
HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)
(fun (h₂ : Eq α α) => rfl)
h₁
this α α a a' h rfl
structure Prod (α : Type u) (β : Type v) where
fst : α
snd : β
attribute [unbox] Prod
/-- Similar to `Prod`, but `α` and `β` can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) where
fst : α
snd : β
/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/
structure MProd (α β : Type u) where
fst : α
snd : β
structure And (a b : Prop) : Prop where
intro :: (left : a) (right : b)
inductive Or (a b : Prop) : Prop where
| inl (h : a) : Or a b
| inr (h : b) : Or a b
inductive Bool : Type where
| false : Bool
| true : Bool
export Bool (false true)
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) where
val : α
property : p val
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
/- Auxiliary axiom used to implement `sorry`. -/
@[extern "lean_sorry", neverExtract]
axiom sorryAx (α : Sort u) (synthetic := true) : α
theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false)
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true)
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
class Inhabited (α : Sort u) where
mk {} :: (default : α)
constant arbitrary [Inhabited α] : α :=
Inhabited.default
instance : Inhabited (Sort u) where
default := PUnit
instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where
default := fun _ => arbitrary
instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where
default := fun _ => arbitrary
deriving instance Inhabited for Bool
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u where
up :: (down : α)
/- Bijection between α and PLift α -/
theorem PLift.up_down {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b
| up a => rfl
theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a :=
rfl
/- Pointed types -/
structure PointedType where
(type : Type u)
(val : type)
instance : Inhabited PointedType.{u} where
default := { type := PUnit.{u+1}, val := ⟨⟩ }
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) where
up :: (down : α)
/- Bijection between α and ULift.{v} α -/
theorem ULift.up_down {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b
| up a => rfl
theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=
rfl
class inductive Decidable (p : Prop) where
| isFalse (h : Not p) : Decidable p
| isTrue (h : p) : Decidable p
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)
export Decidable (isTrue isFalse decide)
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
(a : α) → Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
(a b : α) → Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
(a b : α) → Decidable (Eq a b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=
s a b
theorem decide_eq_true : [s : Decidable p] → p → Eq (decide p) true
| isTrue _, _ => rfl
| isFalse h₁, h₂ => absurd h₂ h₁
theorem decide_eq_false : [s : Decidable p] → Not p → Eq (decide p) false
| isTrue h₁, h₂ => absurd h₁ h₂
| isFalse h, _ => rfl
theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true → p := fun h =>
match (generalizing := false) s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁))
theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false → Not p := fun h =>
match (generalizing := false) s with
| isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁))
| isFalse h₁ => h₁
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse (fun h => Bool.noConfusion h)
| true, false => isFalse (fun h => Bool.noConfusion h)
| true, true => isTrue rfl
class BEq (α : Type u) where
beq : α → α → Bool
open BEq (beq)
instance [DecidableEq α] : BEq α where
beq a b := decide (Eq a b)
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=
Decidable.casesOn (motive := fun _ => α) h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t)
@[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) :=
match dp with
| isTrue hp =>
match dq with
| isTrue hq => isTrue ⟨hp, hq⟩
| isFalse hq => isFalse (fun h => hq (And.right h))
| isFalse hp =>
isFalse (fun h => hp (And.left h))
@[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) :=
match dp with
| isTrue hp => isTrue (Or.inl hp)
| isFalse hp =>
match dq with
| isTrue hq => isTrue (Or.inr hq)
| isFalse hq =>
isFalse fun h => match h with
| Or.inl h => hp h
| Or.inr h => hq h
instance [dp : Decidable p] : Decidable (Not p) :=
match dp with
| isTrue hp => isFalse (absurd hp)
| isFalse hp => isTrue hp
/- Boolean operators -/
@[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α :=
match c with
| true => x
| false => y
@[macroInline] def or (x y : Bool) : Bool :=
match x with
| true => true
| false => y
@[macroInline] def and (x y : Bool) : Bool :=
match x with
| false => false
| true => y
@[inline] def not : Bool → Bool
| true => false
| false => true
inductive Nat where
| zero : Nat
| succ (n : Nat) : Nat
instance : Inhabited Nat where
default := Nat.zero
/- For numeric literals notation -/
class OfNat (α : Type u) (n : Nat) where
ofNat : α
@[defaultInstance 100] /- low prio -/
instance (n : Nat) : OfNat Nat n where
ofNat := n
class LE (α : Type u) where le : α → α → Prop
class LT (α : Type u) where lt : α → α → Prop
@[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a
@[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a
@[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α :=
ite (LT.lt b a) a b
@[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α :=
ite (LE.le a b) a b
class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAdd : α → β → γ
class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hSub : α → β → γ
class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMul : α → β → γ
class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hDiv : α → β → γ
class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMod : α → β → γ
class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hPow : α → β → γ
class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAppend : α → β → γ
class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hOrElse : α → β → γ
class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAndThen : α → β → γ
class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAnd : α → β → γ
class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hXor : α → β → γ
class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hOr : α → β → γ
class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hShiftLeft : α → β → γ
class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hShiftRight : α → β → γ
class Add (α : Type u) where
add : α → α → α
class Sub (α : Type u) where
sub : α → α → α
class Mul (α : Type u) where
mul : α → α → α
class Neg (α : Type u) where
neg : α → α
class Div (α : Type u) where
div : α → α → α
class Mod (α : Type u) where
mod : α → α → α
class Pow (α : Type u) (β : Type v) where
pow : α → β → α
class Append (α : Type u) where
append : α → α → α
class OrElse (α : Type u) where
orElse : α → α → α
class AndThen (α : Type u) where
andThen : α → α → α
class AndOp (α : Type u) where
and : α → α → α
class Xor (α : Type u) where
xor : α → α → α
class OrOp (α : Type u) where
or : α → α → α
class Complement (α : Type u) where
complement : α → α
class ShiftLeft (α : Type u) where
shiftLeft : α → α → α
class ShiftRight (α : Type u) where
shiftRight : α → α → α
@[defaultInstance]
instance [Add α] : HAdd α α α where
hAdd a b := Add.add a b
@[defaultInstance]
instance [Sub α] : HSub α α α where
hSub a b := Sub.sub a b
@[defaultInstance]
instance [Mul α] : HMul α α α where
hMul a b := Mul.mul a b
@[defaultInstance]
instance [Div α] : HDiv α α α where
hDiv a b := Div.div a b
@[defaultInstance]
instance [Mod α] : HMod α α α where
hMod a b := Mod.mod a b
@[defaultInstance]
instance [Pow α β] : HPow α β α where
hPow a b := Pow.pow a b
@[defaultInstance]
instance [Append α] : HAppend α α α where
hAppend a b := Append.append a b
@[defaultInstance]
instance [OrElse α] : HOrElse α α α where
hOrElse a b := OrElse.orElse a b
@[defaultInstance]
instance [AndThen α] : HAndThen α α α where
hAndThen a b := AndThen.andThen a b
@[defaultInstance]
instance [AndOp α] : HAnd α α α where
hAnd a b := AndOp.and a b
@[defaultInstance]
instance [Xor α] : HXor α α α where
hXor a b := Xor.xor a b
@[defaultInstance]
instance [OrOp α] : HOr α α α where
hOr a b := OrOp.or a b
@[defaultInstance]
instance [ShiftLeft α] : HShiftLeft α α α where
hShiftLeft a b := ShiftLeft.shiftLeft a b
@[defaultInstance]
instance [ShiftRight α] : HShiftRight α α α where
hShiftRight a b := ShiftRight.shiftRight a b
open HAdd (hAdd)
open HMul (hMul)
open HPow (hPow)
open HAppend (hAppend)
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
instance : Add Nat where
add := Nat.add
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_mul"]
protected def Nat.mul : (@& Nat) → (@& Nat) → Nat
| a, 0 => 0
| a, Nat.succ b => Nat.add (Nat.mul a b) a
instance : Mul Nat where
mul := Nat.mul
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_pow"]
protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat
| 0 => 1
| succ n => Nat.mul (Nat.pow m n) m
instance : Pow Nat Nat where
pow := Nat.pow
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_eq"]
def Nat.beq : (@& Nat) → (@& Nat) → Bool
| zero, zero => true
| zero, succ m => false
| succ n, zero => false
| succ n, succ m => beq n m
theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m
| zero, zero, h => rfl
| zero, succ m, h => Bool.noConfusion h
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have : Eq (beq n m) true := h
have : Eq n m := eq_of_beq_eq_true this
this ▸ rfl
theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m)
| zero, zero, h₁, h₂ => Bool.noConfusion h₁
| zero, succ m, h₁, h₂ => Nat.noConfusion h₂
| succ n, zero, h₁, h₂ => Nat.noConfusion h₂
| succ n, succ m, h₁, h₂ =>
have : Eq (beq n m) false := h₁
Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this))
@[extern "lean_nat_dec_eq"]
protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) :=
match h:beq n m with
| true => isTrue (eq_of_beq_eq_true h)
| false => isFalse (ne_of_beq_eq_false h)
@[inline] instance : DecidableEq Nat := Nat.decEq
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_le"]
def Nat.ble : @& Nat → @& Nat → Bool
| zero, zero => true
| zero, succ m => true
| succ n, zero => false
| succ n, succ m => ble n m
protected inductive Nat.le (n : Nat) : Nat → Prop
| refl : Nat.le n n
| step {m} : Nat.le n m → Nat.le n (succ m)
instance : LE Nat where
le := Nat.le
protected def Nat.lt (n m : Nat) : Prop :=
Nat.le (succ n) m
instance : LT Nat where
lt := Nat.lt
theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False
| 0, h => nomatch h
| succ n, h => nomatch h
theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) :=
not_succ_le_zero n
theorem Nat.zero_le : (n : Nat) → LE.le 0 n
| zero => Nat.le.refl
| succ n => Nat.le.step (zero_le n)
theorem Nat.succ_le_succ : LE.le n m → LE.le (succ n) (succ m)
| Nat.le.refl => Nat.le.refl
| Nat.le.step h => Nat.le.step (succ_le_succ h)
theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) :=
succ_le_succ (zero_le n)
theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) :=
Nat.le.step h
protected theorem Nat.le_trans {n m k : Nat} : LE.le n m → LE.le m k → LE.le n k
| h, Nat.le.refl => h
| h₁, Nat.le.step h₂ => Nat.le.step (Nat.le_trans h₁ h₂)
protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k :=
Nat.le_trans (le_step h₁)
theorem Nat.le_succ (n : Nat) : LE.le n (succ n) :=
Nat.le.step Nat.le.refl
theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) :=
Nat.le_trans h (le_succ m)
protected theorem Nat.le_refl (n : Nat) : LE.le n n :=
Nat.le.refl
theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) :=
zero_lt_succ n
set_option bootstrap.genMatcherCode false in
@[extern c inline "lean_nat_sub(#1, lean_box(1))"]
def Nat.pred : (@& Nat) → Nat
| 0 => 0
| succ a => a
theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m)
| _, _, Nat.le.refl => Nat.le.refl
| 0, succ m, Nat.le.step h => h
| succ n, succ m, Nat.le.step h => Nat.le_trans (le_succ _) h
theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m :=
pred_le_pred
theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n :=
le_of_succ_le_succ
protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m)
| zero, zero, h => Or.inl rfl
| zero, succ n, h => Or.inr (Nat.succ_le_succ (Nat.zero_le _))
| succ n, zero, h => absurd h (not_succ_le_zero _)
| succ n, succ m, h =>
have : LE.le n m := Nat.le_of_succ_le_succ h
match Nat.eq_or_lt_of_le this with
| Or.inl h => Or.inl (h ▸ rfl)
| Or.inr h => Or.inr (succ_le_succ h)
protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) :=
match m with
| zero => Or.inr (zero_le n)
| succ m =>
match Nat.lt_or_ge n m with
| Or.inl h => Or.inl (le_succ_of_le h)
| Or.inr h =>
match Nat.eq_or_lt_of_le h with
| Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _)
| Or.inr h1 => Or.inr h1
theorem Nat.not_succ_le_self : (n : Nat) → Not (LE.le (succ n) n)
| 0 => not_succ_le_zero _
| succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n)
protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) :=
Nat.not_succ_le_self n
protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (h₁ : LE.le n m) (h₂ : LT.lt m k) : LT.lt n k :=
Nat.le_trans (Nat.succ_le_succ h₁) h₂
protected theorem Nat.le_antisymm {n m : Nat} (h₁ : LE.le n m) (h₂ : LE.le m n) : Eq n m :=
match h₁ with
| Nat.le.refl => rfl
| Nat.le.step h => absurd (Nat.lt_of_le_of_lt h h₂) (Nat.lt_irrefl n)
protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m :=
match Nat.lt_or_ge n m with
| Or.inl h₃ => h₃
| Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂
theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m :=
match n, m with
| 0, _ => Nat.zero_le _
| succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h)
theorem Nat.ble_self_eq_true : (n : Nat) → Eq (Nat.ble n n) true
| 0 => rfl
| succ n => ble_self_eq_true n
theorem Nat.ble_succ_eq_true : {n m : Nat} → Eq (Nat.ble n m) true → Eq (Nat.ble n (succ m)) true
| 0, _, _ => rfl
| succ n, succ m, h => ble_succ_eq_true (n := n) h
theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true :=
match h with
| Nat.le.refl => Nat.ble_self_eq_true n
| Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h)
theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) :=
fun h' => absurd (Nat.ble_eq_true_of_le h') h
@[extern "lean_nat_dec_le"]
instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) :=
dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h))
@[extern "lean_nat_dec_lt"]
instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) :=
decLe (succ n) m
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_sub"]
protected def Nat.sub : (@& Nat) → (@& Nat) → Nat
| a, 0 => a
| a, succ b => pred (Nat.sub a b)
instance : Sub Nat where
sub := Nat.sub
@[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) :=
fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant
def System.Platform.numBits : Nat :=
(getNumBits ()).val
theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) :=
(getNumBits ()).property
structure Fin (n : Nat) where
val : Nat
isLt : LT.lt val n
theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val :=
h ▸ rfl
theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) :=
fun h' => absurd (val_eq_of_eq h') h
instance (n : Nat) : DecidableEq (Fin n) :=
fun i j =>
match decEq i.val j.val with
| isTrue h => isTrue (Fin.eq_of_val_eq h)
| isFalse h => isFalse (Fin.ne_of_val_ne h)
instance {n} : LT (Fin n) where
lt a b := LT.lt a.val b.val
instance {n} : LE (Fin n) where
le a b := LE.le a.val b.val
instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt ..
instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe ..
def UInt8.size : Nat := 256
structure UInt8 where
val : Fin UInt8.size
attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk
attribute [extern "lean_uint8_to_nat"] UInt8.val
@[extern "lean_uint8_of_nat"]
def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt8 := UInt8.decEq
instance : Inhabited UInt8 where
default := UInt8.ofNatCore 0 (by decide)
def UInt16.size : Nat := 65536
structure UInt16 where
val : Fin UInt16.size
attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk
attribute [extern "lean_uint16_to_nat"] UInt16.val
@[extern "lean_uint16_of_nat"]
def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt16 := UInt16.decEq
instance : Inhabited UInt16 where
default := UInt16.ofNatCore 0 (by decide)
def UInt32.size : Nat := 4294967296
structure UInt32 where
val : Fin UInt32.size
attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk
attribute [extern "lean_uint32_to_nat"] UInt32.val
@[extern "lean_uint32_of_nat"]
def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := {
val := { val := n, isLt := h }
}
@[extern "lean_uint32_to_nat"]
def UInt32.toNat (n : UInt32) : Nat := n.val.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt32 := UInt32.decEq
instance : Inhabited UInt32 where
default := UInt32.ofNatCore 0 (by decide)
instance : LT UInt32 where
lt a b := LT.lt a.val b.val
instance : LE UInt32 where
le a b := LE.le a.val b.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m))
instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b
instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b
def UInt64.size : Nat := 18446744073709551616
structure UInt64 where
val : Fin UInt64.size
attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk
attribute [extern "lean_uint64_to_nat"] UInt64.val
@[extern "lean_uint64_of_nat"]
def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt64 := UInt64.decEq
instance : Inhabited UInt64 where
default := UInt64.ofNatCore 0 (by decide)
def USize.size : Nat := hPow 2 System.Platform.numBits
theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) :=
show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from
match System.Platform.numBits, System.Platform.numBits_eq with
| _, Or.inl rfl => Or.inl (by decide)
| _, Or.inr rfl => Or.inr (by decide)
structure USize where
val : Fin USize.size
attribute [extern "lean_usize_of_nat_mk"] USize.mk
attribute [extern "lean_usize_to_nat"] USize.val
@[extern "lean_usize_of_nat"]
def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def USize.decEq (a b : USize) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq USize := USize.decEq
instance : Inhabited USize where
default := USize.ofNatCore 0 (match USize.size, usize_size_eq with
| _, Or.inl rfl => by decide
| _, Or.inr rfl => by decide)
@[extern "lean_usize_of_nat"]
def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := {
val := {
val := n
isLt := match USize.size, usize_size_eq with
| _, Or.inl rfl => h
| _, Or.inr rfl => Nat.lt_trans h (by decide)
}
}
abbrev Nat.isValidChar (n : Nat) : Prop :=
Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000))
abbrev UInt32.isValidChar (n : UInt32) : Prop :=
n.toNat.isValidChar
/-- The `Char` Type represents an unicode scalar value.
See http://www.unicode.org/glossary/#unicode_scalar_value). -/
structure Char where
val : UInt32
valid : val.isValidChar
private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size :=
match h with
| Or.inl h => Nat.lt_trans h (by decide)
| Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide)
@[extern "lean_uint32_of_nat"]
private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char :=
{ val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h }
@[noinline, matchPattern]
def Char.ofNat (n : Nat) : Char :=
dite (n.isValidChar)
(fun h => Char.ofNatAux n h)
(fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) })
theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val
| _, _, rfl => rfl
theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) :=
fun h' => absurd (val_eq_of_eq h') h
theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) :=
fun h' => absurd (eq_of_val_eq h') h
instance : DecidableEq Char :=
fun c d =>
match decEq c.val d.val with
| isTrue h => isTrue (Char.eq_of_val_eq h)
| isFalse h => isFalse (Char.ne_of_val_ne h)
def Char.utf8Size (c : Char) : UInt32 :=
let v := c.val
ite (LE.le v (UInt32.ofNatCore 0x7F (by decide)))
(UInt32.ofNatCore 1 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide)))
(UInt32.ofNatCore 2 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide)))
(UInt32.ofNatCore 3 (by decide))
(UInt32.ofNatCore 4 (by decide))))
inductive Option (α : Type u) where
| none : Option α
| some (val : α) : Option α
attribute [unbox] Option
export Option (none some)
instance {α} : Inhabited (Option α) where
default := none
@[macroInline] def Option.getD : Option α → α → α
| some x, _ => x
| none, e => e
inductive List (α : Type u) where
| nil : List α
| cons (head : α) (tail : List α) : List α
instance {α} : Inhabited (List α) where
default := List.nil
protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b)
| nil, nil => isTrue rfl
| cons a as, nil => isFalse (fun h => List.noConfusion h)
| nil, cons b bs => isFalse (fun h => List.noConfusion h)
| cons a as, cons b bs =>
match decEq a b with
| isTrue hab =>
match List.hasDecEq as bs with
| isTrue habs => isTrue (hab ▸ habs ▸ rfl)
| isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs))
| isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab))
instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq
@[specialize]
def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α
| a, nil => a
| a, cons b l => foldl f (f a b) l
def List.set : List α → Nat → α → List α
| cons a as, 0, b => cons b as
| cons a as, Nat.succ n, b => cons a (set as n b)
| nil, _, _ => nil
def List.length : List α → Nat
| nil => 0
| cons a as => HAdd.hAdd (length as) 1
def List.lengthTRAux : List α → Nat → Nat
| nil, n => n
| cons a as, n => lengthTRAux as (Nat.succ n)
def List.lengthTR (as : List α) : Nat :=
lengthTRAux as 0
@[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ :=
rfl
def List.concat {α : Type u} : List α → α → List α
| nil, b => cons b nil
| cons a as, b => cons a (concat as b)
def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α
| nil, i, h => absurd h (Nat.not_lt_zero _)
| cons a as, 0, h => a
| cons a as, Nat.succ i, h =>
have : LT.lt i.succ as.length.succ := length_cons .. ▸ h
get as i (Nat.le_of_succ_le_succ this)
structure String where
data : List Char
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 (Eq s₁ s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq String := String.decEq
/-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded.
Codepoint positions (counting the Unicode codepoints rather than bytes)
are represented by plain `Nat`s instead.
Indexing a `String` by a byte position is constant-time, while codepoint
positions need to be translated internally to byte positions in linear-time. -/
abbrev String.Pos := Nat
structure Substring where
str : String
startPos : String.Pos
stopPos : String.Pos
@[inline] def Substring.bsize : Substring → Nat
| ⟨_, b, e⟩ => e.sub b
def String.csize (c : Char) : Nat :=
c.utf8Size.toNat
private def String.utf8ByteSizeAux : List Char → Nat → Nat
| List.nil, r => r
| List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c))
@[extern "lean_string_utf8_byte_size"]
def String.utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def String.bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def String.toSubstring (s : String) : Substring := {
str := s
startPos := 0
stopPos := s.bsize
}
@[extern c inline "#3"]
unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β :=
cast lcProof (PUnit.{v})
@[neverExtract, extern "lean_panic_fn"]
constant panic {α : Type u} [Inhabited α] (msg : String) : α
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (α : Type u) where
data : List α
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_mk"] Array.mk
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := {
data := List.nil
}
def Array.empty {α : Type u} : Array α :=
mkEmpty 0
@[reducible, extern "lean_array_get_size"]
def Array.size {α : Type u} (a : @& Array α) : Nat :=
a.data.length
@[extern "lean_array_fget"]
def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α :=
a.data.get i.val i.isLt
@[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α :=
dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀)
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
Array.getD a i arbitrary
def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α :=
self.get! idx
@[extern "lean_array_push"]
def Array.push {α : Type u} (a : Array α) (v : α) : Array α := {
data := List.concat a.data v
}
@[extern "lean_array_fset"]
def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := {
data := a.data.set i.val v
}
@[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α :=
dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a)
@[extern "lean_array_set"]
def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α :=
Array.setD a i v
-- Slower `Array.append` used in quotations.
protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α :=
let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α :=
dite (LT.lt j bs.size)
(fun hlt =>
match i with
| 0 => as
| Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩)))
(fun _ => as)
loop bs.size 0 as
@[inlineIfReduce]
def List.toArrayAux : List α → Array α → Array α
| nil, r => r
| cons a as, r => toArrayAux as (r.push a)
@[inlineIfReduce]
def List.redLength : List α → Nat
| nil => 0
| cons _ as => as.redLength.succ
@[inline, matchPattern, export lean_list_to_array]
def List.toArray (as : List α) : Array α :=
as.toArrayAux (Array.mkEmpty as.redLength)
class Bind (m : Type u → Type v) where
bind : {α β : Type u} → m α → (α → m β) → m β
export Bind (bind)
class Pure (f : Type u → Type v) where
pure {α : Type u} : α → f α
export Pure (pure)
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)
class Seq (f : Type u → Type v) : Type (max (u+1) v) where
seq : {α β : Type u} → f (α → β) → f α → f β
class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
seqLeft : {α β : Type u} → f α → f β → f α
class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
seqRight : {α β : Type u} → f α → f β → f β
class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y x
seqLeft x y := bind x fun a => bind y (fun _ => pure a)
seqRight x y := bind x fun _ => y
instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where
default := pure
instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where
default := pure arbitrary
-- A fusion of Haskell's `sequence` and `map`
def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) :=
let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) :=
dite (LT.lt j as.size)
(fun hlt =>
match i with
| 0 => pure bs
| Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b))
(fun _ => bs)
loop as.size 0 Array.empty
/-- A Function for lifting a computation from an inner Monad to an outer Monad.
Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),
but `n` does not have to be a monad transformer.
Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/
class MonadLift (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
/-- The reflexive-transitive closure of `MonadLift`.
`monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`.
Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/
class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
export MonadLiftT (monadLift)
abbrev liftM := @monadLift
instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where
monadLift x := MonadLift.monadLift (m := n) (monadLift x)
instance (m) : MonadLiftT m m where
monadLift x := x
/-- A functor in the category of monads. Can be used to lift monad-transforming functions.
Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),
but not restricted to monad transformers.
Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/
class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
/-- The reflexive-transitive closure of `MonadFunctor`.
`monadMap` is used to transitively lift Monad morphisms -/
class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
export MonadFunctorT (monadMap)
instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where
monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f)
instance monadFunctorRefl (m) : MonadFunctorT m m where
monadMap f := f
inductive Except (ε : Type u) (α : Type v) where
| error : ε → Except ε α
| ok : α → Except ε α
attribute [unbox] Except
instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where
default := Except.error arbitrary
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class MonadExceptOf (ε : Type u) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α :=
MonadExceptOf.throw e
abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α :=
MonadExceptOf.tryCatch x handle
/-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
export MonadExcept (throw tryCatch)
instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where
throw := throwThe ε
tryCatch := tryCatchThe ε
namespace MonadExcept
variable {ε : Type u} {m : Type v → Type w}
@[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α :=
tryCatch t₁ fun _ => t₂
instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where
orElse := MonadExcept.orelse
end MonadExcept
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
ρ → m α
instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where
default := fun _ => arbitrary
@[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α :=
x r
namespace ReaderT
section
variable {ρ : Type u} {m : Type u → Type v} {α : Type u}
instance : MonadLift m (ReaderT ρ m) where
monadLift x := fun _ => x
instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where
throw e := liftM (m := m) (throw e)
tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r)
end
section
variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u}
@[inline] protected def read : ReaderT ρ m ρ :=
pure
@[inline] protected def pure (a : α) : ReaderT ρ m α :=
fun r => pure a
@[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β :=
fun r => bind (x r) fun a => f a r
@[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β :=
fun r => Functor.map f (x r)
instance : Monad (ReaderT ρ m) where
pure := ReaderT.pure
bind := ReaderT.bind
map := ReaderT.map
instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where
monadMap f x := fun ctx => f (x ctx)
@[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α :=
fun x r => x (f r)
end
end ReaderT
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this Function cannot be lifted using `monadLift`.
Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where
lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α
```
-/
class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where
read : m ρ
@[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ :=
MonadReaderOf.read
/-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/
class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where
read : m ρ
export MonadReader (read)
instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where
read := readThe ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where
read := liftM (m := m) read
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where
read := ReaderT.read
class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
@[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α :=
MonadWithReaderOf.withReader f x
class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
export MonadWithReader (withReader)
instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where
withReader := withTheReader ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where
withReader f := monadMap (m := m) (withTheReader ρ f)
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where
withReader f x := fun ctx => x (f ctx)
/-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html).
In contrast to the Haskell implementation, we use overlapping instances to derive instances
automatically from `monadLift`. -/
class MonadStateOf (σ : Type u) (m : Type u → Type v) where
/- Obtain the top-most State of a Monad stack. -/
get : m σ
/- Set the top-most State of a Monad stack. -/
set : σ → m PUnit
/- Map the top-most State of a Monad stack.
Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a`
because the latter does not use the State linearly (without sufficient inlining). -/
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadStateOf (set)
abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ :=
MonadStateOf.get
@[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit :=
MonadStateOf.modifyGet fun s => (PUnit.unit, f s)
@[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α :=
MonadStateOf.modifyGet f
/-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/
class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where
get : m σ
set : σ → m PUnit
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadState (get modifyGet)
instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where
set := MonadStateOf.set
get := getThe σ
modifyGet f := MonadStateOf.modifyGet f
@[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit :=
modifyGet fun s => (PUnit.unit, f s)
@[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ :=
modifyGet fun s => (s, f s)
-- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer
-- will be picked first
instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where
get := liftM (m := m) MonadStateOf.get
set s := liftM (m := m) (MonadStateOf.set s)
modifyGet f := monadLift (m := m) (MonadState.modifyGet f)
namespace EStateM
inductive Result (ε σ α : Type u) where
| ok : α → σ → Result ε σ α
| error : ε → σ → Result ε σ α
variable {ε σ α : Type u}
instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where
default := Result.error arbitrary arbitrary
end EStateM
open EStateM (Result) in
def EStateM (ε σ α : Type u) := σ → Result ε σ α
namespace EStateM
variable {ε σ α β : Type u}
instance [Inhabited ε] : Inhabited (EStateM ε σ α) where
default := fun s => Result.error arbitrary s
@[inline] protected def pure (a : α) : EStateM ε σ α := fun s =>
Result.ok a s
@[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ =>
Result.ok ⟨⟩ s
@[inline] protected def get : EStateM ε σ σ := fun s =>
Result.ok s s
@[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s =>
match f s with
| (a, s) => Result.ok a s
@[inline] protected def throw (e : ε) : EStateM ε σ α := fun s =>
Result.error e s
/-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/
class Backtrackable (δ : outParam (Type u)) (σ : Type u) where
save : σ → δ
restore : σ → δ → σ
@[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s
match x s with
| Result.error e s => handle e (Backtrackable.restore s d)
| ok => ok
@[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s;
match x₁ s with
| Result.error _ s => x₂ (Backtrackable.restore s d)
| ok => ok
@[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s =>
match x s with
| Result.error e s => Result.error (f e) s
| Result.ok a s => Result.ok a s
@[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => f a s
| Result.error e s => Result.error e s
@[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => Result.ok (f a) s
| Result.error e s => Result.error e s
@[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok _ s => y s
| Result.error e s => Result.error e s
instance : Monad (EStateM ε σ) where
bind := EStateM.bind
pure := EStateM.pure
map := EStateM.map
seqRight := EStateM.seqRight
instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where
orElse := EStateM.orElse
instance : MonadStateOf σ (EStateM ε σ) where
set := EStateM.set
get := EStateM.get
modifyGet := EStateM.modifyGet
instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where
throw := EStateM.throw
tryCatch := EStateM.tryCatch
@[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α :=
x s
@[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α :=
match run x s with
| Result.ok v _ => some v
| Result.error .. => none
@[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩
@[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s
/- Dummy default instance -/
instance nonBacktrackable : Backtrackable PUnit σ where
save := dummySave
restore := dummyRestore
end EStateM
class Hashable (α : Sort u) where
hash : α → UInt64
export Hashable (hash)
@[extern c inline "(size_t)#1"]
constant UInt64.toUSize (u : UInt64) : USize
@[extern c inline "(uint64_t)#1"]
constant USize.toUInt64 (u : USize) : UInt64
@[extern "lean_uint64_mix_hash"]
constant mixHash (u₁ u₂ : UInt64) : UInt64
@[extern "lean_string_hash"]
protected constant String.hash (s : @& String) : UInt64
instance : Hashable String where
hash := String.hash
namespace Lean
/- Hierarchical names -/
inductive Name where
| anonymous : Name
| str : Name → String → UInt64 → Name
| num : Name → Nat → UInt64 → Name
instance : Inhabited Name where
default := Name.anonymous
protected def Name.hash : Name → UInt64
| Name.anonymous => UInt64.ofNatCore 1723 (by decide)
| Name.str p s h => h
| Name.num p v h => h
instance : Hashable Name where
hash := Name.hash
namespace Name
@[export lean_name_mk_string]
def mkStr (p : Name) (s : String) : Name :=
Name.str p s (mixHash (hash p) (hash s))
@[export lean_name_mk_numeral]
def mkNum (p : Name) (v : Nat) : Name :=
Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide))))
def mkSimple (s : String) : Name :=
mkStr Name.anonymous s
@[extern "lean_name_eq"]
protected def beq : (@& Name) → (@& Name) → Bool
| anonymous, anonymous => true
| str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂)
| num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂)
| _, _ => false
instance : BEq Name where
beq := Name.beq
protected def append : Name → Name → Name
| n, anonymous => n
| n, str p s _ => Name.mkStr (Name.append n p) s
| n, num p d _ => Name.mkNum (Name.append n p) d
instance : Append Name where
append := Name.append
end Name
/- Syntax -/
/-- Source information of tokens. -/
inductive SourceInfo where
/-
Token from original input with whitespace and position information.
`leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing,
it is not at all clear what the preceding token was, especially with backtracking. -/
| original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos)
/-
Synthesized token (e.g. from a quotation) annotated with a span from the original source.
In the delaborator, we "misuse" this constructor to store synthetic positions identifying
subterms. -/
| synthetic (pos : String.Pos) (endPos : String.Pos)
/- Synthesized token without position information. -/
| protected none
instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩
namespace SourceInfo
def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos :=
match info, originalOnly with
| original (pos := pos) .., _ => some pos
| synthetic (pos := pos) .., false => some pos
| _, _ => none
end SourceInfo
abbrev SyntaxNodeKind := Name
/- Syntax AST -/
inductive Syntax where
| missing : Syntax
| node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax
| atom (info : SourceInfo) (val : String) : Syntax
| ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax
instance : Inhabited Syntax where
default := Syntax.missing
/- Builtin kinds -/
def choiceKind : SyntaxNodeKind := `choice
def nullKind : SyntaxNodeKind := `null
def groupKind : SyntaxNodeKind := `group
def identKind : SyntaxNodeKind := `ident
def strLitKind : SyntaxNodeKind := `strLit
def charLitKind : SyntaxNodeKind := `charLit
def numLitKind : SyntaxNodeKind := `numLit
def scientificLitKind : SyntaxNodeKind := `scientificLit
def nameLitKind : SyntaxNodeKind := `nameLit
def fieldIdxKind : SyntaxNodeKind := `fieldIdx
def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind
def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind
namespace Syntax
def getKind (stx : Syntax) : SyntaxNodeKind :=
match stx with
| Syntax.node k args => k
-- We use these "pseudo kinds" for antiquotation kinds.
-- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident)
-- is compiled to ``if stx.isOfKind `ident ...``
| Syntax.missing => `missing
| Syntax.atom _ v => Name.mkSimple v
| Syntax.ident .. => identKind
def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax :=
match stx with
| Syntax.node _ args => Syntax.node k args
| _ => stx
def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool :=
beq stx.getKind k
def getArg (stx : Syntax) (i : Nat) : Syntax :=
match stx with
| Syntax.node _ args => args.getD i Syntax.missing
| _ => Syntax.missing
-- Add `stx[i]` as sugar for `stx.getArg i`
@[inline] def getOp (self : Syntax) (idx : Nat) : Syntax :=
self.getArg idx
def getArgs (stx : Syntax) : Array Syntax :=
match stx with
| Syntax.node _ args => args
| _ => Array.empty
def getNumArgs (stx : Syntax) : Nat :=
match stx with
| Syntax.node _ args => args.size
| _ => 0
def isMissing : Syntax → Bool
| Syntax.missing => true
| _ => false
def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool :=
and (stx.isOfKind k) (beq stx.getNumArgs n)
def isIdent : Syntax → Bool
| ident _ _ _ _ => true
| _ => false
def getId : Syntax → Name
| ident _ _ val _ => val
| _ => Name.anonymous
def matchesNull (stx : Syntax) (n : Nat) : Bool :=
isNodeOf stx nullKind n
def matchesIdent (stx : Syntax) (id : Name) : Bool :=
and stx.isIdent (beq stx.getId id)
def setArgs (stx : Syntax) (args : Array Syntax) : Syntax :=
match stx with
| node k _ => node k args
| stx => stx
def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax :=
match stx with
| node k args => node k (args.setD i arg)
| stx => stx
/-- Retrieve the left-most leaf's info in the Syntax tree. -/
partial def getHeadInfo? : Syntax → Option SourceInfo
| atom info _ => some info
| ident info .. => some info
| node _ args =>
let rec loop (i : Nat) : Option SourceInfo :=
match decide (LT.lt i args.size) with
| true => match getHeadInfo? (args.get! i) with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _ => none
/-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/
partial def getHeadInfo (stx : Syntax) : SourceInfo :=
match stx.getHeadInfo? with
| some info => info
| none => SourceInfo.none
def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
stx.getHeadInfo.getPos? originalOnly
partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
match stx, originalOnly with
| atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos
| ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos
| node _ args, _ =>
let rec loop (i : Nat) : Option String.Pos :=
match decide (LT.lt i args.size) with
| true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _, _ => none
/--
An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically
remove/insert the separators. -/
structure SepArray (sep : String) where
elemsAndSeps : Array Syntax
end Syntax
def SourceInfo.fromRef (ref : Syntax) : SourceInfo :=
match ref.getPos?, ref.getTailPos? with
| some pos, some tailPos => SourceInfo.synthetic pos tailPos
| _, _ => SourceInfo.none
def mkAtom (val : String) : Syntax :=
Syntax.atom SourceInfo.none val
def mkAtomFrom (src : Syntax) (val : String) : Syntax :=
Syntax.atom (SourceInfo.fromRef src) val
/- Parser descriptions -/
inductive ParserDescr where
| const (name : Name)
| unary (name : Name) (p : ParserDescr)
| binary (name : Name) (p₁ p₂ : ParserDescr)
| node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr)
| trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr)
| symbol (val : String)
| nonReservedSymbol (val : String) (includeIdent : Bool)
| cat (catName : Name) (rbp : Nat)
| parser (declName : Name)
| nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr)
| sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
| sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
instance : Inhabited ParserDescr where
default := ParserDescr.symbol ""
abbrev TrailingParserDescr := ParserDescr
/-
Runtime support for making quotation terms auto-hygienic, by mangling identifiers
introduced by them with a "macro scope" supplied by the context. Details to appear in a
paper soon.
-/
abbrev MacroScope := Nat
/-- Macro scope used internally. It is not available for our frontend. -/
def reservedMacroScope := 0
/-- First macro scope available for our frontend -/
def firstFrontendMacroScope := hAdd reservedMacroScope 1
class MonadRef (m : Type → Type) where
getRef : m Syntax
withRef {α} : Syntax → m α → m α
export MonadRef (getRef)
instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where
getRef := liftM (getRef : m _)
withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x
def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax :=
match ref.getPos? with
| some _ => ref
| _ => oldRef
@[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α :=
bind getRef fun oldRef =>
let ref := replaceRef ref oldRef
MonadRef.withRef ref x
/-- A monad that supports syntax quotations. Syntax quotations (in term
position) are monadic values that when executed retrieve the current "macro
scope" from the monad and apply it to every identifier they introduce
(independent of whether this identifier turns out to be a reference to an
existing declaration, or an actually fresh binding during further
elaboration). We also apply the position of the result of `getRef` to each
introduced symbol, which results in better error positions than not applying
any position. -/
class MonadQuotation (m : Type → Type) extends MonadRef m where
-- Get the fresh scope of the current macro invocation
getCurrMacroScope : m MacroScope
getMainModule : m Name
/- Execute action in a new macro invocation context. This transformer should be
used at all places that morally qualify as the beginning of a "macro call",
e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it
can also be used internally inside a "macro" if identifiers introduced by
e.g. different recursive calls should be independent and not collide. While
returning an intermediate syntax tree that will recursively be expanded by
the elaborator can be used for the same effect, doing direct recursion inside
the macro guarded by this transformer is often easier because one is not
restricted to passing a single syntax tree. Modelling this helper as a
transformer and not just a monadic action ensures that the current macro
scope before the recursive call is restored after it, as expected. -/
withFreshMacroScope {α : Type} : m α → m α
export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope)
def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do
SourceInfo.fromRef (← getRef)
instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where
getCurrMacroScope := liftM (m := m) getCurrMacroScope
getMainModule := liftM (m := m) getMainModule
withFreshMacroScope := monadMap (m := m) withFreshMacroScope
/-
We represent a name with macro scopes as
```
<actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes>
```
Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5]
```
foo.bla._@.Init.Data.List.Basic._hyg.2.5
```
We may have to combine scopes from different files/modules.
The main modules being processed is always the right most one.
This situation may happen when we execute a macro generated in
an imported file in the current file.
```
foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4
```
The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance.
-/
def Name.hasMacroScopes : Name → Bool
| str _ s _ => beq s "_hyg"
| num p _ _ => hasMacroScopes p
| _ => false
private def eraseMacroScopesAux : Name → Name
| Name.str p s _ => match beq s "_@" with
| true => p
| false => eraseMacroScopesAux p
| Name.num p _ _ => eraseMacroScopesAux p
| Name.anonymous => Name.anonymous
@[export lean_erase_macro_scopes]
def Name.eraseMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => eraseMacroScopesAux n
| false => n
private def simpMacroScopesAux : Name → Name
| Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i
| n => eraseMacroScopesAux n
/- Helper function we use to create binder names that do not need to be unique. -/
@[export lean_simp_macro_scopes]
def Name.simpMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => simpMacroScopesAux n
| false => n
structure MacroScopesView where
name : Name
imported : Name
mainModule : Name
scopes : List MacroScope
instance : Inhabited MacroScopesView where
default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩
def MacroScopesView.review (view : MacroScopesView) : Name :=
match view.scopes with
| List.nil => view.name
| List.cons _ _ =>
let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg")
view.scopes.foldl Name.mkNum base
private def assembleParts : List Name → Name → Name
| List.nil, acc => acc
| List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s)
| List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n)
| _, acc => panic "Error: unreachable @ assembleParts"
private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps }
| false => extractImported scps mainModule p (List.cons n parts)
| n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts)
| _, _ => panic "Error: unreachable @ extractImported"
private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps }
| false => extractMainModule scps p (List.cons n parts)
| n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil
| _, _ => panic "Error: unreachable @ extractMainModule"
private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView
| Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc)
| Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg"
| _, _ => panic "Error: unreachable @ extractMacroScopesAux"
/--
Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`.
This operation is useful for analyzing/transforming the original identifiers, then adding back
the scopes (via `MacroScopesView.review`). -/
def extractMacroScopes (n : Name) : MacroScopesView :=
match n.hasMacroScopes with
| true => extractMacroScopesAux n List.nil
| false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous }
def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name :=
match n.hasMacroScopes with
| true =>
let view := extractMacroScopes n
match beq view.mainModule mainModule with
| true => Name.mkNum n scp
| false =>
{ view with
imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule)
mainModule := mainModule
scopes := List.cons scp List.nil
}.review
| false =>
Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp
@[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name :=
bind getMainModule fun mainModule =>
bind getCurrMacroScope fun scp =>
pure (Lean.addMacroScope mainModule n scp)
def defaultMaxRecDepth := 512
def maxRecDepthErrorMessage : String :=
"maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)"
namespace Macro
/- References -/
private constant MethodsRefPointed : PointedType.{0}
private def MethodsRef : Type := MethodsRefPointed.type
structure Context where
methods : MethodsRef
mainModule : Name
currMacroScope : MacroScope
currRecDepth : Nat := 0
maxRecDepth : Nat := defaultMaxRecDepth
ref : Syntax
inductive Exception where
| error : Syntax → String → Exception
| unsupportedSyntax : Exception
structure State where
macroScope : MacroScope
traceMsgs : List (Prod Name String) := List.nil
deriving Inhabited
end Macro
abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State)
abbrev Macro := Syntax → MacroM Syntax
namespace Macro
instance : MonadRef MacroM where
getRef := bind read fun ctx => pure ctx.ref
withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x
def addMacroScope (n : Name) : MacroM Name :=
bind read fun ctx =>
pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope)
def throwUnsupported {α} : MacroM α :=
throw Exception.unsupportedSyntax
def throwError {α} (msg : String) : MacroM α :=
bind getRef fun ref =>
throw (Exception.error ref msg)
def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α :=
withRef ref (throwError msg)
@[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α :=
bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh =>
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
@[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α :=
bind read fun ctx =>
match beq ctx.currRecDepth ctx.maxRecDepth with
| true => throw (Exception.error ref maxRecDepthErrorMessage)
| false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x
instance : MonadQuotation MacroM where
getCurrMacroScope ctx := pure ctx.currMacroScope
getMainModule ctx := pure ctx.mainModule
withFreshMacroScope := Macro.withFreshMacroScope
structure Methods where
expandMacro? : Syntax → MacroM (Option Syntax)
getCurrNamespace : MacroM Name
hasDecl : Name → MacroM Bool
resolveNamespace? : Name → MacroM (Option Name)
resolveGlobalName : Name → MacroM (List (Prod Name (List String)))
deriving Inhabited
unsafe def mkMethodsImp (methods : Methods) : MethodsRef :=
unsafeCast methods
@[implementedBy mkMethodsImp]
constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val
instance : Inhabited MethodsRef where
default := mkMethods arbitrary
unsafe def getMethodsImp : MacroM Methods :=
bind read fun ctx => pure (unsafeCast (ctx.methods))
@[implementedBy getMethodsImp] constant getMethods : MacroM Methods
/-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/
def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do
(← getMethods).expandMacro? stx
/-- Return `true` if the environment contains a declaration with name `declName` -/
def hasDecl (declName : Name) : MacroM Bool := do
(← getMethods).hasDecl declName
def getCurrNamespace : MacroM Name := do
(← getMethods).getCurrNamespace
def resolveNamespace? (n : Name) : MacroM (Option Name) := do
(← getMethods).resolveNamespace? n
def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do
(← getMethods).resolveGlobalName n
def trace (clsName : Name) (msg : String) : MacroM Unit := do
modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs }
end Macro
export Macro (expandMacro?)
namespace PrettyPrinter
abbrev UnexpandM := EStateM Unit Unit
/--
Function that tries to reverse macro expansions as a post-processing step of delaboration.
While less general than an arbitrary delaborator, it can be declared without importing `Lean`.
Used by the `[appUnexpander]` attribute. -/
-- a `kindUnexpander` could reasonably be added later
abbrev Unexpander := Syntax → UnexpandM Syntax
-- unexpanders should not need to introduce new names
instance : MonadQuotation UnexpandM where
getRef := pure Syntax.missing
withRef := fun _ => id
getCurrMacroScope := pure 0
getMainModule := pure `_fakeMod
withFreshMacroScope := id
end PrettyPrinter
end Lean
|
6d3dbefa014aad195cd44bd365d2bf9c663a3859 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/data/bool/basic.lean | 0595c7acffbef30a36a67ec9096ef3e55add1f2e | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 782 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.core
/-!
# Boolean operations
-/
/-- `cond b x y` is `x` if `b = tt` and `y` otherwise. -/
@[inline] def {u} cond {a : Type u} : bool → a → a → a
| tt x y := x
| ff x y := y
/-- Boolean OR -/
@[inline] def bor : bool → bool → bool
| tt b := tt
| ff b := b
/-- Boolean AND -/
@[inline] def band : bool → bool → bool
| tt b := b
| ff b := ff
/-- Boolean NOT -/
@[inline] def bnot : bool → bool
| tt := ff
| ff := tt
/-- Boolean XOR -/
@[inline] def bxor : bool → bool → bool
| tt ff := tt
| ff tt := tt
| _ _ := ff
notation x || y := bor x y
notation x && y := band x y
|
1f8b7f9d39be34f7af023e63704caac15bdc3125 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/combinatorics/simple_graph/matching.lean | 9575ac48b595404679a62ae90ccea0fd1ca6b30f | [
"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 | 2,010 | lean | /-
Copyright (c) 2020 Alena Gusakov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alena Gusakov
-/
import data.fintype.basic
import data.sym2
import combinatorics.simple_graph.basic
/-!
# Matchings
## Main definitions
* a `matching` on a simple graph is a subset of its edge set such that
no two edges share an endpoint.
* a `perfect_matching` on a simple graph is a matching in which every
vertex belongs to an edge.
TODO:
- Lemma stating that the existence of a perfect matching on `G` implies that
the cardinality of `V` is even (assuming it's finite)
- Hall's Marriage Theorem
- Tutte's Theorem
- consider coercions instead of type definition for `matching`:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532935457
- consider expressing `matching_verts` as union:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532906131
TODO: Tutte and Hall require a definition of subgraphs.
-/
open finset
universe u
namespace simple_graph
variables {V : Type u} (G : simple_graph V)
/--
A matching on `G` is a subset of its edges such that no two edges share a vertex.
-/
structure matching :=
(edges : set (sym2 V))
(sub_edges : edges ⊆ G.edge_set)
(disjoint : ∀ (x y ∈ edges) (v : V), v ∈ x ∧ v ∈ y → x = y)
instance : inhabited (matching G) :=
⟨⟨∅, set.empty_subset _, λ _ _ hx, false.elim (set.not_mem_empty _ hx)⟩⟩
variables {G}
/--
`M.support` is the set of vertices of `G` that are
contained in some edge of matching `M`
-/
def matching.support (M : G.matching) : set V :=
{v : V | ∃ x ∈ M.edges, v ∈ x}
/--
A perfect matching `M` on graph `G` is a matching such that
every vertex is contained in an edge of `M`.
-/
def matching.is_perfect (M : G.matching) : Prop :=
M.support = set.univ
lemma matching.is_perfect_iff (M : G.matching) :
M.is_perfect ↔ ∀ (v : V), ∃ e ∈ M.edges, v ∈ e :=
set.eq_univ_iff_forall
end simple_graph
|
72f8a2e1694cef35a3b343d164a2353437f40a1f | b9a81ebb9de684db509231c4469a7d2c88915808 | /src/super/cdcl_solver.lean | a6344289e251f54a426fb6ba0fc6bd2cd2c79eae | [] | no_license | leanprover/super | 3dd81ce8d9ac3cba20bce55e84833fadb2f5716e | 47b107b4cec8f3b41d72daba9cbda2f9d54025de | refs/heads/master | 1,678,482,996,979 | 1,676,526,367,000 | 1,676,526,367,000 | 92,215,900 | 12 | 6 | null | 1,513,327,539,000 | 1,495,570,640,000 | Lean | UTF-8 | Lean | false | false | 14,235 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause
open tactic expr monad super native
namespace cdcl
@[reducible] meta def prop_var := expr
@[reducible] meta def proof_term := expr
@[reducible] meta def proof_hyp := expr
meta inductive trail_elem
| dec : prop_var → bool → proof_hyp → trail_elem
| propg : prop_var → bool → proof_term → proof_hyp → trail_elem
| dbl_neg_propg : prop_var → bool → proof_term → proof_hyp → trail_elem
namespace trail_elem
meta def var : trail_elem → prop_var
| (dec v _ _) := v
| (propg v _ _ _) := v
| (dbl_neg_propg v _ _ _) := v
meta def phase : trail_elem → bool
| (dec _ ph _) := ph
| (propg _ ph _ _) := ph
| (dbl_neg_propg _ ph _ _) := ph
meta def hyp : trail_elem → proof_hyp
| (dec _ _ h) := h
| (propg _ _ _ h) := h
| (dbl_neg_propg _ _ _ h) := h
meta def is_decision : trail_elem → bool
| (dec _ _ _) := tt
| (propg _ _ _ _) := ff
| (dbl_neg_propg _ _ _ _) := ff
end trail_elem
meta structure var_state :=
(phase : bool)
(assigned : option proof_hyp)
meta structure learned_clause :=
(c : clause)
(actual_proof : proof_term)
meta inductive prop_lit
| neg : prop_var → prop_lit
| pos : prop_var → prop_lit
namespace prop_lit
meta instance prop_lit.has_lt : has_lt prop_lit :=
⟨λl₁ l₂, match l₁, l₂ with
| pos _, neg _ := true
| neg _, pos _ := false
| pos v₁, pos v₂ := v₁ < v₂
| neg v₁, neg v₂ := v₁ < v₂
end⟩
meta instance prop_lit.decidable_lt : decidable_rel ((<) : prop_lit → prop_lit → Prop) :=
λl₁ l₂, match l₁, l₂ with
| pos _, neg _ := is_true trivial
| neg _, pos _ := is_false not_false
| pos v₁, pos v₂ := expr.lt_prop.decidable_rel v₁ v₂
| neg v₁, neg v₂ := expr.lt_prop.decidable_rel v₁ v₂
end
meta def of_cls_lit : clause.literal → prop_lit
| (clause.literal.left v) := neg v
| (clause.literal.right v) := pos v
meta def of_var_and_phase (v : prop_var) : bool → prop_lit
| tt := pos v
| ff := neg v
end prop_lit
meta def watch_map := rb_map name (ℕ × ℕ × clause)
meta structure state :=
(trail : list trail_elem)
(vars : rb_map prop_var var_state)
(unassigned : rb_map prop_var prop_var)
(clauses : list clause)
(learned : list learned_clause)
(watches : rb_map prop_lit watch_map)
(conflict : option proof_term)
(unitp_queue : list prop_var)
(local_false : expr)
namespace state
meta def initial (local_false : expr) : state := {
trail := [],
vars := rb_map.mk _ _,
unassigned := rb_map.mk _ _,
clauses := [],
learned := [],
watches := rb_map.mk _ _,
conflict := none,
unitp_queue := [],
local_false := local_false
}
meta def watches_for (st : state) (pl : prop_lit) : watch_map :=
(st.watches.find pl).get_or_else (rb_map.mk _ _)
end state
meta def solver := state_t state tactic
section
local attribute [reducible] solver
meta instance : monad solver := infer_instance
meta instance : alternative solver := infer_instance
meta instance : monad_state _ solver := infer_instance
meta instance : has_monad_lift tactic solver := infer_instance
meta instance (α : Type) : has_coe (tactic α) (solver α) :=
⟨monad_lift⟩
end
meta def fail {A B} [has_to_format B] (b : B) : solver A :=
@tactic.fail A B _ b
meta def get_local_false : solver expr :=
do st ← get, return st.local_false
meta def mk_var_core (v : prop_var) (ph : bool) : solver unit := do
modify $ λst, match st.vars.find v with
| (some _) := st
| none := { st with
vars := st.vars.insert v ⟨ph, none⟩,
unassigned := st.unassigned.insert v v
}
end,
skip
meta def mk_var (v : prop_var) : solver unit := mk_var_core v ff
meta def set_conflict (proof : proof_term) : solver unit := do
modify $ λst, { st with conflict := some proof }, skip
meta def has_conflict : solver bool :=
do st ← get, return st.conflict.is_some
meta def push_trail (elem : trail_elem) : solver unit := do
st ← get,
match st.vars.find elem.var with
| none := fail $ "unknown variable: " ++ elem.var.to_string
| some ⟨_, some _⟩ := fail $ "adding already assigned variable to trail: " ++ elem.var.to_string
| some ⟨_, none⟩ :=
put { st with
vars := st.vars.insert elem.var ⟨elem.phase, some elem.hyp⟩,
unassigned := st.unassigned.erase elem.var,
trail := elem :: st.trail,
unitp_queue := elem.var :: st.unitp_queue
} >> skip
end
meta def pop_trail_core : solver (option trail_elem) := do
st ← get,
match st.trail with
| elem :: rest := do
put { st with trail := rest,
vars := st.vars.insert elem.var ⟨elem.phase, none⟩,
unassigned := st.unassigned.insert elem.var elem.var,
unitp_queue := [] },
return $ some elem
| [] := return none
end
meta def is_decision_level_zero : solver bool :=
do st ← get, return $ st.trail.for_all $ λelem, ¬elem.is_decision
meta def revert_to_decision_level_zero : unit → solver unit | () := do
is_dl0 ← is_decision_level_zero,
if is_dl0 then return ()
else do pop_trail_core, revert_to_decision_level_zero ()
meta def formula_of_lit (local_false : expr) (v : prop_var) (ph : bool) :=
if ph then v else imp v local_false
meta def lookup_var (v : prop_var) : solver (option var_state) :=
do st ← get, return $ st.vars.find v
meta def add_propagation (v : prop_var) (ph : bool) (just : proof_term) (just_is_dn : bool) : solver unit :=
do v_st ← lookup_var v, local_false ← get_local_false, match v_st with
| none := fail $ "propagating unknown variable: " ++ v.to_string
| some ⟨assg_ph, some proof⟩ :=
if ph = assg_ph then
return ()
else if assg_ph ∧ ¬just_is_dn then
set_conflict (app just proof)
else
set_conflict (app proof just)
| some ⟨_, none⟩ := do
hyp_name ← mk_fresh_name,
hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph),
if just_is_dn then do
push_trail $ trail_elem.dbl_neg_propg v ph just hyp
else do
push_trail $ trail_elem.propg v ph just hyp
end
meta def add_decision (v : prop_var) (ph : bool) : solver unit := do
hyp_name ← mk_fresh_name,
local_false ← get_local_false,
hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph),
push_trail $ trail_elem.dec v ph hyp
meta def lookup_lit (l : clause.literal) : solver (option (bool × proof_hyp)) :=
do var_st_opt ← lookup_var l.formula, match var_st_opt with
| none := return none
| some ⟨ph, none⟩ := return none
| some ⟨ph, some proof⟩ :=
return $ some (if l.is_neg then bnot ph else ph, proof)
end
meta def lit_is_false (l : clause.literal) : solver bool :=
do s ← lookup_lit l, return $ match s with
| some (ff, _) := tt
| _ := ff
end
meta def lit_is_not_false (l : clause.literal) : solver bool :=
do isf ← lit_is_false l, return $ bnot isf
meta def cls_is_false (c : clause) : solver bool :=
list.band <$> mapm lit_is_false c.get_lits
private meta def unit_propg_cls' : clause → solver (option prop_var) | c :=
if c.num_lits = 0 then return (some c.proof)
else let hd := c.get_lit 0 in
do lit_st ← lookup_lit hd, match lit_st with
| some (ff, isf_prf) := unit_propg_cls' (c.inst isf_prf)
| _ := return none
end
meta def unit_propg_cls : clause → solver unit | c :=
do has_confl ← has_conflict,
if has_confl then return () else
if c.num_lits = 0 then do set_conflict c.proof
else let hd := c.get_lit 0 in
do lit_st ← lookup_lit hd, match lit_st with
| some (ff, isf_prf) := unit_propg_cls (c.inst isf_prf)
| some (tt, _) := return ()
| none :=
do fls_prf_opt ← unit_propg_cls' (c.inst (expr.mk_var 0)),
match fls_prf_opt with
| some fls_prf := do
fls_prf' ← return $ lam `H binder_info.default c.type.binding_domain fls_prf,
if hd.is_neg then
add_propagation hd.formula ff fls_prf' ff
else
add_propagation hd.formula tt fls_prf' tt
| none := return ()
end
end
private meta def modify_watches_for (pl : prop_lit) (f : watch_map → watch_map) : solver unit := do
modify $ λst, { st with
watches := st.watches.insert pl $ f $ st.watches_for pl
}, skip
private meta def add_watch (n : name) (c : clause) (i j : ℕ) : solver unit :=
let l := c.get_lit i, pl := prop_lit.of_cls_lit l in
modify_watches_for pl $ λw, w.insert n (i,j,c)
private meta def remove_watch (n : name) (c : clause) (i : ℕ) : solver unit :=
let l := c.get_lit i, pl := prop_lit.of_cls_lit l in
modify_watches_for pl $ λw, w.erase n
private meta def set_watches (n : name) (c : clause) : solver unit :=
if c.num_lits = 0 then
set_conflict c.proof
else if c.num_lits = 1 then
unit_propg_cls c
else do
not_false_lits ← filter (λi, lit_is_not_false (c.get_lit i)) (list.range c.num_lits),
match not_false_lits with
| [] := do
add_watch n c 0 1,
add_watch n c 1 0,
unit_propg_cls c
| [i] :=
let j := if i = 0 then 1 else 0 in do
add_watch n c i j,
add_watch n c j i,
unit_propg_cls c
| (i::j::_) := do
add_watch n c i j,
add_watch n c j i
end
meta def update_watches (n : name) (c : clause) (i₁ i₂ : ℕ) : solver unit := do
remove_watch n c i₁,
remove_watch n c i₂,
set_watches n c
meta def mk_clause (c : clause) : solver unit := do
c : clause ← c.distinct,
c.get_lits.mmap' (λl, mk_var l.formula),
revert_to_decision_level_zero (),
modify $ λst, { st with clauses := c :: st.clauses },
c_name ← mk_fresh_name,
set_watches c_name c
meta def unit_propg_var (v : prop_var) : solver unit :=
do st ← get, if st.conflict.is_some then return () else
match st.vars.find v with
| some ⟨ph, none⟩ := fail $ "propagating unassigned variable: " ++ v.to_string
| none := fail $ "unknown variable: " ++ v.to_string
| some ⟨ph, some _⟩ :=
let watches := st.watches_for $ prop_lit.of_var_and_phase v (bnot ph) in
watches.to_list.mmap' $ λw, update_watches w.1 w.2.2.2 w.2.1 w.2.2.1
end
meta def analyze_conflict' (local_false : expr) : proof_term → list trail_elem → clause
| proof (trail_elem.dec v ph hyp :: es) :=
let abs_prf := abstract_local proof hyp.local_uniq_name in
if has_var abs_prf then
clause.close_const (analyze_conflict' proof es) hyp
else
analyze_conflict' proof es
| proof (trail_elem.propg v ph l_prf hyp :: es) :=
let abs_prf := abstract_local proof hyp.local_uniq_name in
if has_var abs_prf then
analyze_conflict' (app (lam hyp.local_pp_name binder_info.default (formula_of_lit local_false v ph) abs_prf) l_prf) es
else
analyze_conflict' proof es
| proof (trail_elem.dbl_neg_propg v ph l_prf hyp :: es) :=
let abs_prf := abstract_local proof hyp.local_uniq_name in
if has_var abs_prf then
analyze_conflict' (app l_prf (lambdas [hyp] proof)) es
else
analyze_conflict' proof es
| proof [] := ⟨0, 0, proof, local_false, local_false⟩
meta def analyze_conflict (proof : proof_term) : solver clause :=
do st ← get, return $ analyze_conflict' st.local_false proof st.trail
meta def add_learned (c : clause) : solver unit := do
prf_abbrev_name ← mk_fresh_name,
c' ← return { c with proof := local_const prf_abbrev_name prf_abbrev_name binder_info.default c.type },
modify $ λst, { st with learned := ⟨c', c.proof⟩ :: st.learned },
c_name ← mk_fresh_name,
set_watches c_name c'
meta def backtrack_with : clause → solver unit | conflict_clause := do
isf ← cls_is_false conflict_clause,
if ¬isf then
modify (λst, { st with conflict := none }) >> skip
else do
removed_elem ← pop_trail_core,
if removed_elem.is_some then
backtrack_with conflict_clause
else
return ()
meta def replace_learned_clauses' : proof_term → list learned_clause → proof_term
| proof [] := proof
| proof (⟨c, actual_proof⟩ :: lcs) :=
let abs_prf := abstract_local proof c.proof.local_uniq_name in
if has_var abs_prf then
replace_learned_clauses' (elet c.proof.local_pp_name c.type actual_proof abs_prf) lcs
else
replace_learned_clauses' proof lcs
meta def replace_learned_clauses (proof : proof_term) : solver proof_term :=
do st ← get, return $ replace_learned_clauses' proof st.learned
meta inductive result
| unsat : proof_term → result
| sat : rb_map prop_var bool → result
variable theory_solver : solver (option proof_term)
meta def unit_propg : unit → solver unit | () := do
st ← get,
if st.conflict.is_some then return () else
match st.unitp_queue with
| [] := return ()
| (v::vs) := do
put { st with unitp_queue := vs },
unit_propg_var v,
unit_propg ()
end
private meta def run' : unit → solver result | () := do
unit_propg (),
st ← get,
match st.conflict with
| some conflict := do
conflict_clause ← analyze_conflict conflict,
if conflict_clause.num_lits = 0 then do
proof ← replace_learned_clauses conflict_clause.proof,
return (result.unsat proof)
else do
backtrack_with conflict_clause,
add_learned conflict_clause,
run' ()
| none :=
match st.unassigned.min with
| none := do
theory_conflict ← theory_solver,
match theory_conflict with
| some conflict := do set_conflict conflict, run' ()
| none := return $ result.sat (st.vars.map (λvar_st, var_st.phase))
end
| some unassigned :=
match st.vars.find unassigned with
| some ⟨ph, none⟩ := do add_decision unassigned ph, run' ()
| _ := fail $ "unassigned variable is assigned: " ++ unassigned.to_string
end
end
end
meta def run : solver result := run' theory_solver ()
meta def solve (local_false : expr) (clauses : list clause) : tactic result := do
res ← (do clauses.mmap' mk_clause, run theory_solver).run (state.initial local_false),
return res.1
meta def theory_solver_of_tactic (th_solver : tactic unit) : cdcl.solver (option cdcl.proof_term) :=
do s ← get, ↑do
hyps ← return $ s.trail.map (λe, e.hyp),
subgoal ← mk_meta_var s.local_false,
goals ← get_goals,
set_goals [subgoal],
hvs ← hyps.mmap' (λhyp, assertv hyp.local_pp_name hyp.local_type hyp),
solved ← (do th_solver, done, return tt) <|> return ff,
set_goals goals,
if solved then do
proof ← instantiate_mvars subgoal,
proof' ← whnf proof, -- gets rid of the unnecessary asserts
return $ some proof'
else
return none
end cdcl
|
f938a3f2124d089f18913df0e0f8173d5409cd68 | 9cba98daa30c0804090f963f9024147a50292fa0 | /old/metrology/axis_orientation.lean | e524314504fe85073300435fab3b33994fc9e0b1 | [] | no_license | kevinsullivan/phys | dcb192f7b3033797541b980f0b4a7e75d84cea1a | ebc2df3779d3605ff7a9b47eeda25c2a551e011f | refs/heads/master | 1,637,490,575,500 | 1,629,899,064,000 | 1,629,899,064,000 | 168,012,884 | 0 | 3 | null | 1,629,644,436,000 | 1,548,699,832,000 | Lean | UTF-8 | Lean | false | false | 2,085 | lean | import ...math.affine.affine_euclidean_space_lib
open euclidean
open eucl_lib
open aff_lib
namespace orientation
structure AxisOrientation (dim : ℕ) :=
(or : affine_euclidean_orientation dim)
/-
In relation to a body the standard is:
x forward
y left
z up
For short-range Cartesian representations of geographic locations, use the east north up [5] (ENU) convention:
X east
Y north
Z up
To avoid precision problems with large float32 values, it is recommended to choose a nearby origin such as your system's starting position.
Suffix Frames
In the case of cameras, there is often a second frame defined with a "_optical" suffix. This uses a slightly different convention:
z forward
x right
y down
For outdoor systems where it is desirable to work under the north east down [6] (NED) convention, define an appropriately transformed secondary frame with the "_ned" suffix:
X north
Y east
Z down
-/
noncomputable
def NWU_basis : fin 3 → aff_vec_coord_tuple ℝ 3
| ⟨0,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,-1,0], rfl⟩
| ⟨1,p⟩ := affine_coord_space.mk_tuple_vec ⟨[1,0,0], rfl⟩
| ⟨2,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,0,1], rfl⟩
| ⟨_,p⟩ := affine_coord_space.mk_tuple_vec ⟨[1,1,1], rfl⟩
noncomputable
def NED_basis : fin 3 → aff_vec_coord_tuple ℝ 3
| ⟨0,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,1,0], rfl⟩
| ⟨1,p⟩ := affine_coord_space.mk_tuple_vec ⟨[1,0,0], rfl⟩
| ⟨2,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,0,-1], rfl⟩
| ⟨_, p⟩ := sorry
noncomputable
def ENU_basis : fin 3 → aff_vec_coord_tuple ℝ 3
| ⟨0,p⟩ := affine_coord_space.mk_tuple_vec ⟨[1,0,0], rfl⟩
| ⟨1,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,1,0], rfl⟩
| ⟨2,p⟩ := affine_coord_space.mk_tuple_vec ⟨[0,0,1], rfl⟩
| ⟨_, p⟩ := sorry
noncomputable
def NWU : AxisOrientation 3 :=
⟨⟨NWU_basis, sorry, sorry⟩⟩
noncomputable
def NED : AxisOrientation 3 :=
⟨⟨NED_basis, sorry, sorry⟩⟩
noncomputable
def ENU : AxisOrientation 3 :=
⟨⟨ENU_basis, sorry, sorry⟩⟩
end orientation |
ac89c71cc0d3f73764aabe33a2b90fef44584546 | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world10/level8.lean | 8abc66e27c3af4fd6e298018d156ffb4621058a9 | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/natural_number_game | 05c39e1586408cfb563d1a12e1085a90726ab655 | f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd | refs/heads/master | 1,688,570,964,990 | 1,636,908,242,000 | 1,636,908,242,000 | 195,403,790 | 277 | 84 | Apache-2.0 | 1,694,547,955,000 | 1,562,328,792,000 | Lean | UTF-8 | Lean | false | false | 440 | lean | import game.world10.level7 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 8: `succ_le_succ`
Another straightforward one.
-/
/- Lemma
For all naturals $a$ and $b$, if $a\le b$, then $\operatorname{succ}(a)\le\operatorname{succ}(b)$.
-/
lemma succ_le_succ (a b : mynat) (h : a ≤ b) : succ a ≤ succ b :=
begin [nat_num_game]
cases h with c hc,
use c,
rw hc,
rw succ_add,
refl,
end
end mynat -- hide
|
617ff26f950a2b4b97c9881d1b511ffab4c2f1b1 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/group_theory/subgroup.lean | 43c7d142a2954d85bb399f7721167e859306a915 | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,930 | lean | /-
Copyright (c) 2020 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import group_theory.submonoid
import algebra.group.conj
/-!
# Subgroups
This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled
form (unbundled subgroups are in `deprecated/subgroups.lean`).
We prove subgroups of a group form a complete lattice, and results about images and preimages of
subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms.
There are also theorems about the subgroups generated by an element or a subset of a group,
defined both inductively and as the infimum of the set of subgroups containing a given
element/subset.
Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration.
## Main definitions
Notation used here:
- `G N` are `group`s
- `A` is an `add_group`
- `H K` are `subgroup`s of `G` or `add_subgroup`s of `A`
- `x` is an element of type `G` or type `A`
- `f g : N →* G` are group homomorphisms
- `s k` are sets of elements of type `G`
Definitions in the file:
* `subgroup G` : the type of subgroups of a group `G`
* `add_subgroup A` : the type of subgroups of an additive group `A`
* `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice
* `subgroup.closure k` : the minimal subgroup that includes the set `k`
* `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G`
* `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set
* `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a
subgroup
* `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a
subgroup
* `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K`
is a subgroup of `G × N`
* `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup
* `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G`
such that `f x = 1`
* `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that
`f x = g x` form a subgroup of `G`
## Implementation notes
Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as
membership of a subgroup's underlying set.
## Tags
subgroup, subgroups
-/
open_locale big_operators
variables {G : Type*} [group G]
variables {A : Type*} [add_group A]
set_option old_structure_cmd true
/-- A subgroup of a group `G` is a subset containing 1, closed under multiplication
and closed under multiplicative inverse. -/
structure subgroup (G : Type*) [group G] extends submonoid G :=
(inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier)
/-- An additive subgroup of an additive group `G` is a subset containing 0, closed
under addition and additive inverse. -/
structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:=
(neg_mem' {x} : x ∈ carrier → -x ∈ carrier)
attribute [to_additive] subgroup
attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid
/-- Reinterpret a `subgroup` as a `submonoid`. -/
add_decl_doc subgroup.to_submonoid
/-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/
add_decl_doc add_subgroup.to_add_submonoid
/-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/
def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) :
add_subgroup (additive G) :=
{ neg_mem' := H.inv_mem',
.. submonoid.to_add_submonoid H.to_submonoid}
/-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/
def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) :
subgroup G :=
{ inv_mem' := H.neg_mem',
.. submonoid.of_add_submonoid H.to_add_submonoid}
/-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/
def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) :
subgroup (multiplicative G) :=
{ inv_mem' := H.neg_mem',
.. add_submonoid.to_submonoid H.to_add_submonoid}
/-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/
def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) :
add_subgroup G :=
{ neg_mem' := H.inv_mem',
.. add_submonoid.of_submonoid H.to_submonoid }
/-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/
def subgroup.add_subgroup_equiv (G : Type*) [group G] :
subgroup G ≃ add_subgroup (additive G) :=
{ to_fun := subgroup.to_add_subgroup,
inv_fun := subgroup.of_add_subgroup,
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl }
namespace subgroup
@[to_additive]
instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier }
@[simp, to_additive]
lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl
@[to_additive]
instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩
@[to_additive]
instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩
@[simp, norm_cast, to_additive]
lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl
@[simp, norm_cast, to_additive]
lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl
-- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute
attribute [norm_cast] add_subgroup.mem_coe
attribute [norm_cast] add_subgroup.coe_coe
end subgroup
@[to_additive]
protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} :
(∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ :=
set_coe.exists
@[to_additive]
protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} :
(∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ :=
set_coe.forall
namespace subgroup
variables (H K : subgroup G)
/-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
@[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one.
Useful to fix definitional equalities"]
protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G :=
{ carrier := s,
one_mem' := hs.symm ▸ K.one_mem',
mul_mem' := hs.symm ▸ K.mul_mem',
inv_mem' := hs.symm ▸ K.inv_mem' }
/- Two subgroups are equal if the underlying set are the same. -/
@[to_additive "Two `add_group`s are equal if the underlying subsets are equal."]
theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K :=
by { cases H, cases K, congr, exact h }
/- Two subgroups are equal if and only if the underlying subsets are equal. -/
@[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."]
protected theorem ext'_iff {H K : subgroup G} :
H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩
/-- Two subgroups are equal if they have the same elements. -/
@[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."]
theorem ext {H K : subgroup G}
(h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h
attribute [ext] add_subgroup.ext
/-- A subgroup contains the group's 1. -/
@[to_additive "An `add_subgroup` contains the group's 0."]
theorem one_mem : (1 : G) ∈ H := H.one_mem'
/-- A subgroup is closed under multiplication. -/
@[to_additive "An `add_subgroup` is closed under addition."]
theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy
/-- A subgroup is closed under inverse. -/
@[to_additive "An `add_subgroup` is closed under inverse."]
theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx
@[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H :=
⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩
@[to_additive]
lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H :=
⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩
@[to_additive]
lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H :=
⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩
/-- Product of a list of elements in a subgroup is in the subgroup. -/
@[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."]
lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K :=
K.to_submonoid.list_prod_mem
/-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/
@[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group`
is in the `add_subgroup`."]
lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) :
(∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g
/-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the
subgroup. -/
@[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset`
is in the `add_subgroup`."]
lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G)
{ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) :
∏ c in t, f c ∈ K :=
K.to_submonoid.prod_mem h
lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx
lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K
| (int.of_nat n) := pow_mem _ hx n
| -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ
/-- Construct a subgroup from a nonempty set that is closed under division. -/
@[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"]
def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G :=
have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx,
have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx,
{ carrier := s,
one_mem' := one_mem,
inv_mem' := inv_mem,
mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) }
/-- A subgroup of a group inherits a multiplication. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits an addition."]
instance has_mul : has_mul H := H.to_submonoid.has_mul
/-- A subgroup of a group inherits a 1. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits a zero."]
instance has_one : has_one H := H.to_submonoid.has_one
/-- A subgroup of a group inherits an inverse. -/
@[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."]
instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩
@[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl
@[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl
attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero
add_subgroup.coe_neg add_subgroup.coe_mk
/-- A subgroup of a group inherits a group structure. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."]
instance to_group {G : Type*} [group G] (H : subgroup G) : group H :=
{ inv := has_inv.inv,
mul_left_inv := λ x, subtype.eq $ mul_left_inv x,
.. H.to_submonoid.to_monoid }
/-- A subgroup of a `comm_group` is a `comm_group`. -/
@[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."]
instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group}
/-- The natural group hom from a subgroup of group `G` to `G`. -/
@[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."]
def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl
@[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_pow _ _ _
@[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_gpow _ _ _
@[to_additive]
instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩
@[to_additive]
lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl
@[simp, to_additive]
lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl
@[to_additive]
instance : partial_order (subgroup G) :=
{ le := (≤),
.. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') }
/-- The subgroup `G` of the group `G`. -/
@[to_additive "The `add_subgroup G` of the `add_group G`."]
instance : has_top (subgroup G) :=
⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩
/-- The trivial subgroup `{1}` of an group `G`. -/
@[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."]
instance : has_bot (subgroup G) :=
⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩
@[to_additive]
instance : inhabited (subgroup G) := ⟨⊥⟩
@[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl
@[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl
@[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) :=
begin
split,
{ intros h x x_in,
rwa [h, mem_bot] at x_in },
{ intros h,
ext x,
rw mem_bot,
exact ⟨h x, by { rintros rfl, exact H.one_mem }⟩ },
end
@[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) :=
begin
split,
{ introI h,
rcases exists_ne (1 : H) with ⟨⟨h, h_in⟩, h_ne⟩,
use [h, h_in],
intro hyp,
apply h_ne,
simpa [hyp] },
{ rintros ⟨x, x_in, hx⟩,
apply nontrivial_of_ne (⟨x, x_in⟩ : H) 1,
intro hyp,
apply hx,
simpa [has_one.one] using hyp },
end
/-- A subgroup is either the trivial subgroup or nontrivial. -/
@[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H :=
begin
classical,
by_cases h : ∀ x ∈ H, x = (1 : G),
{ left,
exact H.eq_bot_iff_forall.mpr h },
{ right,
push_neg at h,
simpa [nontrivial_iff_exists_ne_one] using h },
end
/-- A subgroup is either the trivial subgroup or contains a nonzero element. -/
@[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) :=
begin
convert H.bot_or_nontrivial,
rw nontrivial_iff_exists_ne_one
end
/-- The inf of two subgroups is their intersection. -/
@[to_additive "The inf of two `add_subgroups`s is their intersection."]
instance : has_inf (subgroup G) :=
⟨λ H₁ H₂,
{ inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩,
.. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩
@[simp, to_additive]
lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[to_additive]
instance : has_Inf (subgroup G) :=
⟨λ s,
{ inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h),
.. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩
@[simp, to_additive]
lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl
attribute [norm_cast] coe_Inf add_subgroup.coe_Inf
@[simp, to_additive]
lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[to_additive]
lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp, to_additive]
lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
attribute [norm_cast] coe_infi add_subgroup.coe_infi
/-- Subgroups of a group form a complete lattice. -/
@[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."]
instance : complete_lattice (subgroup G) :=
{ bot := (⊥),
bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
.. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image
(λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi }
@[to_additive]
lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
@[to_additive]
lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
@[to_additive]
lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) :
∀ {x : G}, x ∈ S i → x ∈ supr S :=
show S i ≤ supr S, from le_supr _ _
@[to_additive]
lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G}
(hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
/-- The `subgroup` generated by a set. -/
@[to_additive "The `add_subgroup` generated by a set"]
def closure (k : set G) : subgroup G := Inf {K | k ⊆ K}
variable {k : set G}
@[to_additive]
lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K :=
mem_Inf
/-- The subgroup generated by a set includes the set. -/
@[simp, to_additive "The `add_subgroup` generated by a set includes the set."]
lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx
open set
/-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/
@[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"]
lemma closure_le : closure k ≤ K ↔ k ⊆ K :=
⟨subset.trans subset_closure, λ h, Inf_le h⟩
@[to_additive]
lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K :=
le_antisymm ((closure_le $ K).2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and
is preserved under multiplication and inverse, then `p` holds for all elements of the closure
of `k`. -/
@[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all
elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements
of the additive closure of `k`."]
lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k)
(Hk : ∀ x ∈ k, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹) : p x :=
(@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h
attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction
/-- An induction principle on elements of the subtype `subgroup.closure`.
If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse,
then `p` holds for all elements `x : closure k`.
The difference with `subgroup.closure_induction` is that this acts on the subtype.
-/
@[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`.
If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation,
then `p` holds for all elements `x : closure k`.
The difference with `add_subgroup.closure_induction` is that this acts on the subtype."]
lemma closure_induction' (k : set G) {p : closure k → Prop}
(Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩)
(H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹)
(x : closure k) :
p x :=
subtype.rec_on x $ λ x hx, begin
refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc),
exact closure_induction hx
(λ x hx, ⟨subset_closure hx, Hk x hx⟩)
⟨one_mem _, H1⟩
(λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy,
⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩)
(λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩),
end
attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction'
variable (G)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure G _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, @closure_le _ _ t s,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {G}
/-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`. -/
@[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`"]
lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k :=
(subgroup.gi G).gc.monotone_l h'
/-- Closure of a subgroup `K` equals `K`. -/
@[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"]
lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K
@[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ :=
(subgroup.gi G).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ :=
@coe_top G _ ▸ closure_eq ⊤
@[to_additive]
lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t :=
(subgroup.gi G).gc.l_sup
@[to_additive]
lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subgroup.gi G).gc.l_supr
@[to_additive]
lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) :
closure S = ⊥ ↔ S ⊆ {1} :=
by { rw [← le_bot_iff], exact closure_le _}
/-- The subgroup generated by an element of a group equals the set of integer number powers of
the element. -/
lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, gpow_one x⟩ },
{ exact ⟨0, rfl⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, gpow_add x n m⟩ },
rintros _ ⟨n, rfl⟩,
exact ⟨-n, gpow_neg x n⟩
end
lemma closure_singleton_one : closure ({1} : set G) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
@[to_additive]
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K)
{x : G} :
x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩,
suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i,
by simpa only [closure_Union, closure_eq (K _)] using this,
refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _),
{ exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hK i j with ⟨k, hki, hkj⟩,
exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ },
rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩
end
@[to_additive]
lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) :
((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
@[to_additive]
lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty)
(hK : directed_on (≤) K) {x : G} :
x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s :=
begin
haveI : nonempty K := Kne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk]
end
variables {N : Type*} [group N] {P : Type*} [group P]
/-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def comap {N : Type*} [group N] (f : G →* N)
(H : subgroup N) : subgroup G :=
{ carrier := (f ⁻¹' H),
inv_mem' := λ a ha,
show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha,
.. H.to_submonoid.comap f }
@[simp, to_additive]
lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl
@[simp, to_additive]
lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl
@[to_additive]
lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) :
(K.comap g).comap f = K.comap (g.comp f) :=
rfl
/-- The image of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def map (f : G →* N) (H : subgroup G) : subgroup N :=
{ carrier := (f '' H),
inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ },
.. H.to_submonoid.map f }
@[simp, to_additive]
lemma coe_map (f : G →* N) (K : subgroup G) :
(K.map f : set N) = f '' K := rfl
@[simp, to_additive]
lemma mem_map {f : G →* N} {K : subgroup G} {y : N} :
y ∈ K.map f ↔ ∃ x ∈ K, f x = y :=
mem_image_iff_bex
@[to_additive]
lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) :=
ext' $ image_image _ _ _
@[to_additive]
lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} :
K.map f ≤ H ↔ K ≤ H.comap f :=
image_subset_iff
@[to_additive]
lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) :=
λ _ _, map_le_iff_le_comap
@[to_additive]
lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f :=
(gc_map_comap f).l_sup
@[to_additive]
lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
@[to_additive]
lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f :=
(gc_map_comap f).u_inf
@[to_additive]
lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/
@[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K`
as an `add_subgroup` of `A × B`."]
def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) :=
{ inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩,
.. submonoid.prod H.to_submonoid K.to_submonoid}
@[to_additive coe_prod]
lemma coe_prod (H : subgroup G) (K : subgroup N) :
(H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl
@[to_additive mem_prod]
lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} :
p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl
@[to_additive prod_mono]
lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) :=
λ s s' hs t t' ht, set.prod_mono hs ht
@[to_additive prod_mono_right]
lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) :=
prod_mono (le_refl K)
@[to_additive prod_mono_left]
lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) :=
λ s₁ s₂ hs, prod_mono hs (le_refl H)
@[to_additive prod_top]
lemma prod_top (K : subgroup G) :
K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
@[to_additive top_prod]
lemma top_prod (H : subgroup N) :
(⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp, to_additive top_prod_top]
lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ :=
(top_prod _).trans $ comap_top _
@[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ :=
ext' $ by simp [coe_prod, prod.one_eq_mk]
/-- Product of subgroups is isomorphic to their product as groups. -/
@[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product
as additive groups"]
def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K :=
{ map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K }
/-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/
structure normal : Prop :=
(conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H)
attribute [class] normal
end subgroup
namespace add_subgroup
/-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/
structure normal (H : add_subgroup A) : Prop :=
(conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n - g ∈ H)
attribute [to_additive add_subgroup.normal] subgroup.normal
attribute [class] normal
end add_subgroup
namespace subgroup
variables {H K : subgroup G}
@[priority 100, to_additive]
instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal :=
⟨by simp [mul_comm, mul_left_comm]⟩
namespace normal
variable (nH : H.normal)
@[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H :=
have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa
@[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H :=
⟨nH.mem_comm, nH.mem_comm⟩
end normal
@[priority 100, to_additive]
instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩
@[priority 100, to_additive]
instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩
variable (G)
/-- The center of a group `G` is the set of elements that commute with everything in `G` -/
@[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"]
def center : subgroup G :=
{ carrier := {z | ∀ g, g * z = z * g},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g,
by assoc_rw [ha, hb g],
inv_mem' := λ a (ha : ∀ g, g * a = a * g) g,
by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] }
variable {G}
@[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl
@[priority 100, to_additive]
instance center_normal : (center G).normal :=
⟨begin
assume n hn g h,
assoc_rw [hn (h * g), hn g],
simp
end⟩
variables {G} (H)
/-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/
@[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."]
def normalizer : subgroup G :=
{ carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n,
by { rw [hb, ha], simp [mul_assoc] },
inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n,
by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } }
-- variant for sets.
-- TODO should this replace `normalizer`?
/-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/
@[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."]
def set_normalizer (S : set G) : subgroup G :=
{ carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n,
by { rw [hb, ha], simp [mul_assoc] },
inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n,
by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } }
variable {H}
@[to_additive] lemma mem_normalizer_iff {g : G} :
g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl
@[to_additive] lemma le_normalizer : H ≤ normalizer H :=
λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH]
@[priority 100, to_additive]
instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal :=
⟨λ x xH g, by simpa using (g.2 x).1 xH⟩
open_locale classical
@[to_additive]
lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer :=
λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩,
λ yH, by simpa [mem_comap, mul_assoc] using
hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩
end subgroup
namespace group
variables {s : set G}
/-- Given an element `a`, `conjugates a` is the set of conjugates. -/
def conjugates (a : G) : set G := {b | is_conj a b}
lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _
/-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of
the elements of `s`. -/
def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a
lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x :=
set.mem_bUnion_iff
theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s :=
λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩
theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) :
conjugates_of_set s ⊆ conjugates_of_set t :=
set.bUnion_subset_bUnion_left h
lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) :
conjugates a ⊆ N :=
by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c }
theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) :
conjugates_of_set s ⊆ N :=
set.bUnion_subset (λ x H, conjugates_subset_normal (h H))
/-- The set of conjugates of `s` is closed under conjugation. -/
lemma conj_mem_conjugates_of_set {x c : G} :
x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) :=
λ H,
begin
rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩,
exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩,
end
end group
namespace subgroup
open group
variable {s : set G}
/-- The normal closure of a set `s` is the subgroup closure of all the conjugates of
elements of `s`. It is the smallest normal subgroup containing `s`. -/
def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s)
theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s :=
subset_closure
theorem subset_normal_closure : s ⊆ normal_closure s :=
set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure
/-- The normal closure of `s` is a normal subgroup. -/
instance normal_closure_normal : (normal_closure s).normal :=
⟨λ n h g,
begin
refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) },
{ simpa using (normal_closure s).one_mem },
{ rw ← conj_mul,
exact mul_mem _ ihx ihy },
{ rw ← conj_inv,
exact inv_mem _ ihx }
end⟩
/-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/
theorem normal_closure_le_normal {N : subgroup G} [N.normal]
(h : s ⊆ N) : normal_closure s ≤ N :=
begin
assume a w,
refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset h hx) },
{ exact subgroup.one_mem _ },
{ exact subgroup.mul_mem _ ihx ihy },
{ exact subgroup.inv_mem _ ihx }
end
lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N :=
⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩
theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t :=
normal_closure_le_normal (set.subset.trans h subset_normal_closure)
theorem normal_closure_eq_infi : normal_closure s =
⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N :=
le_antisymm
(le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal))))
(infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance)
(infi_le_of_le subset_normal_closure (le_refl _))))
end subgroup
namespace add_subgroup
open set
lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) :
∀ n : ℤ, gsmul n x ∈ H
| (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n
| -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n
lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H :=
H.add_mem hx (H.neg_mem hy)
/-- The `add_subgroup` generated by an element of an `add_group` equals the set of
natural number multiples of the element. -/
lemma mem_closure_singleton {x y : A} :
y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, one_gsmul x⟩ },
{ exact ⟨0, rfl⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, add_gsmul x n m⟩ },
{ rintros _ ⟨n, rfl⟩,
refine ⟨-n, neg_gsmul x n⟩ }
end
lemma closure_singleton_zero : closure ({0} : set A) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
variable (H : add_subgroup A)
@[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x :=
coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _
@[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x :=
coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _
attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow
attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow
end add_subgroup
namespace monoid_hom
variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G)
open subgroup
/-- The range of a monoid homomorphism from a group is a subgroup. -/
@[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."]
def range (f : G →* N) : subgroup N :=
subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff])
@[simp, to_additive] lemma coe_range (f : G →* N) :
(f.range : set N) = set.range f := rfl
@[simp, to_additive] lemma mem_range {f : G →* N} {y : N} :
y ∈ f.range ↔ ∃ x, f x = y :=
iff.rfl
@[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f :=
by ext; simp
/-- The canonical surjective group homomorphism `G →* f(G)` induced by a group
homomorphism `G →* N`. -/
@[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group
homomorphism `G →+ N`."]
def to_range (f : G →* N) : G →* f.range :=
monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _}
@[to_additive]
lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range :=
by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f
@[to_additive]
lemma range_top_iff_surjective {N} [group N] {f : G →* N} :
f.range = (⊤ : subgroup N) ↔ function.surjective f :=
subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective monoid homomorphism is the whole of the codomain. -/
@[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."]
lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) :
f.range = (⊤ : subgroup N) :=
range_top_iff_surjective.2 hf
/-- Restriction of a group hom to a subgroup of the codomain. -/
@[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."]
def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S :=
{ to_fun := λ n, ⟨f n, h n⟩,
map_one' := subtype.eq f.map_one,
map_mul' := λ x y, subtype.eq (f.map_mul x y) }
/-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that
`f x = 1` -/
@[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements
such that `f x = 0`"]
def ker (f : G →* N) := (⊥ : subgroup N).comap f
@[to_additive]
lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl
@[to_additive]
lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl
@[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f :=
begin
ext,
change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1,
simp only [],
end
/-- The subgroup of elements `x : G` such that `f x = g x` -/
@[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"]
def eq_locus (f g : G →* N) : subgroup G :=
{ inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx],
.. eq_mlocus f g}
/-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/
@[to_additive]
lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from (closure_le _).2 h
@[to_additive]
lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) :
f = g :=
ext $ λ x, h trivial
@[to_additive]
lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_top $ hs ▸ eq_on_closure h
@[to_additive]
lemma gclosure_preimage_le (f : G →* N) (s : set N) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
(closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx
/-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup
generated by the image of the set. -/
@[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals
the `add_subgroup` generated by the image of the set."]
lemma map_closure (f : G →* N) (s : set G) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s)
(gclosure_preimage_le _ _))
((closure_le _).2 $ set.image_subset _ subset_closure)
end monoid_hom
namespace monoid_hom
variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃]
variables (f : G₁ →* G₂)
/-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ`
* such that `φ.comp f = g` (`lift_of_surjective_comp`),
* where `f : G₁ →+* G₂` is surjective (`hf`),
* and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`.
See `lift_of_surjective_eq` for the uniqueness lemma.
```
G₁.
| \
f | \ g
| \
v \⌟
G₂----> G₃
∃!φ
```
-/
@[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ`
* such that `φ.comp f = g` (`lift_of_surjective_comp`),
* where `f : G₁ →+* G₂` is surjective (`hf`),
* and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`.
See `lift_of_surjective_eq` for the uniqueness lemma.
```
G₁.
| \\
f | \\ g
| \\
v \\⌟
G₂----> G₃
∃!φ
```"]
noncomputable def lift_of_surjective
(hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) :
G₂ →* G₃ :=
{ to_fun := λ b, g (classical.some (hf b)),
map_one' := hg (classical.some_spec (hf 1)),
map_mul' :=
begin
intros x y,
rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul],
simp only [classical.some_spec (hf _)],
end }
@[simp, to_additive]
lemma lift_of_surjective_comp_apply
(hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) :
(f.lift_of_surjective hf g hg) (f x) = g x :=
begin
dsimp [lift_of_surjective],
rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one],
simp only [classical.some_spec (hf _)],
end
@[simp, to_additive]
lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) :
(f.lift_of_surjective hf g hg).comp f = g :=
by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] }
@[to_additive]
lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker)
(h : G₂ →* G₃) (hh : h.comp f = g) :
h = (f.lift_of_surjective hf g hg) :=
begin
ext b, rcases hf b with ⟨a, rfl⟩,
simp only [← comp_apply, hh, f.lift_of_surjective_comp],
end
end monoid_hom
variables {N : Type*} [group N]
-- Here `H.normal` is an explicit argument so we can use dot notation with `comap`.
@[to_additive]
lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) :
(H.comap f).normal :=
⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩
@[priority 100, to_additive]
instance subgroup.normal_comap {H : subgroup N}
[nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _
@[priority 100, to_additive]
instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal :=
by rw [monoid_hom.ker]; apply_instance
namespace subgroup
/-- The subgroup generated by an element. -/
def gpowers (g : G) : subgroup G :=
subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl
@[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩
lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} :=
by { ext, exact mem_closure_singleton.symm }
@[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl
lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K :=
λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end
end subgroup
namespace add_subgroup
/-- The subgroup generated by an element. -/
def gmultiples (a : A) : add_subgroup A :=
add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl
@[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩
lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} :=
by { ext, exact mem_closure_singleton.symm }
@[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl
lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B :=
@subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h
attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers
attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers
attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure
attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom
attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset
end add_subgroup
namespace mul_equiv
variables {H K : subgroup G}
/-- Makes the identity isomorphism from a proof two subgroups of a multiplicative
group are equal. -/
@[to_additive "Makes the identity additive isomorphism from a proof
two subgroups of an additive group are equal."]
def subgroup_congr (h : H = K) : H ≃* K :=
{ map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h }
end mul_equiv
-- TODO : ↥(⊤ : subgroup H) ≃* H ?
|
3db27c798e01e95dc8a32f2de3136545c2e048b5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Util/HasConstCache.lean | 744079153b013d017ee41123b91a9142d98415cf | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,501 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
structure HasConstCache (declName : Name) where
cache : HashMapImp Expr Bool := mkHashMapImp
unsafe def HasConstCache.containsUnsafe (e : Expr) : StateM (HasConstCache declName) Bool := do
if let some r := (← get).cache.find? (beq := ⟨ptrEq⟩) e then
return r
else
match e with
| .const n .. => return n == declName
| .app f a => cache e (← containsUnsafe f <||> containsUnsafe a)
| .lam _ d b _ => cache e (← containsUnsafe d <||> containsUnsafe b)
| .forallE _ d b _ => cache e (← containsUnsafe d <||> containsUnsafe b)
| .letE _ t v b _ => cache e (← containsUnsafe t <||> containsUnsafe v <||> containsUnsafe b)
| .mdata _ b => cache e (← containsUnsafe b)
| .proj _ _ b => cache e (← containsUnsafe b)
| _ => return false
where
cache (e : Expr) (r : Bool) : StateM (HasConstCache declName) Bool := do
modify fun ⟨cache⟩ => ⟨cache.insert (beq := ⟨ptrEq⟩) e r |>.1⟩
return r
/--
Return true iff `e` contains the constant `declName`.
Remark: the results for visited expressions are stored in the state cache. -/
@[implemented_by HasConstCache.containsUnsafe]
opaque HasConstCache.contains (e : Expr) : StateM (HasConstCache declName) Bool
end Lean
|
41508a1695b9bc66dd29fd456bb587c02a71fa25 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/equiv.lean | f7a5ac8d4e7e2ca8904bebb3b8f0b10f9d2b7ff0 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 16,758 | 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
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import data.sum data.nat
open function
structure equiv [class] (A B : Type) :=
(to_fun : A → B)
(inv_fun : B → A)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
attribute [reducible]
definition perm (A : Type) := equiv A A
infix ` ≃ `:50 := equiv
definition fn {A B : Type} (e : equiv A B) : A → B :=
@equiv.to_fun A B e
infixr ` ∙ `:100 := fn
definition inv {A B : Type} [e : equiv A B] : B → A :=
@equiv.inv_fun A B e
lemma eq_of_to_fun_eq {A B : Type} : ∀ {e₁ e₂ : equiv A B}, fn e₁ = fn e₂ → e₁ = e₂
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) h :=
have f₁ = f₂, from h,
have g₁ = g₂, from funext (λ x,
have f₁ (g₁ x) = f₂ (g₂ x), from eq.trans (r₁ x) (eq.symm (r₂ x)),
have f₁ (g₁ x) = f₁ (g₂ x), begin subst f₂, exact this end,
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this),
by congruence; repeat assumption
attribute [refl]
protected definition refl (A : Type) : A ≃ A :=
mk (@id A) (@id A) (λ x, rfl) (λ x, rfl)
attribute [symm]
protected definition symm {A B : Type} : A ≃ B → B ≃ A
| (mk f g h₁ h₂) := mk g f h₂ h₁
attribute [trans]
protected definition trans {A B C : Type} : A ≃ B → B ≃ C → A ≃ C
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk (f₂ ∘ f₁) (g₁ ∘ g₂)
(show ∀ x, g₁ (g₂ (f₂ (f₁ x))) = x, by intros; rewrite [l₂, l₁]; reflexivity)
(show ∀ x, f₂ (f₁ (g₁ (g₂ x))) = x, by intros; rewrite [r₁, r₂]; reflexivity)
abbreviation id {A : Type} := equiv.refl A
namespace ops
postfix ⁻¹ := equiv.symm
postfix ⁻¹ := equiv.inv
notation e₁ ∘ e₂ := equiv.trans e₂ e₁
end ops
open equiv.ops
lemma id_apply {A : Type} (x : A) : id ∙ x = x :=
rfl
lemma comp_apply {A B C : Type} (g : B ≃ C) (f : A ≃ B) (x : A) : (g ∘ f) ∙ x = g ∙ f ∙ x :=
begin cases g, cases f, esimp end
lemma inverse_apply_apply {A B : Type} : ∀ (e : A ≃ B) (x : A), e⁻¹ ∙ e ∙ x = x
| (mk f₁ g₁ l₁ r₁) x := begin unfold [equiv.symm, fn], rewrite l₁ end
lemma eq_iff_eq_of_injective {A B : Type} {f : A → B} (inj : injective f) (a b : A) : f a = f b ↔ a = b :=
iff.intro
(suppose f a = f b, inj this)
(suppose a = b, by rewrite this)
lemma apply_eq_iff_eq {A B : Type} : ∀ (f : A ≃ B) (x y : A), f ∙ x = f ∙ y ↔ x = y
| (mk f₁ g₁ l₁ r₁) x y := eq_iff_eq_of_injective (injective_of_left_inverse l₁) x y
lemma apply_eq_iff_eq_inverse_apply {A B : Type} : ∀ (f : A ≃ B) (x : A) (y : B), f ∙ x = y ↔ x = f⁻¹ ∙ y
| (mk f₁ g₁ l₁ r₁) x y :=
begin
esimp, unfold [equiv.symm, fn], apply iff.intro,
suppose f₁ x = y, by subst y; rewrite l₁,
suppose x = g₁ y, by subst x; rewrite r₁
end
definition false_equiv_empty : empty ≃ false :=
mk (λ e, empty.rec _ e) (λ h, false.rec _ h) (λ e, empty.rec _ e) (λ h, false.rec _ h)
attribute [congr]
definition arrow_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ → B₁) ≃ (A₂ → B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ (h : A₁ → B₁) (a : A₂), f₂ (h (g₁ a)))
(λ (h : A₂ → B₂) (a : A₁), g₂ (h (f₁ a)))
(λ h, funext (λ a, by rewrite [l₁, l₂]; reflexivity))
(λ h, funext (λ a, by rewrite [r₁, r₂]; reflexivity))
section
open unit
attribute [simp]
definition arrow_unit_equiv_unit (A : Type) : (A → unit) ≃ unit :=
mk (λ f, star) (λ u, (λ f, star))
(λ f, funext (λ x, by cases (f x); reflexivity))
(λ u, by cases u; reflexivity)
attribute [simp]
definition unit_arrow_equiv (A : Type) : (unit → A) ≃ A :=
mk (λ f, f star) (λ a, (λ u, a))
(λ f, funext (λ x, by cases x; reflexivity))
(λ u, rfl)
attribute [simp]
definition empty_arrow_equiv_unit (A : Type) : (empty → A) ≃ unit :=
mk (λ f, star) (λ u, λ e, empty.rec _ e)
(λ f, funext (λ x, empty.rec _ x))
(λ u, by cases u; reflexivity)
attribute [simp]
definition false_arrow_equiv_unit (A : Type) : (false → A) ≃ unit :=
calc (false → A) ≃ (empty → A) : arrow_congr false_equiv_empty !equiv.refl
... ≃ unit : empty_arrow_equiv_unit
end
attribute [congr]
definition prod_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ × B₁) ≃ (A₂ × B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ p, match p with (a₁, b₁) := (f₁ a₁, f₂ b₁) end)
(λ p, match p with (a₂, b₂) := (g₁ a₂, g₂ b₂) end)
(λ p, begin cases p, esimp, rewrite [l₁, l₂], reflexivity end)
(λ p, begin cases p, esimp, rewrite [r₁, r₂], reflexivity end)
attribute [simp]
definition prod_comm (A B : Type) : (A × B) ≃ (B × A) :=
mk (λ p, match p with (a, b) := (b, a) end)
(λ p, match p with (b, a) := (a, b) end)
(λ p, begin cases p, esimp end)
(λ p, begin cases p, esimp end)
attribute [simp]
definition prod_assoc (A B C : Type) : ((A × B) × C) ≃ (A × (B × C)) :=
mk (λ t, match t with ((a, b), c) := (a, (b, c)) end)
(λ t, match t with (a, (b, c)) := ((a, b), c) end)
(λ t, begin cases t with ab c, cases ab, esimp end)
(λ t, begin cases t with a bc, cases bc, esimp end)
section
open unit prod.ops
attribute [simp]
definition prod_unit_right (A : Type) : (A × unit) ≃ A :=
mk (λ p, p.1)
(λ a, (a, star))
(λ p, begin cases p with a u, cases u, esimp end)
(λ a, rfl)
attribute [simp]
definition prod_unit_left (A : Type) : (unit × A) ≃ A :=
calc (unit × A) ≃ (A × unit) : prod_comm
... ≃ A : prod_unit_right
attribute [simp]
definition prod_empty_right (A : Type) : (A × empty) ≃ empty :=
mk (λ p, empty.rec _ p.2) (λ e, empty.rec _ e) (λ p, empty.rec _ p.2) (λ e, empty.rec _ e)
attribute [simp]
definition prod_empty_left (A : Type) : (empty × A) ≃ empty :=
calc (empty × A) ≃ (A × empty) : prod_comm
... ≃ empty : prod_empty_right
end
section
open sum
attribute [congr]
definition sum_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ + B₁) ≃ (A₂ + B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end)
(λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end)
(λ s, begin cases s, {esimp, rewrite l₁, reflexivity}, {esimp, rewrite l₂, reflexivity} end)
(λ s, begin cases s, {esimp, rewrite r₁, reflexivity}, {esimp, rewrite r₂, reflexivity} end)
open bool unit
definition bool_equiv_unit_sum_unit : bool ≃ (unit + unit) :=
mk (λ b, match b with tt := inl star | ff := inr star end)
(λ s, match s with inl star := tt | inr star := ff end)
(λ b, begin cases b, esimp, esimp end)
(λ s, begin cases s with u u, {cases u, esimp}, {cases u, esimp} end)
attribute [simp]
definition sum_comm (A B : Type) : (A + B) ≃ (B + A) :=
mk (λ s, match s with inl a := inr a | inr b := inl b end)
(λ s, match s with inl b := inr b | inr a := inl a end)
(λ s, begin cases s, esimp, esimp end)
(λ s, begin cases s, esimp, esimp end)
attribute [simp]
definition sum_assoc (A B C : Type) : ((A + B) + C) ≃ (A + (B + C)) :=
mk (λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end)
(λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end)
(λ s, begin cases s with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with a bc, esimp, cases bc, repeat esimp end)
attribute [simp]
definition sum_empty_right (A : Type) : (A + empty) ≃ A :=
mk (λ s, match s with inl a := a | inr e := empty.rec _ e end)
(λ a, inl a)
(λ s, begin cases s with a e, esimp, exact empty.rec _ e end)
(λ a, rfl)
attribute [simp]
definition sum_empty_left (A : Type) : (empty + A) ≃ A :=
calc (empty + A) ≃ (A + empty) : sum_comm
... ≃ A : sum_empty_right
end
section
open prod.ops
definition arrow_prod_equiv_prod_arrow (A B C : Type) : (C → A × B) ≃ ((C → A) × (C → B)) :=
mk (λ f, (λ c, (f c).1, λ c, (f c).2))
(λ p, λ c, (p.1 c, p.2 c))
(λ f, funext (λ c, begin esimp, cases f c, esimp end))
(λ p, begin cases p, esimp end)
definition arrow_arrow_equiv_prod_arrow (A B C : Type) : (A → B → C) ≃ (A × B → C) :=
mk (λ f, λ p, f p.1 p.2)
(λ f, λ a b, f (a, b))
(λ f, rfl)
(λ f, funext (λ p, begin cases p, esimp end))
open sum
definition sum_arrow_equiv_prod_arrow (A B C : Type) : ((A + B) → C) ≃ ((A → C) × (B → C)) :=
mk (λ f, (λ a, f (inl a), λ b, f (inr b)))
(λ p, (λ s, match s with inl a := p.1 a | inr b := p.2 b end))
(λ f, funext (λ s, begin cases s, esimp, esimp end))
(λ p, begin cases p, esimp end)
definition sum_prod_distrib (A B C : Type) : ((A + B) × C) ≃ ((A × C) + (B × C)) :=
mk (λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end)
(λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end)
(λ p, begin cases p with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with ac bc, cases ac, esimp, cases bc, esimp end)
definition prod_sum_distrib (A B C : Type) : (A × (B + C)) ≃ ((A × B) + (A × C)) :=
calc (A × (B + C)) ≃ ((B + C) × A) : prod_comm
... ≃ ((B × A) + (C × A)) : sum_prod_distrib
... ≃ ((A × B) + (A × C)) : sum_congr !prod_comm !prod_comm
definition bool_prod_equiv_sum (A : Type) : (bool × A) ≃ (A + A) :=
calc (bool × A) ≃ ((unit + unit) × A) : prod_congr bool_equiv_unit_sum_unit !equiv.refl
... ≃ (A × (unit + unit)) : prod_comm
... ≃ ((A × unit) + (A × unit)) : prod_sum_distrib
... ≃ (A + A) : sum_congr !prod_unit_right !prod_unit_right
end
section
open sum nat unit prod.ops
definition nat_equiv_nat_sum_unit : nat ≃ (nat + unit) :=
mk (λ n, match n with zero := inr star | succ a := inl a end)
(λ s, match s with inl n := succ n | inr star := zero end)
(λ n, begin cases n, repeat esimp end)
(λ s, begin cases s with a u, esimp, {cases u, esimp} end)
attribute [simp]
definition nat_sum_unit_equiv_nat : (nat + unit) ≃ nat :=
equiv.symm nat_equiv_nat_sum_unit
attribute [simp]
definition nat_prod_nat_equiv_nat : (nat × nat) ≃ nat :=
mk (λ p, mkpair p.1 p.2)
(λ n, unpair n)
(λ p, begin cases p, apply unpair_mkpair end)
(λ n, mkpair_unpair n)
attribute [simp]
definition nat_sum_bool_equiv_nat : (nat + bool) ≃ nat :=
calc (nat + bool) ≃ (nat + (unit + unit)) : sum_congr !equiv.refl bool_equiv_unit_sum_unit
... ≃ ((nat + unit) + unit) : sum_assoc
... ≃ (nat + unit) : sum_congr nat_sum_unit_equiv_nat !equiv.refl
... ≃ nat : nat_sum_unit_equiv_nat
open decidable
attribute [simp]
definition nat_sum_nat_equiv_nat : (nat + nat) ≃ nat :=
mk (λ s, match s with inl n := 2*n | inr n := 2*n+1 end)
(λ n, if even n then inl (n / 2) else inr ((n - 1) / 2))
(λ s, begin
have two_gt_0 : 2 > zero, from dec_trivial,
cases s,
{esimp, rewrite [if_pos (even_two_mul _), nat.mul_div_cancel_left _ two_gt_0]},
{esimp, rewrite [if_neg (not_even_two_mul_plus_one _), nat.add_sub_cancel,
nat.mul_div_cancel_left _ two_gt_0]}
end)
(λ n, by_cases
(λ h : even n,
by rewrite [if_pos h]; esimp; rewrite [nat.mul_div_cancel' (dvd_of_even h)])
(λ h : ¬ even n,
begin
rewrite [if_neg h], esimp,
cases n,
{exact absurd even_zero h},
{rewrite [-(add_one a), nat.add_sub_cancel,
nat.mul_div_cancel' (dvd_of_even (even_of_odd_succ (odd_of_not_even h)))]}
end))
definition prod_equiv_of_equiv_nat {A : Type} : A ≃ nat → (A × A) ≃ A :=
take e, calc
(A × A) ≃ (nat × nat) : prod_congr e e
... ≃ nat : nat_prod_nat_equiv_nat
... ≃ A : equiv.symm e
end
section
open decidable
definition decidable_eq_of_equiv {A B : Type} [h : decidable_eq A] : A ≃ B → decidable_eq B
| (mk f g l r) :=
take b₁ b₂, match h (g b₁) (g b₂) with
| inl he := inl (have aux : f (g b₁) = f (g b₂), from congr_arg f he,
begin rewrite *r at aux, exact aux end)
| inr hn := inr (λ b₁eqb₂, by subst b₁eqb₂; exact absurd rfl hn)
end
end
definition inhabited_of_equiv {A B : Type} [h : inhabited A] : A ≃ B → inhabited B
| (mk f g l r) := inhabited.mk (f (inhabited.value h))
section
open subtype
definition subtype_equiv_of_subtype {A B : Type} {p : A → Prop} : A ≃ B → {a : A | p a} ≃ {b : B | p b⁻¹}
| (mk f g l r) :=
mk (λ s, match s with tag v h := tag (f v) (eq.rec_on (eq.symm (l v)) h) end)
(λ s, match s with tag v h := tag (g v) (eq.rec_on (eq.symm (r v)) h) end)
(λ s, begin cases s, esimp, congruence, rewrite l, reflexivity end)
(λ s, begin cases s, esimp, congruence, rewrite r, reflexivity end)
end
section swap
variable {A : Type}
variable [h : decidable_eq A]
include h
open decidable
definition swap_core (a b r : A) : A :=
if r = a then b
else if r = b then a
else r
lemma swap_core_swap_core (r a b : A) : swap_core a b (swap_core a b r) = r :=
by_cases
(suppose r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos (eq.refl b), -`r = a`, -`r = b`, if_pos (eq.refl r)] end)
(suppose ¬ r = b,
have b ≠ a, from assume h, begin rewrite h at this, contradiction end,
begin unfold swap_core, rewrite [*if_pos `r = a`, if_pos (eq.refl b), if_neg `b ≠ a`, `r = a`] end))
(suppose ¬ r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`, if_pos (eq.refl a), this] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`, if_neg `¬ r = a`] end))
lemma swap_core_self (r a : A) : swap_core a a r = r :=
by_cases
(suppose r = a, begin unfold swap_core, rewrite [*if_pos this, this] end)
(suppose r ≠ a, begin unfold swap_core, rewrite [*if_neg this] end)
lemma swap_core_comm (r a b : A) : swap_core a b r = swap_core b a r :=
by_cases
(suppose r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos `r = b`, -`r = a`, -`r = b`] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_pos `r = a`, if_neg `¬ r = b`] end))
(suppose ¬ r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`] end))
definition swap (a b : A) : perm A :=
mk (swap_core a b)
(swap_core a b)
(λ x, abstract by rewrite swap_core_swap_core end)
(λ x, abstract by rewrite swap_core_swap_core end)
lemma swap_self (a : A) : swap a a = id :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_self end))
lemma swap_comm (a b : A) : swap a b = swap b a :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_comm end))
lemma swap_apply_def (a b : A) (x : A) : swap a b ∙ x = if x = a then b else if x = b then a else x :=
rfl
lemma swap_apply_left (a b : A) : swap a b ∙ a = b :=
if_pos rfl
lemma swap_apply_right (a b : A) : swap a b ∙ b = a :=
by_cases
(suppose b = a, by rewrite [swap_apply_def, this, *if_pos rfl])
(suppose b ≠ a, by rewrite [swap_apply_def, if_pos rfl, if_neg this])
lemma swap_apply_of_ne_of_ne {a b : A} {x : A} : x ≠ a → x ≠ b → swap a b ∙ x = x :=
assume h₁ h₂, by rewrite [swap_apply_def, if_neg h₁, if_neg h₂]
lemma swap_swap (a b : A) : swap a b ∘ swap a b = id :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn, equiv.trans, equiv.refl], rewrite swap_core_swap_core end))
lemma swap_comp_apply (a b : A) (π : perm A) (x : A) : (swap a b ∘ π) ∙ x = if π ∙ x = a then b else if π ∙ x = b then a else π ∙ x :=
begin cases π, reflexivity end
end swap
end equiv
|
ce898f52d8448b4b72632e37c9eea06e973b7010 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/theories/analysis/real_deriv.lean | 14e439a6fd89c4c768863afec61158efeb4f5427 | [
"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,988 | lean | /-
Copyright (c) 2016 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
Derivatives on ℝ
-/
import .bounded_linear_operator
open real nat classical topology analysis set
noncomputable theory
namespace real
-- make instance of const mul bdd lin op?
definition has_deriv_at (f : ℝ → ℝ) (d x : ℝ) := has_frechet_deriv_at f (λ t, d • t) x
theorem has_deriv_at_intro (f : ℝ → ℝ) (d x : ℝ) (H : (λ h, (f (x + h) - f x) / h) ⟶ d [at 0]) :
has_deriv_at f d x :=
begin
apply has_frechet_deriv_at_intro,
intros ε Hε,
cases approaches_at_dest H Hε with δ Hδ,
existsi δ,
split,
exact and.left Hδ,
intro y Hy,
rewrite [-sub_zero y at Hy{2}],
note Hδ' := and.right Hδ y (and.right Hy) (and.left Hy),
have Hδ'' : abs ((f (x + y) - f x - d * y) / y) < ε,
by rewrite [-div_sub_div_same, mul_div_cancel _ (and.left Hy)]; apply Hδ',
show abs (f (x + y) - f x - d * y) / abs y < ε, by rewrite -abs_div; apply Hδ''
end
theorem has_deriv_at_of_has_frechet_deriv_at {f g : ℝ → ℝ} [is_bdd_linear_map g] {d x : ℝ}
(H : has_frechet_deriv_at f g x) (Hg : g = λ x, d * x) :
has_deriv_at f d x :=
by apply is_frechet_deriv_at_of_eq H Hg
theorem has_deriv_at_const (c x : ℝ) : has_deriv_at (λ t, c) 0 x :=
has_deriv_at_of_has_frechet_deriv_at
(@has_frechet_deriv_at_const ℝ ℝ _ _ _ c)
(funext (λ v, by rewrite zero_mul))
theorem has_deriv_at_id (x : ℝ) : has_deriv_at (λ t, t) 1 x :=
has_deriv_at_of_has_frechet_deriv_at
(@has_frechet_deriv_at_id ℝ ℝ _ _ _)
(funext (λ v, by rewrite one_mul))
theorem has_deriv_at_mul {f : ℝ → ℝ} {d x : ℝ} (H : has_deriv_at f d x) (c : ℝ) :
has_deriv_at (λ t, c * f t) (c * d) x :=
has_deriv_at_of_has_frechet_deriv_at
(has_frechet_deriv_at_smul _ _ c H)
(funext (λ v, by rewrite mul.assoc))
end real
|
4e7052244e9e10c34282c0d4916b9df8139a3538 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/analysis/special_functions/polynomials.lean | 64f772afc053cd7a25b55d752c60e0712a9efbb9 | [
"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 | 10,715 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Devon Tuma
-/
import analysis.asymptotics.asymptotic_equivalent
import analysis.asymptotics.specific_asymptotics
import data.polynomial.ring_division
/-!
# Limits related to polynomial and rational functions
This file proves basic facts about limits of polynomial and rationals functions.
The main result is `eval_is_equivalent_at_top_eval_lead`, which states that for
any polynomial `P` of degree `n` with leading coefficient `a`, the corresponding
polynomial function is equivalent to `a * x^n` as `x` goes to +∞.
We can then use this result to prove various limits for polynomial and rational
functions, depending on the degrees and leading coefficients of the considered
polynomials.
-/
open filter finset asymptotics
open_locale asymptotics topological_space
namespace polynomial
variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜] (P Q : polynomial 𝕜)
lemma eventually_no_roots (hP : P ≠ 0) : ∀ᶠ x in filter.at_top, ¬ P.is_root x :=
begin
obtain ⟨x₀, hx₀⟩ := exists_max_root P hP,
refine filter.eventually_at_top.mpr (⟨x₀ + 1, λ x hx h, _⟩),
exact absurd (hx₀ x h) (not_le.mpr (lt_of_lt_of_le (lt_add_one x₀) hx)),
end
variables [order_topology 𝕜]
section polynomial_at_top
lemma is_equivalent_at_top_lead :
(λ x, eval x P) ~[at_top] (λ x, P.leading_coeff * x ^ P.nat_degree) :=
begin
by_cases h : P = 0,
{ simp [h] },
{ conv_lhs
{ funext,
rw [polynomial.eval_eq_finset_sum, sum_range_succ] },
exact is_equivalent.refl.add_is_o (is_o.sum $ λ i hi, is_o.const_mul_left
(is_o.const_mul_right (λ hz, h $ leading_coeff_eq_zero.mp hz) $
is_o_pow_pow_at_top_of_lt (mem_range.mp hi)) _) }
end
lemma tendsto_at_top_of_leading_coeff_nonneg (hdeg : 1 ≤ P.degree) (hnng : 0 ≤ P.leading_coeff) :
tendsto (λ x, eval x P) at_top at_top :=
P.is_equivalent_at_top_lead.symm.tendsto_at_top
(tendsto_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg)
(lt_of_le_of_ne hnng $ ne.symm $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg))
lemma tendsto_at_top_iff_leading_coeff_nonneg :
tendsto (λ x, eval x P) at_top at_top ↔ 1 ≤ P.degree ∧ 0 ≤ P.leading_coeff :=
begin
refine ⟨λ h, _, λ h, tendsto_at_top_of_leading_coeff_nonneg P h.1 h.2⟩,
have : tendsto (λ x, P.leading_coeff * x ^ P.nat_degree) at_top at_top :=
is_equivalent.tendsto_at_top (is_equivalent_at_top_lead P) h,
rw tendsto_const_mul_pow_at_top_iff P.leading_coeff P.nat_degree at this,
rw [degree_eq_nat_degree (leading_coeff_ne_zero.mp (ne_of_lt this.2).symm), ← nat.cast_one],
refine ⟨with_bot.coe_le_coe.mpr this.1, le_of_lt this.2⟩,
end
lemma tendsto_at_bot_of_leading_coeff_nonpos (hdeg : 1 ≤ P.degree) (hnps : P.leading_coeff ≤ 0) :
tendsto (λ x, eval x P) at_top at_bot :=
P.is_equivalent_at_top_lead.symm.tendsto_at_bot
(tendsto_neg_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg)
(lt_of_le_of_ne hnps $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg))
lemma tendsto_at_bot_iff_leading_coeff_nonpos :
tendsto (λ x, eval x P) at_top at_bot ↔ 1 ≤ P.degree ∧ P.leading_coeff ≤ 0 :=
begin
refine ⟨λ h, _, λ h, tendsto_at_bot_of_leading_coeff_nonpos P h.1 h.2⟩,
have : tendsto (λ x, P.leading_coeff * x ^ P.nat_degree) at_top at_bot :=
(is_equivalent.tendsto_at_bot (is_equivalent_at_top_lead P) h),
rw tendsto_neg_const_mul_pow_at_top_iff P.leading_coeff P.nat_degree at this,
rw [degree_eq_nat_degree (leading_coeff_ne_zero.mp (ne_of_lt this.2)), ← nat.cast_one],
refine ⟨with_bot.coe_le_coe.mpr this.1, le_of_lt this.2⟩,
end
lemma abs_tendsto_at_top (hdeg : 1 ≤ P.degree) :
tendsto (λ x, abs $ eval x P) at_top at_top :=
begin
by_cases hP : 0 ≤ P.leading_coeff,
{ exact tendsto_abs_at_top_at_top.comp (P.tendsto_at_top_of_leading_coeff_nonneg hdeg hP)},
{ push_neg at hP,
exact tendsto_abs_at_bot_at_top.comp (P.tendsto_at_bot_of_leading_coeff_nonpos hdeg hP.le)}
end
lemma abs_is_bounded_under_iff :
is_bounded_under (≤) at_top (λ x, abs (eval x P)) ↔ P.degree ≤ 0 :=
begin
refine ⟨λ h, _, λ h, ⟨abs (P.coeff 0), eventually_map.mpr (eventually_of_forall
(forall_imp (λ _, le_of_eq) (λ x, congr_arg abs $ trans (congr_arg (eval x)
(eq_C_of_degree_le_zero h)) (eval_C))))⟩⟩,
contrapose! h,
exact not_is_bounded_under_of_tendsto_at_top
(abs_tendsto_at_top P (nat.with_bot.one_le_iff_zero_lt.2 h))
end
lemma abs_tendsto_at_top_iff :
tendsto (λ x, abs $ eval x P) at_top at_top ↔ 1 ≤ P.degree :=
⟨λ h, nat.with_bot.one_le_iff_zero_lt.2 (not_le.mp ((mt (abs_is_bounded_under_iff P).mpr)
(not_is_bounded_under_of_tendsto_at_top h))), abs_tendsto_at_top P⟩
lemma tendsto_nhds_iff {c : 𝕜} :
tendsto (λ x, eval x P) at_top (𝓝 c) ↔ P.leading_coeff = c ∧ P.degree ≤ 0 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ have := P.is_equivalent_at_top_lead.tendsto_nhds h,
by_cases hP : P.leading_coeff = 0,
{ simp only [hP, zero_mul, tendsto_const_nhds_iff] at this,
refine ⟨trans hP this, by simp [leading_coeff_eq_zero.1 hP]⟩ },
{ rw [tendsto_const_mul_pow_nhds_iff hP, nat_degree_eq_zero_iff_degree_le_zero] at this,
exact this.symm } },
{ refine P.is_equivalent_at_top_lead.symm.tendsto_nhds _,
have : P.nat_degree = 0 := nat_degree_eq_zero_iff_degree_le_zero.2 h.2,
simp only [h.1, this, pow_zero, mul_one],
exact tendsto_const_nhds }
end
end polynomial_at_top
section polynomial_div_at_top
lemma is_equivalent_at_top_div :
(λ x, (eval x P)/(eval x Q)) ~[at_top]
λ x, P.leading_coeff/Q.leading_coeff * x^(P.nat_degree - Q.nat_degree : ℤ) :=
begin
by_cases hP : P = 0,
{ simp [hP] },
by_cases hQ : Q = 0,
{ simp [hQ] },
refine (P.is_equivalent_at_top_lead.symm.div
Q.is_equivalent_at_top_lead.symm).symm.trans
(eventually_eq.is_equivalent ((eventually_gt_at_top 0).mono $ λ x hx, _)),
simp [← div_mul_div, hP, hQ, fpow_sub hx.ne.symm]
end
lemma div_tendsto_zero_of_degree_lt (hdeg : P.degree < Q.degree) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 0) :=
begin
by_cases hP : P = 0,
{ simp [hP, tendsto_const_nhds] },
rw ← nat_degree_lt_nat_degree_iff hP at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _,
rw ← mul_zero,
refine (tendsto_fpow_at_top_zero _).const_mul _,
linarith
end
lemma div_tendsto_zero_iff_degree_lt (hQ : Q ≠ 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 0) ↔ P.degree < Q.degree :=
begin
refine ⟨λ h, _, div_tendsto_zero_of_degree_lt P Q⟩,
by_cases hPQ : P.leading_coeff / Q.leading_coeff = 0,
{ simp only [div_eq_mul_inv, inv_eq_zero, mul_eq_zero] at hPQ,
cases hPQ with hP0 hQ0,
{ rw [leading_coeff_eq_zero.1 hP0, degree_zero],
exact bot_lt_iff_ne_bot.2 (λ hQ', hQ (degree_eq_bot.1 hQ')) },
{ exact absurd (leading_coeff_eq_zero.1 hQ0) hQ } },
{ have := (is_equivalent_at_top_div P Q).tendsto_nhds h,
rw tendsto_const_mul_fpow_at_top_zero_iff hPQ at this,
cases this with h h,
{ exact absurd h.2 hPQ },
{ rw [sub_lt_iff_lt_add, zero_add, int.coe_nat_lt] at h,
exact degree_lt_degree h.1 } }
end
lemma div_tendsto_leading_coeff_div_of_degree_eq (hdeg : P.degree = Q.degree) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 $ P.leading_coeff / Q.leading_coeff) :=
begin
refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _,
rw show (P.nat_degree : ℤ) = Q.nat_degree, by simp [hdeg, nat_degree],
simp [tendsto_const_nhds]
end
lemma div_tendsto_at_top_of_degree_gt' (hdeg : Q.degree < P.degree)
(hpos : 0 < P.leading_coeff/Q.leading_coeff) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top :=
begin
have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hpos, linarith},
rw ← nat_degree_lt_nat_degree_iff hQ at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_at_top _,
apply tendsto.const_mul_at_top hpos,
apply tendsto_fpow_at_top_at_top,
linarith
end
lemma div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) (hnng : 0 ≤ P.leading_coeff/Q.leading_coeff) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top :=
have ratio_pos : 0 < P.leading_coeff/Q.leading_coeff,
from lt_of_le_of_ne hnng
(div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h)
(λ h, hQ $ leading_coeff_eq_zero.mp h)).symm,
div_tendsto_at_top_of_degree_gt' P Q hdeg ratio_pos
lemma div_tendsto_at_bot_of_degree_gt' (hdeg : Q.degree < P.degree)
(hneg : P.leading_coeff/Q.leading_coeff < 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot :=
begin
have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hneg, linarith},
rw ← nat_degree_lt_nat_degree_iff hQ at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_at_bot _,
apply tendsto.neg_const_mul_at_top hneg,
apply tendsto_fpow_at_top_at_top,
linarith
end
lemma div_tendsto_at_bot_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) (hnps : P.leading_coeff/Q.leading_coeff ≤ 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot :=
have ratio_neg : P.leading_coeff/Q.leading_coeff < 0,
from lt_of_le_of_ne hnps
(div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h)
(λ h, hQ $ leading_coeff_eq_zero.mp h)),
div_tendsto_at_bot_of_degree_gt' P Q hdeg ratio_neg
lemma abs_div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) :
tendsto (λ x, abs ((eval x P)/(eval x Q))) at_top at_top :=
begin
by_cases h : 0 ≤ P.leading_coeff/Q.leading_coeff,
{ exact tendsto_abs_at_top_at_top.comp (P.div_tendsto_at_top_of_degree_gt Q hdeg hQ h) },
{ push_neg at h,
exact tendsto_abs_at_bot_at_top.comp (P.div_tendsto_at_bot_of_degree_gt Q hdeg hQ h.le) }
end
end polynomial_div_at_top
theorem is_O_of_degree_le (h : P.degree ≤ Q.degree) :
is_O (λ x, eval x P) (λ x, eval x Q) filter.at_top :=
begin
by_cases hp : P = 0,
{ simpa [hp] using is_O_zero (λ x, eval x Q) filter.at_top },
{ have hq : Q ≠ 0 := ne_zero_of_degree_ge_degree h hp,
have hPQ : ∀ᶠ (x : 𝕜) in at_top, eval x Q = 0 → eval x P = 0 :=
filter.mem_of_superset (polynomial.eventually_no_roots Q hq) (λ x h h', absurd h' h),
cases le_iff_lt_or_eq.mp h with h h,
{ exact is_O_of_div_tendsto_nhds hPQ 0 (div_tendsto_zero_of_degree_lt P Q h) },
{ exact is_O_of_div_tendsto_nhds hPQ _ (div_tendsto_leading_coeff_div_of_degree_eq P Q h) } }
end
end polynomial
|
d3eb035832424644ff41e37ba5454efcc9088fab | 2385ce0e3b60d8dbea33dd439902a2070cca7a24 | /tests/lean/run/1797.lean | 12a9338e022fe57613611fde8296ed2aa5f54472 | [
"Apache-2.0"
] | permissive | TehMillhouse/lean | 68d6fdd2fb11a6c65bc28dec308d70f04dad38b4 | 6bbf2fbd8912617e5a973575bab8c383c9c268a1 | refs/heads/master | 1,620,830,893,339 | 1,515,592,479,000 | 1,515,592,997,000 | 116,964,828 | 0 | 0 | null | 1,515,592,734,000 | 1,515,592,734,000 | null | UTF-8 | Lean | false | false | 144 | lean | example (n : nat) : true :=
begin
cases h : n with m,
{ guard_hyp h := n = nat.zero, sorry },
{ guard_hyp h := n = nat.succ m, sorry}
end
|
c5269f342d69a30537ec840b26b8b1c4aeb21132 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/basics/unnamed_349.lean | 09f4710429e345ee5d289449e9443d181297c1f1 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 320 | lean | import data.real.basic
variables a b : ℝ
-- BEGIN
example : (a + b) * (a + b) = a * a + 2 * (a * b) + b * b :=
calc
(a + b) * (a + b)
= a * a + b * a + (a * b + b * b) :
begin
sorry
end
... = a * a + (b * a + a * b) + b * b : by sorry
... = a * a + 2 * (a * b) + b * b : by sorry
-- END |
e8cc1f58fbf7e56a18230b4449cc4a9a45b87237 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast16.lean | b3bdcb0ca4908a7c745365ca751545c6dee9c95b | [
"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 | 202 | lean | set_option trace.blast true
example (p q : Prop) : p ∨ q → q ∨ p :=
by blast
definition lemma1 (p q r s : Prop) (a b : nat) : r ∨ s → p ∨ q → a = b → q ∨ p :=
by blast
print lemma1
|
8353bf971444a406579abcabb1550096e11970a5 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Init/Notation.lean | 6517d4da35987a64a6b3fb3b1f78d3209117dc95 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,457 | 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
Notation for operators defined at Prelude.lean
-/
prelude
import Init.Prelude
infixr:90 " ∘ " => Function.comp
infixr:35 " × " => Prod
infixl:65 " + " => Add.add
infixl:65 " - " => Sub.sub
infixl:70 " * " => Mul.mul
infixl:70 " / " => Div.div
infixl:70 " % " => Mod.mod
infixl:70 " %ₙ " => ModN.modn
infixr:80 " ^ " => Pow.pow
infix:50 " ≤ " => HasLessEq.LessEq
infix:50 " <= " => HasLessEq.LessEq
infix:50 " < " => HasLess.Less
infix:50 " ≥ " => GreaterEq
infix:50 " >= " => GreaterEq
infix:50 " > " => Greater
infix:50 " = " => Eq
infix:50 " == " => BEq.beq
infix:50 " ~= " => HEq
infix:50 " ≅ " => HEq
infixr:35 " ∧ " => And
infixr:35 " /\\ " => And
infixr:30 " ∨ " => Or
infixr:30 " \\/ " => Or
infixl:35 " && " => and
infixl:30 " || " => or
infixl:65 " ++ " => Append.append
infixr:67 " :: " => List.cons
infixr:2 " <|> " => OrElse.orElse
infixr:60 " >> " => AndThen.andThen
infixl:55 " >>= " => Bind.bind
infixl:60 " <*> " => Seq.seq
infixl:60 " <* " => SeqLeft.seqLeft
infixr:60 " *> " => SeqRight.seqRight
infixr:100 " <$> " => Functor.map
macro "if" h:ident " : " c:term " then " t:term " else " e:term : term =>
`(dite $c (fun $h => $t) (fun $h => $e))
macro "if" c:term " then " t:term " else " e:term : term =>
`(ite $c $t $e)
|
5230e745497b3cd2530a3a31175f134c1735068c | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/testing/slim_check/testable.lean | 7087b24ed77dcded41cbb278c904d65bcb411027 | [
"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 | 22,903 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import testing.slim_check.sampleable
/-!
# `testable` Class
Testable propositions have a procedure that can generate counter-examples
together with a proof that they invalidate the proposition.
This is a port of the Haskell QuickCheck library.
## Creating Customized Instances
The type classes `testable` and `sampleable` are the means by which
`slim_check` creates samples and tests them. For instance, the proposition
`∀ i j : ℕ, i ≤ j` has a `testable` instance because `ℕ` is sampleable
and `i ≤ j` is decidable. Once `slim_check` finds the `testable`
instance, it can start using the instance to repeatedly creating samples
and checking whether they satisfy the property. This allows the
user to create new instances and apply `slim_check` to new situations.
### Polymorphism
The property `testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys
= ys ++ xs)` shows us that type-polymorphic properties can be
tested. `α` is instantiated with `ℤ` first and then tested as normal
monomorphic properties.
The monomorphisation limits the applicability of `slim_check` to
polymorphic properties that can be stated about integers. The
limitation may be lifted in the future but, for now, if
one wishes to use a different type than `ℤ`, one has to refer to
the desired type.
### What do I do if I'm testing a property about my newly defined type?
Let us consider a type made for a new formalization:
```lean
structure my_type :=
(x y : ℕ)
(h : x ≤ y)
```
How do we test a property about `my_type`? For instance, let us consider
`testable.check $ ∀ a b : my_type, a.y ≤ b.x → a.x ≤ b.y`. Writing this
property as is will give us an error because we do not have an instance
of `sampleable my_type`. We can define one as follows:
```lean
instance : sampleable my_type :=
{ sample := do
x ← sample ℕ,
xy_diff ← sample ℕ,
return { x := x, y := x + xy_diff, h := /- some proof -/ } }
```
We can see that the instance is very simple because our type is built
up from other type that have `sampleable` instances. `sampleable` also
has a `shrink` method but it is optional. We may want to implement one
for ease of testing as:
```lean
/- ... -/
shrink := λ ⟨x,y,h⟩, (λ ⟨x,y⟩, { x := x, y := x + y, h := /- proof -/}) <$> shrink (x, y - x)
}
```
Again, we take advantage of the fact that other types have useful
`shrink` implementations, in this case `prod`.
### Optimizing the sampling
Some properties are guarded by a proposition. For instance, recall this
example:
```lean
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100)
```
When testing the above example, we generate a natural number, we check
that it is even and test it if it is even or throw it away and start
over otherwise. Statistically, we can expect half of our samples to be
thrown away by such a filter. Sometimes, the filter is more
restrictive. For instance we might need `x` to be a `prime`
number. This would cause most of our samples to be discarded.
We can help `slim_check` find good samples by providing specialized
sampleable instances. Below, we show an instance for the subtype
of even natural numbers. This means that, when producing
a sample, it is forced to produce a proof that it is even.
```lean
instance {k : ℕ} [fact (0 < k)] : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
```
Such instance will be preferred when testing a proposition of the shape
`∀ x : T, p x → q`
We can observe the effect by enabling tracing:
```lean
/- no specialized sampling -/
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { enable_tracing := tt }
-- discard
-- x := 1
-- discard
-- x := 41
-- discard
-- x := 3
-- discard
-- x := 5
-- discard
-- x := 5
-- discard
-- x := 197
-- discard
-- x := 469
-- discard
-- x := 9
-- discard
-- ===================
-- Found problems!
-- x := 552
-- -------------------
/- let us define a specialized sampling instance -/
instance {k : ℕ} : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { enable_tracing := tt }
-- ===================
-- Found problems!
-- x := 358
-- -------------------
```
Similarly, it is common to write properties of the form: `∀ i j, i ≤ j → ...`
as the following example show:
```lean
#eval check (∀ i j k : ℕ, j < k → i - k < i - j)
```
Without subtype instances, the above property discards many samples
because `j < k` does not hold. Fortunately, we have appropriate
instance to choose `k` intelligently.
## Main definitions
* `testable` class
* `testable.check`: a way to test a proposition using random examples
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v
variables var var' : string
variable α : Type u
variable β : α → Prop
variable f : Type → Prop
namespace slim_check
/-- Result of trying to disprove `p`
The constructors are:
* `success : (psum unit p) → test_result`
succeed when we find another example satisfying `p`
In `success h`, `h` is an optional proof of the proposition.
Without the proof, all we know is that we found one example
where `p` holds. With a proof, the one test was sufficient to
prove that `p` holds and we do not need to keep finding examples.
* `gave_up {} : ℕ → test_result`
give up when a well-formed example cannot be generated.
`gave_up n` tells us that `n` invalid examples were tried.
Above 100, we give up on the proposition and report that we
did not find a way to properly test it.
* `failure : ¬ p → (list string) → test_result`
a counter-example to `p`; the strings specify values for the relevant variables.
`failure h vs` also carries a proof that `p` does not hold. This way, we can
guarantee no false positive.
-/
@[derive inhabited]
inductive test_result (p : Prop)
| success : (psum unit p) → test_result
| gave_up {} : ℕ → test_result
| failure : ¬ p → (list string) → test_result
/-- format a `test_result` as a string. -/
def test_result.to_string {p} : test_result p → string
| (test_result.success (psum.inl ())) := "success (without proof)"
| (test_result.success (psum.inr h)) := "success (with proof)"
| (test_result.gave_up n) := sformat!"gave up {n} times"
| (test_result.failure a vs) := sformat!"failed {vs}"
instance {p} : has_to_string (test_result p) := ⟨ test_result.to_string ⟩
/-- `testable p` uses random examples to try to disprove `p`. -/
class testable (p : Prop) :=
(run [] (enable_tracing minimize : bool) : gen (test_result p))
open list
open test_result
/-- applicative combinator proof carrying test results -/
def combine {p q : Prop} : psum unit (p → q) → psum unit p → psum unit q
| (psum.inr f) (psum.inr x) := psum.inr (f x)
| _ _ := psum.inl ()
/-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/
def and_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∧ q)
| (failure Hce xs) _ := failure (λ h, Hce h.1) xs
| _ (failure Hce xs) := failure (λ h, Hce h.2) xs
| (success xs) (success ys) := success $ combine (combine (psum.inr and.intro) xs) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- Combine the test result for properties `p` and `q` to create a test for their disjunction -/
def or_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∨ q)
| (failure Hce xs) (failure Hce' ys) := failure (λ h, or_iff_not_and_not.1 h ⟨Hce, Hce'⟩) (xs ++ ys)
| (success xs) _ := success $ combine (psum.inr or.inl) xs
| _ (success ys) := success $ combine (psum.inr or.inr) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us
to find counter-examples to `q`. -/
def convert_counter_example {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs) _ := failure (mt h Hce) xs
| (success Hp) Hpq := success (combine Hpq Hp)
| (gave_up n) _ := gave_up n
/-- Test `q` by testing `p` and proving the equivalence between the two. -/
def convert_counter_example' {p q : Prop}
(h : p ↔ q) (r : test_result p) :
test_result q :=
convert_counter_example h.2 r (psum.inr h.1)
/-- When we assign a value to a universally quantified variable,
we record that value using this function so that our counter-examples
can be informative. -/
def add_to_counter_example (x : string) {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs) _ := failure (mt h Hce) $ x :: xs
| r hpq := convert_counter_example h r hpq
/-- Add some formatting to the information recorded by `add_to_counter_example`. -/
def add_var_to_counter_example {γ : Type v} [has_to_string γ]
(var : string) (x : γ) {p q : Prop}
(h : q → p) : test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q :=
@add_to_counter_example (var ++ " := " ++ to_string x) _ _ h
/-- Gadget used to introspect the name of bound variables.
It is used with the `testable` typeclass so that
`testable (named_binder "x" (∀ x, p x))` can use the variable name
of `x` in error messages displayed to the user. If we find that instantiating
the above quantifier with 3 falsifies it, we can print:
```
==============
Problem found!
==============
x := 3
```
-/
@[simp, nolint unused_arguments]
def named_binder (n : string) (p : Prop) : Prop := p
/-- Is the given test result a failure? -/
def is_failure {p} : test_result p → bool
| (test_result.failure _ _) := tt
| _ := ff
instance and_testable (p q : Prop) [testable p] [testable q] :
testable (p ∧ q) :=
⟨ λ tracing min, do
xp ← testable.run p tracing min,
xq ← testable.run q tracing min,
pure $ and_counter_example xp xq ⟩
instance or_testable (p q : Prop) [testable p] [testable q] :
testable (p ∨ q) :=
⟨ λ tracing min, do
xp ← testable.run p tracing min,
match xp with
| success (psum.inl h) := pure $ success (psum.inl h)
| success (psum.inr h) := pure $ success (psum.inr $ or.inl h)
| _ := do
xq ← testable.run q tracing min,
pure $ or_counter_example xp xq
end ⟩
instance iff_testable (p q : Prop) [testable ((p ∧ q) ∨ (¬ p ∧ ¬ q))] :
testable (p ↔ q) :=
⟨ λ tracing min, do
xp ← testable.run ((p ∧ q) ∨ (¬ p ∧ ¬ q)) tracing min,
return $ convert_counter_example' (by tauto!) xp ⟩
@[priority 1000]
instance imp_dec_testable (p : Prop) [decidable p] (β : p → Prop)
[∀ h, testable (β h)] : testable (named_binder var $ Π h, β h) :=
⟨ λ tracing min, do
if h : p
then (λ r, convert_counter_example ($ h) r (psum.inr $ λ q _, q)) <$> testable.run (β h) tracing min
else if tracing then trace "discard" $ return $ gave_up 1
else return $ gave_up 1 ⟩
@[priority 2000]
instance all_types_testable [testable (f ℤ)] : testable (named_binder var $ Π x, f x) :=
⟨ λ tracing min, do
r ← testable.run (f ℤ) tracing min,
return $ add_var_to_counter_example var "ℤ" ($ ℤ) r ⟩
/-- Trace the value of sampled variables if the sample is discarded. -/
def trace_if_giveup {p α β} [has_to_string α] (tracing_enabled : bool) (var : string) (val : α) :
test_result p → thunk β → β
| (test_result.gave_up _) :=
if tracing_enabled then trace (sformat!" {var} := {val}")
else ($ ())
| _ := ($ ())
/-- testable instance for a property iterating over the element of a list -/
@[priority 5000]
instance test_forall_in_list
[∀ x, testable (β x)] [has_to_string α] :
Π xs : list α, testable (named_binder var $ ∀ x, named_binder var' $ x ∈ xs → β x)
| [] := ⟨ λ tracing min, return $ success $ psum.inr (by { introv x h, cases h} ) ⟩
| (x :: xs) :=
⟨ λ tracing min, do
r ← testable.run (β x) tracing min,
trace_if_giveup tracing var x r $
match r with
| failure _ _ := return $ add_var_to_counter_example var x
(by { intro h, apply h, left, refl }) r
| success hp := do
rs ← @testable.run _ (test_forall_in_list xs) tracing min,
return $ convert_counter_example
(by { intros h i h',
apply h,
right, apply h' })
rs
(combine (psum.inr
$ by { intros j h, simp only [ball_cons,named_binder],
split ; assumption, } ) hp)
| gave_up n := do
rs ← @testable.run _ (test_forall_in_list xs) tracing min,
match rs with
| (success _) := return $ gave_up n
| (failure Hce xs) := return $ failure
(by { simp only [ball_cons,named_binder],
apply not_and_of_not_right _ Hce, }) xs
| (gave_up n') := return $ gave_up (n + n')
end
end ⟩
/-- Test proposition `p` by randomly selecting one of the provided
testable instances. -/
def combine_testable (p : Prop)
(t : list $ testable p) (h : 0 < t.length) : testable p :=
⟨ λ tracing min, have 0 < length (map (λ t, @testable.run _ t tracing min) t),
by { rw [length_map], apply h },
gen.one_of (list.map (λ t, @testable.run _ t tracing min) t) this ⟩
/-- Shrink a counter-example `x` by using `shrink x`, picking the first
candidate that falsifies a property and recursively shrinking that one.
The process is guaranteed to terminate because `shrink x` produces
a proof that all the values it produces are smaller (according to `sizeof`)
than `x`. -/
def minimize_aux [sampleable α] [∀ x, testable (β x)] : α → option_t gen (Σ x, test_result (β x)) :=
well_founded.fix has_well_founded.wf $ λ x f_rec, do
⟨y,h₀,⟨h₁⟩⟩ ← (shrink x).mfirst (λ ⟨a,h⟩, do
⟨r⟩ ← monad_lift (uliftable.up $ testable.run (β a) ff tt : gen (ulift (test_result (β a)))),
if is_failure r
then pure (⟨a, r, ⟨h⟩⟩ : (Σ a, test_result (β a) × plift (sizeof_lt a x)))
else failure),
f_rec y h₁ <|> pure ⟨y,h₀⟩.
/-- Once a property fails to hold on an example, look for smaller counter-examples
to show the user. -/
def minimize [sampleable α] [∀ x, testable (β x)] (x : α) (r : test_result (β x)) : gen (Σ x, test_result (β x)) := do
x' ← option_t.run $ minimize_aux α _ x,
pure $ x'.get_or_else ⟨x, r⟩
@[priority 2000]
instance exists_testable (p : Prop)
[testable (named_binder var (∀ x, named_binder var' $ β x → p))] :
testable (named_binder var' (named_binder var (∃ x, β x) → p)) :=
⟨ λ tracing min, do
x ← testable.run (named_binder var (∀ x, named_binder var' $ β x → p)) tracing min,
pure $ convert_counter_example' exists_imp_distrib.symm x ⟩
@[priority 5000]
instance exists_testable' (xs : list α) (p : Prop)
[testable (named_binder var (∀ x, named_binder "H" $ x ∈ xs → named_binder var' (β x → p)))] :
testable (named_binder var' (named_binder var (∃ x ∈ xs, β x) → p)) :=
⟨ λ tracing min, do
x ← testable.run (named_binder var (∀ x, named_binder "H" $ x ∈ xs → named_binder var' (β x → p))) tracing min,
pure $ convert_counter_example' (by simp) x ⟩
/-- Test a universal property by creating a sample of the right type and instantiating the
bound variable with it. -/
instance var_testable [∀ x, testable (β x)] [has_to_string α] [sampleable α] : testable (named_binder var $ Π x : α, β x) :=
⟨ λ tracing min, do
uliftable.adapt_down (sample α) $
λ x, do
r ← testable.run (β x) tracing ff,
uliftable.adapt_down (if is_failure r ∧ min
then minimize _ _ x r
else pure ⟨x,r⟩) $
λ ⟨x,r⟩, return (trace_if_giveup tracing var x r $ add_var_to_counter_example var x ($ x) r) ⟩
@[priority 3000]
instance unused_var_testable (β) [inhabited α] [testable β] : testable (named_binder var $ Π x : α, β) :=
⟨ λ tracing min, do
r ← testable.run β tracing min,
pure $ convert_counter_example ($ default _) r (psum.inr $ λ x _, x) ⟩
@[priority 2000]
instance subtype_var_testable (p : α → Prop) [has_to_string α]
[∀ x, testable (β x)] [sampleable (subtype p)] :
testable (named_binder var $ Π x : α, named_binder var' $ p x → β x) :=
⟨ λ tracing min,
do r ← @testable.run (∀ x : subtype p, β x.val) (slim_check.var_testable var _ _) tracing min,
pure $ convert_counter_example'
⟨λ (h : ∀ x : subtype p, β x) x h', h ⟨x,h'⟩,
λ h ⟨x,h'⟩, h x h'⟩
r ⟩
@[priority 100]
instance decidable_testable (p : Prop) [decidable p] : testable p :=
⟨ λ tracing min, return $ if h : p then success (psum.inr h) else failure h [] ⟩
instance eq_testable {α} [has_repr α] (x y : α) [decidable_eq α] : testable (x = y) :=
⟨ λ tracing min, return $ if h : x = y then success (psum.inr h) else failure h [sformat!"{repr x} ≠ {repr y}"] ⟩
section io
open nat
variable {p : Prop}
/-- Execute `cmd` and repeat every time the result is `gave_up` (at most
`n` times). -/
def retry (cmd : rand (test_result p)) : ℕ → rand (test_result p)
| 0 := return $ gave_up 1
| (succ n) := do
r ← cmd,
match r with
| success hp := return $ success hp
| (failure Hce xs) := return (failure Hce xs)
| (gave_up _) := retry n
end
/-- Count the number of times the test procedure gave up. -/
def give_up (x : ℕ) : test_result p → test_result p
| (success (psum.inl ())) := gave_up x
| (success (psum.inr p)) := success (psum.inr p)
| (gave_up n) := gave_up (n+x)
| (failure Hce xs) := failure Hce xs
variable (p)
variable [testable p]
/-- configuration for testing a property -/
@[derive [has_reflect, inhabited]]
structure slim_check_cfg :=
(num_inst : ℕ := 100) -- number of examples
(max_size : ℕ := 100) -- final size argument
(enable_tracing : bool := ff) -- enable the printing out of discarded samples
(random_seed : option ℕ := none) -- specify a seed to the random number generator to
-- obtain a deterministic behavior
(quiet : bool := ff) -- suppress success message when running `slim_check`
/-- Try `n` times to find a counter-example for `p`. -/
def testable.run_suite_aux (cfg : slim_check_cfg) : test_result p → ℕ → rand (test_result p)
| r 0 := return r
| r (succ n) :=
do let size := (cfg.num_inst - n - 1) * cfg.max_size / cfg.num_inst,
x ← retry ( (testable.run p cfg.enable_tracing tt).run ⟨ size ⟩) 10,
match x with
| (success (psum.inl ())) := testable.run_suite_aux r n
| (success (psum.inr Hp)) := return $ success (psum.inr Hp)
| (failure Hce xs) := return (failure Hce xs)
| (gave_up g) := testable.run_suite_aux (give_up g r) n
end
/-- Try to find a counter-example of `p`. -/
def testable.run_suite (cfg : slim_check_cfg := {}) : rand (test_result p) :=
testable.run_suite_aux p cfg (success $ psum.inl ()) cfg.num_inst
/-- Run a test suite for `p` in `io`. -/
def testable.check' (cfg : slim_check_cfg := {}) : io (test_result p) :=
match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p cfg)
| none := io.run_rand (testable.run_suite p cfg)
end
namespace tactic
open tactic expr
/-!
## Decorations
Instances of `testable` use `named_binder` as a decoration on
propositions in order to access the name of bound variables, as in
`named_binder "x" (forall x, x < y)`. This helps the
`testable` instances create useful error messages where variables
are matched with values that falsify a given proposition.
The following functions help support the gadget so that the user does
not have to put them in themselves.
-/
/-- `add_existential_decorations p` adds `a `named_binder` annotation at the
root of `p` if `p` is an existential quantification. -/
meta def add_existential_decorations : expr → expr
| e@`(@Exists %%α %%(lam n bi d b)) :=
let n := to_string n in
const ``named_binder [] (`(n) : expr) e
| e := e
/-- Traverse the syntax of a proposition to find universal quantifiers
and existential quantifiers and add `named_binder` annotations next to
them. -/
meta def add_decorations : expr → expr | e :=
e.replace $ λ e _,
match e with
| (pi n bi d b) :=
let n := to_string n in
some $ const ``named_binder [] (`(n) : expr)
(pi n bi (add_existential_decorations d) (add_decorations b))
| e := none
end
/-- `decorations_of p` is used as a hint to `mk_decorations` to specify
that the goal should be satisfied with a proposition equivalent to `p`
with added annotations. -/
@[reducible, nolint unused_arguments]
def decorations_of (p : Prop) := Prop
/-- In a goal of the shape `⊢ tactic.decorations_of p`, `mk_decoration` examines
the syntax of `p` and add `named_binder` around universal quantifications and
existential quantifications to improve error messages.
This tool can be used in the declaration of a function as follows:
```lean
def foo (p : Prop) (p' : tactic.decorations_of p . mk_decorations) [testable p'] : ...
```
`p` is the parameter given by the user, `p'` is an equivalent proposition where
the quantifiers are annotated with `named_binder`.
-/
meta def mk_decorations : tactic unit := do
`(tactic.decorations_of %%p) ← target,
exact $ add_decorations p
end tactic
/-- Run a test suite for `p` and return true or false: should we believe that `p` holds? -/
def testable.check (p : Prop) (cfg : slim_check_cfg := {}) (p' : tactic.decorations_of p . tactic.mk_decorations) [testable p'] : io punit := do
x ← match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p' cfg)
| none := io.run_rand (testable.run_suite p' cfg)
end,
match x with
| (success _) := when (¬ cfg.quiet) $ io.put_str_ln "Success"
| (gave_up n) := io.fail sformat!"Gave up {repr n} times"
| (failure _ xs) := do
let counter_ex := string.intercalate "\n" xs,
io.fail sformat!"
===================
Found problems!
{counter_ex}
-------------------
"
end
end io
end slim_check
|
1f242c591c01886d182de881e1b38d93b476cf17 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/shadow.lean | 3628625f8837b3bb32eac192a60b5a29fc2e23c6 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 651 | lean | import Lean
new_frontend
theorem ex1 {α} (x : α) (h : x = x) (x : α) : x = x :=
h
set_option pp.sanitizeNames false in
theorem ex2 {α} (x : α) (h : x = x) (x : α) : x = x :=
h -- this error is confusing because we have disabled `pp.sanitizeNames`
def foo1 {α} [Inhabited α] (inst inst : α) : {β δ : Type} → α → β → δ → α × β × δ :=
_
set_option pp.sanitizeNames false in
def foo2 {α} [Inhabited α] (inst inst : α) : {β δ : Type} → α → β → δ → α × β × δ :=
_
def foo3 {α β} (inst : α) (inst : β) (b : β) (inst : α) [Inhabited α] : {β δ : Type} → α → β → δ → α × β × δ :=
_
|
2eab993c989ae1d90aedadd04b2922d7d3228835 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /assignments/hw3.lean | ee851b768c36a3f640aa1feab6887fb2b8f2cdca | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,293 | lean | /-
Review: bool
New: Product types
New: Polymorphic types
-/
/-
1. [30 points]
In class we implemented a polymorphic ordered
pair abstract data type that we called prod_S_T.
In a new file called dm_prod.lean re-implement
this ADT but call it dm_prod. Implement at least
the following functions:
- fst
- snd
- set_fst
- set_snd
- swap
For this part of the homework, write the function
definitions using lambda expressions and in all
cases specific "implicit arguments" for the type
arguments of these functions.
Then, in a second file called dm_prod_test.lean,
write test cases for your implementation. You
will have to import your dm_prod.lean file into
this test file so that it has access to your
dm_prod definitions.
Your test cases should include (1) the definitions
of three ordered pairs, p1, p2, and p3, with elements
types of ℕ and ℕ, ℕ and bool, and bool and bool,
respectively; (2) the use of #eval or #reduce to
confirm that your functions operate as expected,
at least for these test cases.
-/
/-
2. [40 points].
After each function definition in your dm_prod.test
file, write two new equivalent function definitions,
the first one using C-style and the second using "by
cases" style. Add one prime/tick mark to the name of
each C-style function to avoid name conflicts, and
two tick marks for the "cases-style" definitions. For
all functions, specify the use of implicit arguments
for type arguments.
-/
/-
3. [30 points]
Define a polymorphic ADT called dm_box. This type
builder takes one type argument. The intuitive
idea is that a dm_box contains one value of the
type specified by the type argument. Define dm_box
to have one constructor, mk, that takes one value
of the specified type and that produces a dm_box
with that value stored "in" the box. Note: a box
is very much like an ordered pair but it contains
only one value, not two. Define one "inspector"
function, unbox, that takes a dm_box and returns
the value "inside" the box. Write unbox, unbox',
and unbox'', using respectively lambda, C-style,
and cases syntax. Put your definitions in a file,
dm_box.lean, and write a few test cases, using
values of different types, in dm_box_test.lean.
-/
/-
Submit all four files required for this assigment
via the HW#3 assignment page on Collab.
-/ |
b677f3654fed6dd992be3c36ebab84ced1e0f9c1 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/category_theory/limits/shapes/images.lean | 28e5145ddb6be7172c04dd95658f76a77f57e055 | [
"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 | 27,284 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.strong_epi
/-!
# Categorical images
We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`,
so that `m` factors through the `m'` in any other such factorisation.
## Main definitions
* A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism
* `is_image F` means that a given mono factorisation `F` has the universal property of the image.
* `has_image f` means that we have chosen an image for the morphism `f : X ⟶ Y`.
* In this case, `image f` is the image object, `image.ι f : image f ⟶ Y` is the monomorphism `m`
of the factorisation and `factor_thru_image f : X ⟶ image f` is the morphism `e`.
* `has_images C` means that every morphism in `C` has an image.
* Let `f : X ⟶ Y` and `g : P ⟶ Q` be morphisms in `C`, which we will represent as objects of the
arrow category `arrow C`. Then `sq : f ⟶ g` is a commutative square in `C`. If `f` and `g` have
images, then `has_image_map sq` represents the fact that there is a morphism
`i : image f ⟶ image g` making the diagram
X ----→ image f ----→ Y
| | |
| | |
↓ ↓ ↓
P ----→ image g ----→ Q
commute, where the top row is the image factorisation of `f`, the bottom row is the image
factorisation of `g`, and the outer rectangle is the commutative square `sq`.
* If a category `has_images`, then `has_image_maps` means that every commutative square admits an
image map.
* If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is
always a strong epimorphism.
## Main statements
* When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism.
* When `C` has strong epi images, then these images admit image maps.
## Future work
* TODO: coimages, and abelian categories.
* TODO: connect this with existing working in the group theory and ring theory libraries.
-/
noncomputable theory
universes v u
open category_theory
open category_theory.limits.walking_parallel_pair
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {X Y : C} (f : X ⟶ Y)
/-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/
structure mono_factorisation (f : X ⟶ Y) :=
(I : C)
(m : I ⟶ Y)
[m_mono : mono m]
(e : X ⟶ I)
(fac' : e ≫ m = f . obviously)
restate_axiom mono_factorisation.fac'
attribute [simp, reassoc] mono_factorisation.fac
attribute [instance] mono_factorisation.m_mono
attribute [instance] mono_factorisation.m_mono
namespace mono_factorisation
/-- The obvious factorisation of a monomorphism through itself. -/
def self [mono f] : mono_factorisation f :=
{ I := X,
m := f,
e := 𝟙 X }
-- I'm not sure we really need this, but the linter says that an inhabited instance
-- ought to exist...
instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩
variables {f}
/-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely
determined. -/
@[ext]
lemma ext
{F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' :=
begin
cases F, cases F',
cases hI,
simp at hm,
dsimp at F_fac' F'_fac',
congr,
{ assumption },
{ resetI, apply (cancel_mono F_m).1,
rw [F_fac', hm, F'_fac'], }
end
/-- Any mono factorisation of `f` gives a mono factorisation of `f ≫ g` when `g` is a mono. -/
@[simps]
def comp_mono (F : mono_factorisation f) {Y' : C} (g : Y ⟶ Y') [mono g] :
mono_factorisation (f ≫ g) :=
{ I := F.I,
m := F.m ≫ g,
m_mono := mono_comp _ _,
e := F.e, }
/-- A mono factorisation of `f ≫ g`, where `g` is an isomorphism,
gives a mono factorisation of `f`. -/
@[simps]
def of_comp_iso {Y' : C} {g : Y ⟶ Y'} [is_iso g] (F : mono_factorisation (f ≫ g)) :
mono_factorisation f :=
{ I := F.I,
m := F.m ≫ (inv g),
m_mono := mono_comp _ _,
e := F.e, }
/-- Any mono factorisation of `f` gives a mono factorisation of `g ≫ f`. -/
@[simps]
def iso_comp (F : mono_factorisation f) {X' : C} (g : X' ⟶ X) :
mono_factorisation (g ≫ f) :=
{ I := F.I,
m := F.m,
e := g ≫ F.e, }
/-- A mono factorisation of `g ≫ f`, where `g` is an isomorphism,
gives a mono factorisation of `f`. -/
@[simps]
def of_iso_comp {X' : C} (g : X' ⟶ X) [is_iso g] (F : mono_factorisation (g ≫ f)) :
mono_factorisation f :=
{ I := F.I,
m := F.m,
e := inv g ≫ F.e, }
end mono_factorisation
variable {f}
/-- Data exhibiting that a given factorisation through a mono is initial. -/
structure is_image (F : mono_factorisation f) :=
(lift : Π (F' : mono_factorisation f), F.I ⟶ F'.I)
(lift_fac' : Π (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously)
restate_axiom is_image.lift_fac'
attribute [simp, reassoc] is_image.lift_fac
@[simp, reassoc] lemma is_image.fac_lift {F : mono_factorisation f} (hF : is_image F)
(F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e :=
(cancel_mono F'.m).1 $ by simp
variable (f)
namespace is_image
/-- The trivial factorisation of a monomorphism satisfies the universal property. -/
@[simps]
def self [mono f] : is_image (mono_factorisation.self f) :=
{ lift := λ F', F'.e }
instance [mono f] : inhabited (is_image (mono_factorisation.self f)) :=
⟨self f⟩
variable {f}
/-- Two factorisations through monomorphisms satisfying the universal property
must factor through isomorphic objects. -/
-- TODO this is another good candidate for a future `unique_up_to_canonical_iso`.
@[simps]
def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I ≅ F'.I :=
{ hom := hF.lift F',
inv := hF'.lift F,
hom_inv_id' := (cancel_mono F.m).1 (by simp),
inv_hom_id' := (cancel_mono F'.m).1 (by simp) }
variables {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F')
lemma iso_ext_hom_m : (iso_ext hF hF').hom ≫ F'.m = F.m := by simp
lemma iso_ext_inv_m : (iso_ext hF hF').inv ≫ F.m = F'.m := by simp
lemma e_iso_ext_hom : F.e ≫ (iso_ext hF hF').hom = F'.e := by simp
lemma e_iso_ext_inv : F'.e ≫ (iso_ext hF hF').inv = F.e := by simp
end is_image
/-- Data exhibiting that a morphism `f` has an image. -/
structure image_factorisation (f : X ⟶ Y) :=
(F : mono_factorisation f)
(is_image : is_image F)
instance inhabited_image_factorisation (f : X ⟶ Y) [mono f] : inhabited (image_factorisation f) :=
⟨⟨_, is_image.self f⟩⟩
/-- `has_image f` means that there exists an image factorisation of `f`. -/
class has_image (f : X ⟶ Y) : Prop :=
mk' :: (exists_image : nonempty (image_factorisation f))
lemma has_image.mk {f : X ⟶ Y} (F : image_factorisation f) : has_image f :=
⟨nonempty.intro F⟩
section
variable [has_image f]
/-- The chosen factorisation of `f` through a monomorphism. -/
def image.mono_factorisation : mono_factorisation f :=
(classical.choice (has_image.exists_image)).F
/-- The witness of the universal property for the chosen factorisation of `f` through
a monomorphism. -/
def image.is_image : is_image (image.mono_factorisation f) :=
(classical.choice (has_image.exists_image)).is_image
/-- The categorical image of a morphism. -/
def image : C := (image.mono_factorisation f).I
/-- The inclusion of the image of a morphism into the target. -/
def image.ι : image f ⟶ Y := (image.mono_factorisation f).m
@[simp] lemma image.as_ι : (image.mono_factorisation f).m = image.ι f := rfl
instance : mono (image.ι f) := (image.mono_factorisation f).m_mono
/-- The map from the source to the image of a morphism. -/
def factor_thru_image : X ⟶ image f := (image.mono_factorisation f).e
/-- Rewrite in terms of the `factor_thru_image` interface. -/
@[simp]
lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl
@[simp, reassoc]
lemma image.fac : factor_thru_image f ≫ image.ι f = f := (image.mono_factorisation f).fac'
variable {f}
/-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the
image. -/
def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (image.is_image f).lift F'
@[simp, reassoc]
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f :=
(image.is_image f).lift_fac' F'
@[simp, reassoc]
lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e :=
(image.is_image f).fac_lift F'
@[simp, reassoc]
lemma is_image.lift_ι {F : mono_factorisation f} (hF : is_image F) :
hF.lift (image.mono_factorisation f) ≫ image.ι f = F.m :=
hF.lift_fac _
-- TODO we could put a category structure on `mono_factorisation f`,
-- with the morphisms being `g : I ⟶ I'` commuting with the `m`s
-- (they then automatically commute with the `e`s)
-- and show that an `image_of f` gives an initial object there
-- (uniqueness of the lift comes for free).
instance lift_mono (F' : mono_factorisation f) : mono (image.lift F') :=
by { apply mono_of_mono _ F'.m, simpa using mono_factorisation.m_mono _ }
lemma has_image.uniq
(F' : mono_factorisation f) (l : image f ⟶ F'.I) (w : l ≫ F'.m = image.ι f) :
l = image.lift F' :=
(cancel_mono F'.m).1 (by simp [w])
/-- If `has_image g`, then `has_image (f ≫ g)` when `f` is an isomorphism. -/
instance {X Y Z : C} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) [has_image g] : has_image (f ≫ g) :=
{ exists_image := ⟨{
F :=
{ I := image g,
m := image.ι g,
e := f ≫ factor_thru_image g, },
is_image := { lift := λ F', image.lift { I := F'.I, m := F'.m, e := inv f ≫ F'.e, }, }, }⟩ }
end
section
variables (C)
/-- `has_images` represents a choice of image for every morphism -/
class has_images :=
(has_image : Π {X Y : C} (f : X ⟶ Y), has_image f)
attribute [instance, priority 100] has_images.has_image
end
section
variables (f) [has_image f]
/-- The image of a monomorphism is isomorphic to the source. -/
def image_mono_iso_source [mono f] : image f ≅ X :=
is_image.iso_ext (image.is_image f) (is_image.self f)
@[simp, reassoc]
lemma image_mono_iso_source_inv_ι [mono f] : (image_mono_iso_source f).inv ≫ image.ι f = f :=
by simp [image_mono_iso_source]
@[simp, reassoc]
lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ι f :=
begin
conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ι f, },
rw [←category.assoc, iso.hom_inv_id, category.id_comp],
end
-- This is the proof that `factor_thru_image f` is an epimorphism
-- from https://en.wikipedia.org/wiki/Image_%28category_theory%29, which is in turn taken from:
-- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1
@[ext]
lemma image.ext {W : C} {g h : image f ⟶ W} [has_limit (parallel_pair g h)]
(w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) :
g = h :=
begin
let q := equalizer.ι g h,
let e' := equalizer.lift _ w,
let F' : mono_factorisation f :=
{ I := equalizer g h,
m := q ≫ image.ι f,
m_mono := by apply mono_comp,
e := e' },
let v := image.lift F',
have t₀ : v ≫ q ≫ image.ι f = image.ι f := image.lift_fac F',
have t : v ≫ q = 𝟙 (image f) :=
(cancel_mono_id (image.ι f)).1 (by { convert t₀ using 1, rw category.assoc }),
-- The proof from wikipedia next proves `q ≫ v = 𝟙 _`,
-- and concludes that `equalizer g h ≅ image f`,
-- but this isn't necessary.
calc g = 𝟙 (image f) ≫ g : by rw [category.id_comp]
... = v ≫ q ≫ g : by rw [←t, category.assoc]
... = v ≫ q ≫ h : by rw [equalizer.condition g h]
... = 𝟙 (image f) ≫ h : by rw [←category.assoc, t]
... = h : by rw [category.id_comp]
end
instance [Π {Z : C} (g h : image f ⟶ Z), has_limit (parallel_pair g h)] :
epi (factor_thru_image f) :=
⟨λ Z g h w, image.ext f w⟩
lemma epi_image_of_epi {X Y : C} (f : X ⟶ Y) [has_image f] [E : epi f] : epi (image.ι f) :=
begin
rw ←image.fac f at E,
resetI,
exact epi_of_epi (factor_thru_image f) (image.ι f),
end
lemma epi_of_epi_image {X Y : C} (f : X ⟶ Y) [has_image f]
[epi (image.ι f)] [epi (factor_thru_image f)] : epi f :=
by { rw [←image.fac f], apply epi_comp, }
end
section
variables {f} {f' : X ⟶ Y} [has_image f] [has_image f']
/--
An equation between morphisms gives a comparison map between the images
(which momentarily we prove is an iso).
-/
def image.eq_to_hom (h : f = f') : image f ⟶ image f' :=
image.lift
{ I := image f',
m := image.ι f',
e := factor_thru_image f', }.
instance (h : f = f') : is_iso (image.eq_to_hom h) :=
⟨⟨image.eq_to_hom h.symm,
⟨(cancel_mono (image.ι f)).1 (by simp [image.eq_to_hom]),
(cancel_mono (image.ι f')).1 (by simp [image.eq_to_hom])⟩⟩⟩
/-- An equation between morphisms gives an isomorphism between the images. -/
def image.eq_to_iso (h : f = f') : image f ≅ image f' := as_iso (image.eq_to_hom h)
/--
As long as the category has equalizers,
the image inclusion maps commute with `image.eq_to_iso`.
-/
lemma image.eq_fac [has_equalizers C] (h : f = f') :
image.ι f = (image.eq_to_iso h).hom ≫ image.ι f' :=
by { ext, simp [image.eq_to_iso, image.eq_to_hom], }
end
section
variables {Z : C} (g : Y ⟶ Z)
/-- The comparison map `image (f ≫ g) ⟶ image g`. -/
def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟶ image g :=
image.lift
{ I := image g,
m := image.ι g,
e := f ≫ factor_thru_image g }
@[simp, reassoc]
lemma image.pre_comp_ι [has_image g] [has_image (f ≫ g)] :
image.pre_comp f g ≫ image.ι g = image.ι (f ≫ g) :=
by simp [image.pre_comp]
@[simp, reassoc]
lemma image.factor_thru_image_pre_comp [has_image g] [has_image (f ≫ g)] :
factor_thru_image (f ≫ g) ≫ image.pre_comp f g = f ≫ factor_thru_image g :=
by simp [image.pre_comp]
/--
`image.pre_comp f g` is a monomorphism.
-/
instance image.pre_comp_mono [has_image g] [has_image (f ≫ g)] : mono (image.pre_comp f g) :=
begin
apply mono_of_mono _ (image.ι g),
simp only [image.pre_comp_ι],
apply_instance,
end
/--
The two step comparison map
`image (f ≫ (g ≫ h)) ⟶ image (g ≫ h) ⟶ image h`
agrees with the one step comparison map
`image (f ≫ (g ≫ h)) ≅ image ((f ≫ g) ≫ h) ⟶ image h`.
-/
lemma image.pre_comp_comp {W : C} (h : Z ⟶ W)
[has_image (g ≫ h)] [has_image (f ≫ g ≫ h)]
[has_image h] [has_image ((f ≫ g) ≫ h)] :
image.pre_comp f (g ≫ h) ≫ image.pre_comp g h =
image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) :=
begin
apply (cancel_mono (image.ι h)).1,
simp [image.pre_comp, image.eq_to_hom],
end
variables [has_equalizers C]
instance has_image_iso_comp [is_iso f] [has_image g] : has_image (f ≫ g) :=
has_image.mk
{ F := (image.mono_factorisation g).iso_comp f,
is_image := { lift := λ F', image.lift (F'.of_iso_comp f) }, }
/--
`image.pre_comp f g` is an isomorphism when `f` is an isomorphism
(we need `C` to have equalizers to prove this).
-/
instance image.is_iso_precomp_iso (f : X ⟶ Y) [is_iso f] [has_image g] :
is_iso (image.pre_comp f g) :=
⟨⟨image.lift
{ I := image (f ≫ g),
m := image.ι (f ≫ g),
e := inv f ≫ factor_thru_image (f ≫ g) },
⟨by { ext, simp [image.pre_comp], }, by { ext, simp [image.pre_comp], }⟩⟩⟩
-- Note that in general we don't have the other comparison map you might expect
-- `image f ⟶ image (f ≫ g)`.
instance has_image_comp_iso [has_image f] [is_iso g] : has_image (f ≫ g) :=
has_image.mk
{ F := (image.mono_factorisation f).comp_mono g,
is_image := { lift := λ F', image.lift F'.of_comp_iso }, }
/-- Postcomposing by an isomorphism induces an isomorphism on the image. -/
def image.comp_iso [has_image f] [is_iso g] :
image f ≅ image (f ≫ g) :=
{ hom := image.lift (image.mono_factorisation (f ≫ g)).of_comp_iso,
inv := image.lift ((image.mono_factorisation f).comp_mono g) }
@[simp, reassoc] lemma image.comp_iso_hom_comp_image_ι [has_image f] [is_iso g] :
(image.comp_iso f g).hom ≫ image.ι (f ≫ g) = image.ι f ≫ g :=
by { ext, simp [image.comp_iso] }
@[simp, reassoc] lemma image.comp_iso_inv_comp_image_ι [has_image f] [is_iso g] :
(image.comp_iso f g).inv ≫ image.ι f = image.ι (f ≫ g) ≫ inv g :=
by { ext, simp [image.comp_iso] }
end
end category_theory.limits
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
section
instance {X Y : C} (f : X ⟶ Y) [has_image f] : has_image (arrow.mk f).hom :=
show has_image f, by apply_instance
end
section has_image_map
/-- An image map is a morphism `image f → image g` fitting into a commutative square and satisfying
the obvious commutativity conditions. -/
structure image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) :=
(map : image f.hom ⟶ image g.hom)
(map_ι' : map ≫ image.ι g.hom = image.ι f.hom ≫ sq.right . obviously)
instance inhabited_image_map {f : arrow C} [has_image f.hom] : inhabited (image_map (𝟙 f)) :=
⟨⟨𝟙 _, by tidy⟩⟩
restate_axiom image_map.map_ι'
attribute [simp, reassoc] image_map.map_ι
@[simp, reassoc]
lemma image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(m : image_map sq) :
factor_thru_image f.hom ≫ m.map = sq.left ≫ factor_thru_image g.hom :=
(cancel_mono (image.ι g.hom)).1 $ by simp
/-- To give an image map for a commutative square with `f` at the top and `g` at the bottom, it
suffices to give a map between any mono factorisation of `f` and any image factorisation of
`g`. -/
def image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F')
{map : F.I ⟶ F'.I} (map_ι : map ≫ F'.m = F.m ≫ sq.right) : image_map sq :=
{ map := image.lift F ≫ map ≫ hF'.lift (image.mono_factorisation g.hom),
map_ι' := by simp [map_ι] }
/-- `has_image_map sq` means that there is an `image_map` for the square `sq`. -/
class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) : Prop :=
mk' :: (has_image_map : nonempty (image_map sq))
lemma has_image_map.mk {f g : arrow C} [has_image f.hom] [has_image g.hom] {sq : f ⟶ g}
(m : image_map sq) : has_image_map sq :=
⟨nonempty.intro m⟩
lemma has_image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F')
(map : F.I ⟶ F'.I) (map_ι : map ≫ F'.m = F.m ≫ sq.right) : has_image_map sq :=
has_image_map.mk $ image_map.transport sq F hF' map_ι
/-- Obtain an `image_map` from a `has_image_map` instance. -/
def has_image_map.image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
[has_image_map sq] : image_map sq :=
classical.choice $ @has_image_map.has_image_map _ _ _ _ _ _ sq _
variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
section
local attribute [ext] image_map
instance : subsingleton (image_map sq) :=
subsingleton.intro $ λ a b, image_map.ext a b $ (cancel_mono (image.ι g.hom)).1 $
by simp only [image_map.map_ι]
end
variable [has_image_map sq]
/-- The map on images induced by a commutative square. -/
abbreviation image.map : image f.hom ⟶ image g.hom :=
(has_image_map.image_map sq).map
lemma image.factor_map :
factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom :=
by simp
lemma image.map_ι : image.map sq ≫ image.ι g.hom = image.ι f.hom ≫ sq.right :=
by simp
lemma image.map_hom_mk'_ι {X Y P Q : C} {k : X ⟶ Y} [has_image k] {l : P ⟶ Q} [has_image l]
{m : X ⟶ P} {n : Y ⟶ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] :
image.map (arrow.hom_mk' w) ≫ image.ι l = image.ι k ≫ n :=
image.map_ι _
section
variables {h : arrow C} [has_image h.hom] (sq' : g ⟶ h)
variables [has_image_map sq']
/-- Image maps for composable commutative squares induce an image map in the composite square. -/
def image_map_comp : image_map (sq ≫ sq') :=
{ map := image.map sq ≫ image.map sq' }
@[simp]
lemma image.map_comp [has_image_map (sq ≫ sq')] :
image.map (sq ≫ sq') = image.map sq ≫ image.map sq' :=
show (has_image_map.image_map (sq ≫ sq')).map = (image_map_comp sq sq').map, by congr
end
section
variables (f)
/-- The identity `image f ⟶ image f` fits into the commutative square represented by the identity
morphism `𝟙 f` in the arrow category. -/
def image_map_id : image_map (𝟙 f) :=
{ map := 𝟙 (image f.hom) }
@[simp]
lemma image.map_id [has_image_map (𝟙 f)] : image.map (𝟙 f) = 𝟙 (image f.hom) :=
show (has_image_map.image_map (𝟙 f)).map = (image_map_id f).map, by congr
end
end has_image_map
section
variables (C) [has_images C]
/-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/
class has_image_maps :=
(has_image_map : Π {f g : arrow C} (st : f ⟶ g), has_image_map st)
attribute [instance, priority 100] has_image_maps.has_image_map
end
section has_image_maps
variables [has_images C] [has_image_maps C]
/-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image
and a commutative square to the induced morphism on images. -/
@[simps]
def im : arrow C ⥤ C :=
{ obj := λ f, image f.hom,
map := λ _ _ st, image.map st }
end has_image_maps
section strong_epi_mono_factorisation
/-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism
and `m` a monomorphism. -/
structure strong_epi_mono_factorisation {X Y : C} (f : X ⟶ Y) extends mono_factorisation f :=
[e_strong_epi : strong_epi e]
attribute [instance] strong_epi_mono_factorisation.e_strong_epi
/-- Satisfying the inhabited linter -/
instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟶ Y) [strong_epi f] :
inhabited (strong_epi_mono_factorisation f) :=
⟨⟨⟨Y, 𝟙 Y, f, by simp⟩⟩⟩
/-- A mono factorisation coming from a strong epi-mono factorisation always has the universal
property of the image. -/
def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟶ Y}
(F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation :=
{ lift := λ G, arrow.lift $ arrow.hom_mk' $
show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac] }
variable (C)
/-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono
factorisation. -/
class has_strong_epi_mono_factorisations : Prop :=
mk' :: (has_fac : Π {X Y : C} (f : X ⟶ Y), nonempty (strong_epi_mono_factorisation f))
variable {C}
lemma has_strong_epi_mono_factorisations.mk
(d : Π {X Y : C} (f : X ⟶ Y), strong_epi_mono_factorisation f) :
has_strong_epi_mono_factorisations C :=
⟨λ X Y f, nonempty.intro $ d f⟩
@[priority 100]
instance has_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_images C :=
{ has_image := λ X Y f,
let F' := classical.choice (has_strong_epi_mono_factorisations.has_fac f) in
has_image.mk { F := F'.to_mono_factorisation,
is_image := F'.to_mono_is_image } }
end strong_epi_mono_factorisation
section has_strong_epi_images
variables (C) [has_images C]
/-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong
epimorphism for all `f`. -/
class has_strong_epi_images : Prop :=
(strong_factor_thru_image : Π {X Y : C} (f : X ⟶ Y), strong_epi (factor_thru_image f))
attribute [instance] has_strong_epi_images.strong_factor_thru_image
end has_strong_epi_images
section has_strong_epi_images
/-- If there is a single strong epi-mono factorisation of `f`, then every image factorisation is a
strong epi-mono factorisation. -/
lemma strong_epi_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y}
(F : strong_epi_mono_factorisation f) {F' : mono_factorisation f} (hF' : is_image F') :
strong_epi F'.e :=
by { rw ←is_image.e_iso_ext_hom F.to_mono_is_image hF', apply strong_epi_comp }
lemma strong_epi_factor_thru_image_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y}
[has_image f] (F : strong_epi_mono_factorisation f) : strong_epi (factor_thru_image f) :=
strong_epi_of_strong_epi_mono_factorisation F $ image.is_image f
/-- If we constructed our images from strong epi-mono factorisations, then these images are
strong epi images. -/
@[priority 100]
instance has_strong_epi_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_strong_epi_images C :=
{ strong_factor_thru_image := λ X Y f,
strong_epi_factor_thru_image_of_strong_epi_mono_factorisation $
classical.choice $ has_strong_epi_mono_factorisations.has_fac f }
end has_strong_epi_images
section has_strong_epi_images
variables [has_images C]
/-- A category with strong epi images has image maps. -/
@[priority 100]
instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] :
has_image_maps C :=
{ has_image_map := λ f g st, has_image_map.mk
{ map := arrow.lift $ arrow.hom_mk' $ show (st.left ≫ factor_thru_image g.hom) ≫ image.ι g.hom =
factor_thru_image f.hom ≫ (image.ι f.hom ≫ st.right), by simp } }
/-- If a category has images, equalizers and pullbacks, then images are automatically strong epi
images. -/
@[priority 100]
instance has_strong_epi_images_of_has_pullbacks_of_has_equalizers [has_pullbacks C]
[has_equalizers C] : has_strong_epi_images C :=
{ strong_factor_thru_image := λ X Y f,
{ epi := by apply_instance,
has_lift := λ A B x y h h_mono w, arrow.has_lift.mk
{ lift := image.lift
{ I := pullback h y,
m := pullback.snd ≫ image.ι f,
m_mono := by exactI mono_comp _ _,
e := pullback.lift _ _ w } ≫ pullback.fst } } }
end has_strong_epi_images
variables [has_strong_epi_mono_factorisations.{v} C]
variables {X Y : C} {f : X ⟶ Y}
/--
If `C` has strong epi mono factorisations, then the image is unique up to isomorphism, in that if
`f` factors as a strong epi followed by a mono, this factorisation is essentially the image
factorisation.
-/
def image.iso_strong_epi_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e]
[mono m] :
I' ≅ image f :=
is_image.iso_ext {strong_epi_mono_factorisation . I := I', m := m, e := e}.to_mono_is_image $
image.is_image f
@[simp]
lemma image.iso_strong_epi_mono_hom_comp_ι {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f)
[strong_epi e] [mono m] :
(image.iso_strong_epi_mono e m comm).hom ≫ image.ι f = m :=
is_image.lift_fac _ _
@[simp]
lemma image.iso_strong_epi_mono_inv_comp_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f)
[strong_epi e] [mono m] :
(image.iso_strong_epi_mono e m comm).inv ≫ m = image.ι f :=
image.lift_fac _
end category_theory.limits
|
7fd206329fbc94235501ffb3efe872eb26d974e6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/measure/stieltjes.lean | cd65059c9a0bc68a17260c8383ac8243c0c4d0fe | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 26,791 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov, Sébastien Gouëzel
-/
import measure_theory.constructions.borel_space.basic
import topology.algebra.order.left_right_lim
/-!
# Stieltjes measures on the real line
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Consider a function `f : ℝ → ℝ` which is monotone and right-continuous. Then one can define a
corrresponding measure, giving mass `f b - f a` to the interval `(a, b]`.
## Main definitions
* `stieltjes_function` is a structure containing a function from `ℝ → ℝ`, together with the
assertions that it is monotone and right-continuous. To `f : stieltjes_function`, one associates
a Borel measure `f.measure`.
* `f.measure_Ioc` asserts that `f.measure (Ioc a b) = of_real (f b - f a)`
* `f.measure_Ioo` asserts that `f.measure (Ioo a b) = of_real (left_lim f b - f a)`.
* `f.measure_Icc` and `f.measure_Ico` are analogous.
-/
section move_this
-- this section contains lemmas that should be moved to appropriate places after the port to lean 4
open filter set
open_locale topology
lemma infi_Ioi_eq_infi_rat_gt {f : ℝ → ℝ} (x : ℝ) (hf : bdd_below (f '' Ioi x))
(hf_mono : monotone f) :
(⨅ r : Ioi x, f r) = ⨅ q : {q' : ℚ // x < q'}, f q :=
begin
refine le_antisymm _ _,
{ haveI : nonempty {r' : ℚ // x < ↑r'},
{ obtain ⟨r, hrx⟩ := exists_rat_gt x,
exact ⟨⟨r, hrx⟩⟩, },
refine le_cinfi (λ r, _),
obtain ⟨y, hxy, hyr⟩ := exists_rat_btwn r.prop,
refine cinfi_set_le hf (hxy.trans _),
exact_mod_cast hyr, },
{ refine le_cinfi (λ q, _),
have hq := q.prop,
rw mem_Ioi at hq,
obtain ⟨y, hxy, hyq⟩ := exists_rat_btwn hq,
refine (cinfi_le _ _).trans _,
{ exact ⟨y, hxy⟩, },
{ refine ⟨hf.some, λ z, _⟩,
rintros ⟨u, rfl⟩,
suffices hfu : f u ∈ f '' Ioi x, from hf.some_spec hfu,
exact ⟨u, u.prop, rfl⟩, },
{ refine hf_mono (le_trans _ hyq.le),
norm_cast, }, },
end
-- todo after the port: move to topology/algebra/order/left_right_lim
lemma right_lim_eq_of_tendsto {α β : Type*} [linear_order α] [topological_space β]
[hα : topological_space α] [h'α : order_topology α] [t2_space β]
{f : α → β} {a : α} {y : β} (h : 𝓝[>] a ≠ ⊥) (h' : tendsto f (𝓝[>] a) (𝓝 y)) :
function.right_lim f a = y :=
@left_lim_eq_of_tendsto αᵒᵈ _ _ _ _ _ _ f a y h h'
-- todo after the port: move to topology/algebra/order/left_right_lim
lemma right_lim_eq_Inf {α β : Type*} [linear_order α] [topological_space β]
[conditionally_complete_linear_order β] [order_topology β] {f : α → β}
(hf : monotone f) {x : α}
[topological_space α] [order_topology α] (h : 𝓝[>] x ≠ ⊥) :
function.right_lim f x = Inf (f '' (Ioi x)) :=
right_lim_eq_of_tendsto h (hf.tendsto_nhds_within_Ioi x)
-- todo after the port: move to order/filter/at_top_bot
lemma exists_seq_monotone_tendsto_at_top_at_top (α : Type*) [semilattice_sup α] [nonempty α]
[(at_top : filter α).is_countably_generated] :
∃ xs : ℕ → α, monotone xs ∧ tendsto xs at_top at_top :=
begin
haveI h_ne_bot : (at_top : filter α).ne_bot := at_top_ne_bot,
obtain ⟨ys, h⟩ := exists_seq_tendsto (at_top : filter α),
let xs : ℕ → α := λ n, finset.sup' (finset.range (n + 1)) finset.nonempty_range_succ ys,
have h_mono : monotone xs,
{ intros i j hij,
rw finset.sup'_le_iff,
intros k hk,
refine finset.le_sup'_of_le _ _ le_rfl,
rw finset.mem_range at hk ⊢,
exact hk.trans_le (add_le_add_right hij _), },
refine ⟨xs, h_mono, _⟩,
{ refine tendsto_at_top_at_top_of_monotone h_mono _,
have : ∀ (a : α), ∃ (n : ℕ), a ≤ ys n,
{ rw tendsto_at_top_at_top at h,
intro a,
obtain ⟨i, hi⟩ := h a,
exact ⟨i, hi i le_rfl⟩, },
intro a,
obtain ⟨i, hi⟩ := this a,
refine ⟨i, hi.trans _⟩,
refine finset.le_sup'_of_le _ _ le_rfl,
rw finset.mem_range_succ_iff, },
end
lemma exists_seq_antitone_tendsto_at_top_at_bot (α : Type*) [semilattice_inf α] [nonempty α]
[h2 : (at_bot : filter α).is_countably_generated] :
∃ xs : ℕ → α, antitone xs ∧ tendsto xs at_top at_bot :=
@exists_seq_monotone_tendsto_at_top_at_top αᵒᵈ _ _ h2
-- todo after the port: move to topology/algebra/order/monotone_convergence
lemma supr_eq_supr_subseq_of_antitone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α]
{l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : antitone f)
(hφ : tendsto φ l at_bot) :
(⨆ i, f i) = (⨆ i, f (φ i)) :=
le_antisymm
(supr_mono' (λ i, exists_imp_exists (λ j (hj : φ j ≤ i), hf hj)
(hφ.eventually $ eventually_le_at_bot i).exists))
(supr_mono' (λ i, ⟨φ i, le_rfl⟩))
namespace measure_theory
-- todo after the port: move these lemmas to measure_theory/measure/measure_space?
variables {α : Type*} {mα : measurable_space α}
include mα
lemma tendsto_measure_Ico_at_top [semilattice_sup α] [no_max_order α]
[(at_top : filter α).is_countably_generated] (μ : measure α) (a : α) :
tendsto (λ x, μ (Ico a x)) at_top (𝓝 (μ (Ici a))) :=
begin
haveI : nonempty α := ⟨a⟩,
have h_mono : monotone (λ x, μ (Ico a x)) := λ i j hij, measure_mono (Ico_subset_Ico_right hij),
convert tendsto_at_top_supr h_mono,
obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_monotone_tendsto_at_top_at_top α,
have h_Ici : Ici a = ⋃ n, Ico a (xs n),
{ ext1 x,
simp only [mem_Ici, mem_Union, mem_Ico, exists_and_distrib_left, iff_self_and],
intro _,
obtain ⟨y, hxy⟩ := no_max_order.exists_gt x,
obtain ⟨n, hn⟩ := tendsto_at_top_at_top.mp hxs_tendsto y,
exact ⟨n, hxy.trans_le (hn n le_rfl)⟩, },
rw [h_Ici, measure_Union_eq_supr, supr_eq_supr_subseq_of_monotone h_mono hxs_tendsto],
exact monotone.directed_le (λ i j hij, Ico_subset_Ico_right (hxs_mono hij)),
end
lemma tendsto_measure_Ioc_at_bot [semilattice_inf α] [no_min_order α]
[(at_bot : filter α).is_countably_generated] (μ : measure α) (a : α) :
tendsto (λ x, μ (Ioc x a)) at_bot (𝓝 (μ (Iic a))) :=
begin
haveI : nonempty α := ⟨a⟩,
have h_mono : antitone (λ x, μ (Ioc x a)) := λ i j hij, measure_mono (Ioc_subset_Ioc_left hij),
convert tendsto_at_bot_supr h_mono,
obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_antitone_tendsto_at_top_at_bot α,
have h_Iic : Iic a = ⋃ n, Ioc (xs n) a,
{ ext1 x,
simp only [mem_Iic, mem_Union, mem_Ioc, exists_and_distrib_right, iff_and_self],
intro _,
obtain ⟨y, hxy⟩ := no_min_order.exists_lt x,
obtain ⟨n, hn⟩ := tendsto_at_top_at_bot.mp hxs_tendsto y,
exact ⟨n, (hn n le_rfl).trans_lt hxy⟩, },
rw [h_Iic, measure_Union_eq_supr, supr_eq_supr_subseq_of_antitone h_mono hxs_tendsto],
exact monotone.directed_le (λ i j hij, Ioc_subset_Ioc_left (hxs_mono hij)),
end
lemma tendsto_measure_Iic_at_top [semilattice_sup α] [(at_top : filter α).is_countably_generated]
(μ : measure α) :
tendsto (λ x, μ (Iic x)) at_top (𝓝 (μ univ)) :=
begin
casesI is_empty_or_nonempty α,
{ have h1 : ∀ x : α, Iic x = ∅ := λ x, subsingleton.elim _ _,
have h2 : (univ : set α) = ∅ := subsingleton.elim _ _,
simp_rw [h1, h2],
exact tendsto_const_nhds, },
have h_mono : monotone (λ x, μ (Iic x)) := λ i j hij, measure_mono (Iic_subset_Iic.mpr hij),
convert tendsto_at_top_supr h_mono,
obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_monotone_tendsto_at_top_at_top α,
have h_univ : (univ : set α) = ⋃ n, Iic (xs n),
{ ext1 x,
simp only [mem_univ, mem_Union, mem_Iic, true_iff],
obtain ⟨n, hn⟩ := tendsto_at_top_at_top.mp hxs_tendsto x,
exact ⟨n, hn n le_rfl⟩, },
rw [h_univ, measure_Union_eq_supr, supr_eq_supr_subseq_of_monotone h_mono hxs_tendsto],
exact monotone.directed_le (λ i j hij, Iic_subset_Iic.mpr (hxs_mono hij)),
end
lemma tendsto_measure_Ici_at_bot [semilattice_inf α]
[h : (at_bot : filter α).is_countably_generated] (μ : measure α) :
tendsto (λ x, μ (Ici x)) at_bot (𝓝 (μ univ)) :=
@tendsto_measure_Iic_at_top αᵒᵈ _ _ h μ
end measure_theory
end move_this
noncomputable theory
open classical set filter function
open ennreal (of_real)
open_locale big_operators ennreal nnreal topology measure_theory
/-! ### Basic properties of Stieltjes functions -/
/-- Bundled monotone right-continuous real functions, used to construct Stieltjes measures. -/
structure stieltjes_function :=
(to_fun : ℝ → ℝ)
(mono' : monotone to_fun)
(right_continuous' : ∀ x, continuous_within_at to_fun (Ici x) x)
namespace stieltjes_function
instance : has_coe_to_fun stieltjes_function (λ _, ℝ → ℝ) := ⟨to_fun⟩
initialize_simps_projections stieltjes_function (to_fun → apply)
variable (f : stieltjes_function)
lemma mono : monotone f := f.mono'
lemma right_continuous (x : ℝ) : continuous_within_at f (Ici x) x := f.right_continuous' x
lemma right_lim_eq (f : stieltjes_function) (x : ℝ) :
function.right_lim f x = f x :=
begin
rw [← f.mono.continuous_within_at_Ioi_iff_right_lim_eq, continuous_within_at_Ioi_iff_Ici],
exact f.right_continuous' x,
end
lemma infi_Ioi_eq (f : stieltjes_function) (x : ℝ) :
(⨅ r : Ioi x, f r) = f x :=
begin
suffices : function.right_lim f x = ⨅ r : Ioi x, f r,
{ rw [← this, f.right_lim_eq], },
rw [right_lim_eq_Inf f.mono, Inf_image'],
rw ← ne_bot_iff,
apply_instance,
end
lemma infi_rat_gt_eq (f : stieltjes_function) (x : ℝ) :
(⨅ r : {r' : ℚ // x < r'}, f r) = f x :=
begin
rw ← infi_Ioi_eq f x,
refine (infi_Ioi_eq_infi_rat_gt _ _ f.mono).symm,
refine ⟨f x, λ y, _⟩,
rintros ⟨y, hy_mem, rfl⟩,
exact f.mono (le_of_lt hy_mem),
end
/-- The identity of `ℝ` as a Stieltjes function, used to construct Lebesgue measure. -/
@[simps] protected def id : stieltjes_function :=
{ to_fun := id,
mono' := λ x y, id,
right_continuous' := λ x, continuous_within_at_id }
@[simp] lemma id_left_lim (x : ℝ) : left_lim stieltjes_function.id x = x :=
tendsto_nhds_unique (stieltjes_function.id.mono.tendsto_left_lim x) $
(continuous_at_id).tendsto.mono_left nhds_within_le_nhds
instance : inhabited stieltjes_function := ⟨stieltjes_function.id⟩
/-- If a function `f : ℝ → ℝ` is monotone, then the function mapping `x` to the right limit of `f`
at `x` is a Stieltjes function, i.e., it is monotone and right-continuous. -/
noncomputable def _root_.monotone.stieltjes_function {f : ℝ → ℝ} (hf : monotone f) :
stieltjes_function :=
{ to_fun := right_lim f,
mono' := λ x y hxy, hf.right_lim hxy,
right_continuous' :=
begin
assume x s hs,
obtain ⟨l, u, hlu, lus⟩ : ∃ (l u : ℝ), right_lim f x ∈ Ioo l u ∧ Ioo l u ⊆ s :=
mem_nhds_iff_exists_Ioo_subset.1 hs,
obtain ⟨y, xy, h'y⟩ : ∃ (y : ℝ) (H : x < y), Ioc x y ⊆ f ⁻¹' (Ioo l u) :=
mem_nhds_within_Ioi_iff_exists_Ioc_subset.1
(hf.tendsto_right_lim x (Ioo_mem_nhds hlu.1 hlu.2)),
change ∀ᶠ y in 𝓝[≥] x, right_lim f y ∈ s,
filter_upwards [Ico_mem_nhds_within_Ici ⟨le_refl x, xy⟩] with z hz,
apply lus,
refine ⟨hlu.1.trans_le (hf.right_lim hz.1), _⟩,
obtain ⟨a, za, ay⟩ : ∃ (a : ℝ), z < a ∧ a < y := exists_between hz.2,
calc right_lim f z ≤ f a : hf.right_lim_le za
... < u : (h'y ⟨hz.1.trans_lt za, ay.le⟩).2,
end }
lemma _root_.monotone.stieltjes_function_eq {f : ℝ → ℝ} (hf : monotone f) (x : ℝ) :
hf.stieltjes_function x = right_lim f x := rfl
lemma countable_left_lim_ne (f : stieltjes_function) :
set.countable {x | left_lim f x ≠ f x} :=
begin
apply countable.mono _ (f.mono.countable_not_continuous_at),
assume x hx h'x,
apply hx,
exact tendsto_nhds_unique (f.mono.tendsto_left_lim x) (h'x.tendsto.mono_left nhds_within_le_nhds),
end
/-! ### The outer measure associated to a Stieltjes function -/
/-- Length of an interval. This is the largest monotone function which correctly measures all
intervals. -/
def length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ioc a b), of_real (f b - f a)
@[simp] lemma length_empty : f.length ∅ = 0 :=
nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma length_Ioc (a b : ℝ) :
f.length (Ioc a b) = of_real (f b - f a) :=
begin
refine le_antisymm (infi_le_of_le a $ infi₂_le b subset.rfl)
(le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw real.to_nnreal_of_nonpos (sub_nonpos.2 (f.mono ab)), apply zero_le, },
cases (Ioc_subset_Ioc_iff ab).1 h with h₁ h₂,
exact real.to_nnreal_le_to_nnreal (sub_le_sub (f.mono h₁) (f.mono h₂))
end
lemma length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : f.length s₁ ≤ f.length s₂ :=
infi_mono $ λ a, binfi_mono $ λ b, h.trans
open measure_theory
/-- The Stieltjes outer measure associated to a Stieltjes function. -/
protected def outer : outer_measure ℝ :=
outer_measure.of_function f.length f.length_empty
lemma outer_le_length (s : set ℝ) : f.outer s ≤ f.length s :=
outer_measure.of_function_le _
/-- If a compact interval `[a, b]` is covered by a union of open interval `(c i, d i)`, then
`f b - f a ≤ ∑ f (d i) - f (c i)`. This is an auxiliary technical statement to prove the same
statement for half-open intervals, the point of the current statement being that one can use
compactness to reduce it to a finite sum, and argue by induction on the size of the covering set. -/
lemma length_subadditive_Icc_Ioo {a b : ℝ} {c d : ℕ → ℝ}
(ss : Icc a b ⊆ ⋃ i, Ioo (c i) (d i)) :
of_real (f b - f a) ≤ ∑' i, of_real (f (d i) - f (c i)) :=
begin
suffices : ∀ (s:finset ℕ) b
(cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)),
(of_real (f b - f a) : ℝ≥0∞) ≤ ∑ i in s, of_real (f (d i) - f (c i)),
{ rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩,
have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)),
by simp only [ext_iff, exists_prop, finset.set_bUnion_coe, mem_Union, forall_const, iff_self,
finite.mem_to_finset],
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa only [e]) },
clear ss b,
refine λ s, finset.strong_induction_on s (λ s IH b cv, _),
cases le_total b a with ab ab,
{ rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 (f.mono ab)), exact zero_le _, },
have := cv ⟨ab, le_rfl⟩, simp at this,
rcases this with ⟨i, is, cb, bd⟩,
rw [← finset.insert_erase is] at cv ⊢,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _),
{ refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (f.mono bd.le) _ },
{ rintro x ⟨h₁, h₂⟩,
refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left
(mt and.left (not_lt_of_le h₂)) }
end
@[simp] lemma outer_Ioc (a b : ℝ) :
f.outer (Ioc a b) = of_real (f b - f a) :=
begin
/- It suffices to show that, if `(a, b]` is covered by sets `s i`, then `f b - f a` is bounded
by `∑ f.length (s i) + ε`. The difficulty is that `f.length` is expressed in terms of half-open
intervals, while we would like to have a compact interval covered by open intervals to use
compactness and finite sums, as provided by `length_subadditive_Icc_Ioo`. The trick is to use the
right-continuity of `f`. If `a'` is close enough to `a` on its right, then `[a', b]` is still
covered by the sets `s i` and moreover `f b - f a'` is very close to `f b - f a` (up to `ε/2`).
Also, by definition one can cover `s i` by a half-closed interval `(p i, q i]` with `f`-length
very close to that of `s i` (within a suitably small `ε' i`, say). If one moves `q i` very
slightly to the right, then the `f`-length will change very little by right continuity, and we
will get an open interval `(p i, q' i)` covering `s i` with `f (q' i) - f (p i)` within `ε' i`
of the `f`-length of `s i`. -/
refine le_antisymm (by { rw ← f.length_Ioc, apply outer_le_length })
(le_infi₂ $ λ s hs, ennreal.le_of_forall_pos_le_add $ λ ε εpos h, _),
let δ := ε / 2,
have δpos : 0 < (δ : ℝ≥0∞), by simpa using εpos.ne',
rcases ennreal.exists_pos_sum_of_countable δpos.ne' ℕ with ⟨ε', ε'0, hε⟩,
obtain ⟨a', ha', aa'⟩ : ∃ a', f a' - f a < δ ∧ a < a',
{ have A : continuous_within_at (λ r, f r - f a) (Ioi a) a,
{ refine continuous_within_at.sub _ continuous_within_at_const,
exact (f.right_continuous a).mono Ioi_subset_Ici_self },
have B : f a - f a < δ, by rwa [sub_self, nnreal.coe_pos, ← ennreal.coe_pos],
exact (((tendsto_order.1 A).2 _ B).and self_mem_nhds_within).exists },
have : ∀ i, ∃ p:ℝ×ℝ, s i ⊆ Ioo p.1 p.2 ∧
(of_real (f p.2 - f p.1) : ℝ≥0∞) < f.length (s i) + ε' i,
{ intro i,
have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne
(ennreal.coe_ne_zero.2 (ε'0 i).ne')),
conv at this { to_lhs, rw length },
simp only [infi_lt_iff, exists_prop] at this,
rcases this with ⟨p, q', spq, hq'⟩,
have : continuous_within_at (λ r, of_real (f r - f p)) (Ioi q') q',
{ apply ennreal.continuous_of_real.continuous_at.comp_continuous_within_at,
refine continuous_within_at.sub _ continuous_within_at_const,
exact (f.right_continuous q').mono Ioi_subset_Ici_self },
rcases (((tendsto_order.1 this).2 _ hq').and self_mem_nhds_within).exists with ⟨q, hq, q'q⟩,
exact ⟨⟨p, q⟩, spq.trans (Ioc_subset_Ioo_right q'q), hq⟩ },
choose g hg using this,
have I_subset : Icc a' b ⊆ ⋃ i, Ioo (g i).1 (g i).2 := calc
Icc a' b ⊆ Ioc a b : λ x hx, ⟨aa'.trans_le hx.1, hx.2⟩
... ⊆ ⋃ i, s i : hs
... ⊆ ⋃ i, Ioo (g i).1 (g i).2 : Union_mono (λ i, (hg i).1),
calc of_real (f b - f a)
= of_real ((f b - f a') + (f a' - f a)) : by rw sub_add_sub_cancel
... ≤ of_real (f b - f a') + of_real (f a' - f a) : ennreal.of_real_add_le
... ≤ (∑' i, of_real (f (g i).2 - f (g i).1)) + of_real δ :
add_le_add (f.length_subadditive_Icc_Ioo I_subset) (ennreal.of_real_le_of_real ha'.le)
... ≤ (∑' i, (f.length (s i) + ε' i)) + δ :
add_le_add (ennreal.tsum_le_tsum (λ i, (hg i).2.le))
(by simp only [ennreal.of_real_coe_nnreal, le_rfl])
... = (∑' i, f.length (s i)) + (∑' i, ε' i) + δ : by rw [ennreal.tsum_add]
... ≤ (∑' i, f.length (s i)) + δ + δ : add_le_add (add_le_add le_rfl hε.le) le_rfl
... = ∑' (i : ℕ), f.length (s i) + ε : by simp [add_assoc, ennreal.add_halves]
end
lemma measurable_set_Ioi {c : ℝ} :
measurable_set[f.outer.caratheodory] (Ioi c) :=
begin
apply outer_measure.of_function_caratheodory (λ t, _),
refine le_infi (λ a, le_infi (λ b, le_infi (λ h, _))),
refine le_trans (add_le_add
(f.length_mono $ inter_subset_inter_left _ h)
(f.length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hac; cases le_total b c with hbc hbc,
{ simp only [Ioc_inter_Ioi, f.length_Ioc, hac, sup_eq_max, hbc, le_refl, Ioc_eq_empty,
max_eq_right, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, not_lt] },
{ simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right,
sup_eq_max, ←ennreal.of_real_add, f.mono hac, f.mono hbc, sub_nonneg, sub_add_sub_cancel,
le_refl, max_eq_right] },
{ simp only [hbc, le_refl, Ioc_eq_empty, Ioc_inter_Ioi, min_eq_left, Ioc_diff_Ioi,
f.length_empty, zero_add, or_true, le_sup_iff, f.length_Ioc, not_lt] },
{ simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right,
sup_eq_max, le_refl, Ioc_eq_empty, add_zero, max_eq_left, f.length_empty, not_lt] }
end
theorem outer_trim : f.outer.trim = f.outer :=
begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
refine le_infi (λ t, le_infi $ λ ht,
ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_countable
(ennreal.coe_pos.2 ε0).ne' ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ s, t i ⊆ s ∧ measurable_set s ∧
f.outer s ≤ f.length (t i) + of_real (ε' i),
{ intro i,
have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne
(ennreal.coe_pos.2 (ε'0 i)).ne'),
conv at this {to_lhs, rw length},
simp only [infi_lt_iff] at this,
rcases this with ⟨a, b, h₁, h₂⟩,
rw ← f.outer_Ioc at h₂,
exact ⟨_, h₁, measurable_set_Ioc, le_of_lt $ by simpa using h₂⟩ },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (ht.trans $ Union_mono (λ i, (hg i).1)) _,
apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _,
exact le_trans (f.outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2)
end
lemma borel_le_measurable : borel ℝ ≤ f.outer.caratheodory :=
begin
rw borel_eq_generate_from_Ioi,
refine measurable_space.generate_from_le _,
simp [f.measurable_set_Ioi] { contextual := tt }
end
/-! ### The measure associated to a Stieltjes function -/
/-- The measure associated to a Stieltjes function, giving mass `f b - f a` to the
interval `(a, b]`. -/
@[irreducible] protected def measure : measure ℝ :=
{ to_outer_measure := f.outer,
m_Union := λ s hs, f.outer.Union_eq_of_caratheodory $
λ i, f.borel_le_measurable _ (hs i),
trimmed := f.outer_trim }
@[simp] lemma measure_Ioc (a b : ℝ) : f.measure (Ioc a b) = of_real (f b - f a) :=
by { rw stieltjes_function.measure, exact f.outer_Ioc a b }
@[simp] lemma measure_singleton (a : ℝ) : f.measure {a} = of_real (f a - left_lim f a) :=
begin
obtain ⟨u, u_mono, u_lt_a, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_mono u ∧ (∀ (n : ℕ), u n < a)
∧ tendsto u at_top (𝓝 a) := exists_seq_strict_mono_tendsto a,
have A : {a} = ⋂ n, Ioc (u n) a,
{ refine subset.antisymm (λ x hx, by simp [mem_singleton_iff.1 hx, u_lt_a]) (λ x hx, _),
simp at hx,
have : a ≤ x := le_of_tendsto' u_lim (λ n, (hx n).1.le),
simp [le_antisymm this (hx 0).2] },
have L1 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (f.measure {a})),
{ rw A,
refine tendsto_measure_Inter (λ n, measurable_set_Ioc) (λ m n hmn, _) _,
{ exact Ioc_subset_Ioc (u_mono.monotone hmn) le_rfl },
{ exact ⟨0, by simpa only [measure_Ioc] using ennreal.of_real_ne_top⟩ } },
have L2 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (of_real (f a - left_lim f a))),
{ simp only [measure_Ioc],
have : tendsto (λ n, f (u n)) at_top (𝓝 (left_lim f a)),
{ apply (f.mono.tendsto_left_lim a).comp,
exact tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ u_lim
(eventually_of_forall (λ n, u_lt_a n)) },
exact ennreal.continuous_of_real.continuous_at.tendsto.comp (tendsto_const_nhds.sub this) },
exact tendsto_nhds_unique L1 L2
end
@[simp] lemma measure_Icc (a b : ℝ) : f.measure (Icc a b) = of_real (f b - left_lim f a) :=
begin
rcases le_or_lt a b with hab|hab,
{ have A : disjoint {a} (Ioc a b), by simp,
simp [← Icc_union_Ioc_eq_Icc le_rfl hab, -singleton_union, ← ennreal.of_real_add,
f.mono.left_lim_le, measure_union A measurable_set_Ioc, f.mono hab] },
{ simp only [hab, measure_empty, Icc_eq_empty, not_le],
symmetry,
simp [ennreal.of_real_eq_zero, f.mono.le_left_lim hab] }
end
@[simp] lemma measure_Ioo {a b : ℝ} : f.measure (Ioo a b) = of_real (left_lim f b - f a) :=
begin
rcases le_or_lt b a with hab|hab,
{ simp only [hab, measure_empty, Ioo_eq_empty, not_lt],
symmetry,
simp [ennreal.of_real_eq_zero, f.mono.left_lim_le hab] },
{ have A : disjoint (Ioo a b) {b}, by simp,
have D : f b - f a = (f b - left_lim f b) + (left_lim f b - f a), by abel,
have := f.measure_Ioc a b,
simp only [←Ioo_union_Icc_eq_Ioc hab le_rfl, measure_singleton,
measure_union A (measurable_set_singleton b), Icc_self] at this,
rw [D, ennreal.of_real_add, add_comm] at this,
{ simpa only [ennreal.add_right_inj ennreal.of_real_ne_top] },
{ simp only [f.mono.left_lim_le, sub_nonneg] },
{ simp only [f.mono.le_left_lim hab, sub_nonneg] } },
end
@[simp] lemma measure_Ico (a b : ℝ) : f.measure (Ico a b) = of_real (left_lim f b - left_lim f a) :=
begin
rcases le_or_lt b a with hab|hab,
{ simp only [hab, measure_empty, Ico_eq_empty, not_lt],
symmetry,
simp [ennreal.of_real_eq_zero, f.mono.left_lim hab] },
{ have A : disjoint {a} (Ioo a b) := by simp,
simp [← Icc_union_Ioo_eq_Ico le_rfl hab, -singleton_union, hab.ne, f.mono.left_lim_le,
measure_union A measurable_set_Ioo, f.mono.le_left_lim hab, ← ennreal.of_real_add] }
end
lemma measure_Iic {l : ℝ} (hf : tendsto f at_bot (𝓝 l)) (x : ℝ) :
f.measure (Iic x) = of_real (f x - l) :=
begin
refine tendsto_nhds_unique (tendsto_measure_Ioc_at_bot _ _) _,
simp_rw measure_Ioc,
exact ennreal.tendsto_of_real (tendsto.const_sub _ hf),
end
lemma measure_Ici {l : ℝ} (hf : tendsto f at_top (𝓝 l)) (x : ℝ) :
f.measure (Ici x) = of_real (l - left_lim f x) :=
begin
refine tendsto_nhds_unique (tendsto_measure_Ico_at_top _ _) _,
simp_rw measure_Ico,
refine ennreal.tendsto_of_real (tendsto.sub_const _ _),
have h_le1 : ∀ x, f (x - 1) ≤ left_lim f x := λ x, monotone.le_left_lim f.mono (sub_one_lt x),
have h_le2 : ∀ x, left_lim f x ≤ f x := λ x, monotone.left_lim_le f.mono le_rfl,
refine tendsto_of_tendsto_of_tendsto_of_le_of_le (hf.comp _) hf h_le1 h_le2,
rw tendsto_at_top_at_top,
exact λ y, ⟨y + 1, λ z hyz, by rwa le_sub_iff_add_le⟩,
end
lemma measure_univ {l u : ℝ} (hfl : tendsto f at_bot (𝓝 l)) (hfu : tendsto f at_top (𝓝 u)) :
f.measure univ = of_real (u - l) :=
begin
refine tendsto_nhds_unique (tendsto_measure_Iic_at_top _) _,
simp_rw measure_Iic f hfl,
exact ennreal.tendsto_of_real (tendsto.sub_const hfu _),
end
instance : is_locally_finite_measure f.measure :=
⟨λ x, ⟨Ioo (x-1) (x+1), Ioo_mem_nhds (by linarith) (by linarith), by simp⟩⟩
end stieltjes_function
|
32b673260103be17e88a0263da8387d701601722 | 85485c410781936e7dd6aba0ba77b8a82f76c1d6 | /src/localization.lean | 81d996a1edd2c0b1b1a3bb5f77dd17bee11f3689 | [] | no_license | yuma-mizuno/lean-cluster-algebra | 5b33657b3cf27c24cab292d4ac62d6e1e5e715b9 | 4a4fb128566305eda2b82aea068157cb43afdf18 | refs/heads/master | 1,689,542,026,900 | 1,630,963,668,000 | 1,630,964,456,000 | 392,828,775 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,484 | lean | import ring_theory.localization
/-!
This file proves some properties on localizations that are needed to define mutations.
## Main statements
* `is_localization_of_lift_of_sup`: let `A`, `B`, and `C` are commutative rings, and `M` and `N`
are submonoids of `A`. Suppose that `B` is a localization of `A` at `M` and `C` is a localization
of `A` at `M ⊔ N`. Then `C` is a localization of `B` at the image of `N` by the localization map
from `A` to `B`.
-/
namespace is_localization
section
variables
{A : Type*} [comm_ring A]
(M N : submonoid A)
(B : Type*) [comm_ring B] (C : Type*) [comm_ring C]
[algebra A B] [algebra A C]
[is_localization M B] [is_localization (M ⊔ N) C]
include M N
noncomputable def lift_of_sup : B →+* C :=
lift $ λ h, by simpa only [set_like.coe_mk] using map_units C (⟨h.1, set_like.le_def.mp le_sup_left h.2⟩ : M ⊔ N)
noncomputable def algebra_of_lift_of_sup : algebra B C := ring_hom.to_algebra (lift_of_sup M N B C)
local attribute[instance] algebra_of_lift_of_sup
lemma eq_comp_map_of_lift_of_sup (a : A) : algebra_map A C a = (algebra_map B C (algebra_map A B a)):=
begin
have : algebra_map B C = lift_of_sup M N B C := by refl,
rw [this, lift_of_sup, lift_eq],
end
lemma eq_comp_of_lift_of_sup : (algebra_map A C) = (algebra_map B C).comp (algebra_map A B) :=
by ext; by rw [ring_hom.coe_comp]; by exact eq_comp_map_of_lift_of_sup M N B C _
lemma is_localization_of_lift_of_sup
{A : Type*} [comm_ring A]
(M : submonoid A) (N : submonoid A)
(B : Type*) [comm_ring B] (C : Type*) [comm_ring C]
[algebra A B] [algebra A C]
[is_localization M B] [is_localization (M ⊔ N) C] :
is_localization (N.map (algebra_map A B) : submonoid B) C :=
{ map_units :=
begin
intros n',
rcases submonoid.mem_map.mp n'.property with ⟨n, ⟨hn, H⟩⟩,
have : n ∈ M ⊔ N := set_like.le_def.mp le_sup_right hn,
simp only [ring_hom.coe_monoid_hom, subtype.val_eq_coe] at H,
rw [<- H, <- eq_comp_map_of_lift_of_sup],
exact is_localization.map_units C ⟨n, this⟩,
end,
surj :=
begin
intros c,
rcases surj (M ⊔ N) c with ⟨⟨a, ⟨mn, h_mn⟩⟩ , H⟩,
rcases submonoid.mem_sup.mp h_mn with ⟨m, hm, n, hn, H'⟩,
repeat {rw eq_comp_map_of_lift_of_sup M N B C at H},
rw [set_like.coe_mk] at H,
dsimp at H,
have : algebra_map A B n ∈ (N.map (algebra_map A B) : submonoid B),
apply submonoid.mem_map.mpr,
use n,
use hn,
rw [ring_hom.coe_monoid_hom],
fsplit,
fsplit,
exact ↑((is_unit.unit (map_units B ⟨m, hm⟩))⁻¹) * (algebra_map A B a),
exact ⟨algebra_map A B n, this⟩,
simp only [set_like.coe_mk, ring_hom.map_mul],
rw [<- H, <- H'],
simp only [ring_hom.map_mul],
ring_nf,
apply congr_arg ( * c),
nth_rewrite 0 <- one_mul ((algebra_map B C) ((algebra_map A B) n)),
apply congr_arg ( * ((algebra_map B C) ((algebra_map A B) n))),
rw <- ring_hom.map_mul,
rw <- ring_hom.map_one (algebra_map B C),
apply congr_arg,
rw units.mul_inv_of_eq,
rw is_unit.unit_spec,
end,
eq_iff_exists :=
begin
intros b₁ b₂,
split,
{ intros h,
rcases surj M b₁ with ⟨⟨a₁, ⟨m₁, hm₁⟩⟩, H₁⟩,
rcases surj M b₂ with ⟨⟨a₂, ⟨m₂, hm₂⟩⟩, H₂⟩,
have : algebra_map A C (a₁ * m₂) = algebra_map A C (a₂ * m₁),
rw eq_comp_map_of_lift_of_sup M N B C,
rw eq_comp_map_of_lift_of_sup M N B C,
dsimp at *,
simp only [ring_hom.map_mul],
rw [<- H₁, <- H₂],
simp only [ring_hom.map_mul],
rw h,
ring,
rcases (eq_iff_exists (M ⊔ N) C).mp this with ⟨⟨mn, mn_in⟩, hmn⟩,
rcases submonoid.mem_sup.mp mn_in with ⟨m, hm, n, hn, H'⟩,
dsimp at *,
have : algebra_map A B n ∈ submonoid.map ↑(algebra_map A B) N,
apply submonoid.mem_map.mpr,
use n,
use hn,
rw [ring_hom.coe_monoid_hom],
use ⟨algebra_map A B n, this⟩,
dsimp,
refine (is_unit.mul_left_inj _).mp _,
exact algebra_map A B m,
exact map_units B ⟨m, hm⟩,
repeat {rw [mul_assoc, <- ring_hom.map_mul]},
rw mul_comm at H',
rw H',
have hb₁ : b₁ = mk' B a₁ ⟨m₁, hm₁⟩ := eq_mk'_iff_mul_eq.mpr H₁,
have hb₂ : b₂ = mk' B a₂ ⟨m₂, hm₂⟩ := eq_mk'_iff_mul_eq.mpr H₂,
rw [hb₁, hb₂],
nth_rewrite_lhs 0 mul_comm,
nth_rewrite_rhs 0 mul_comm,
rw [mul_mk'_eq_mk'_of_mul, mul_mk'_eq_mk'_of_mul],
refine mk'_eq_of_eq _,
dsimp,
exact calc mn * a₂ * m₁ = a₂ * m₁ * mn : by ring
... = a₁ * m₂ * mn : by rw <-hmn
... = mn * a₁ * m₂ : by ring },
{ intros h,
rcases h with ⟨⟨n', hn'⟩, H⟩,
rcases submonoid.mem_map.mp hn' with ⟨n, ⟨hn, H'⟩⟩,
have n_in : n ∈ M ⊔ N := submonoid.mem_sup_right hn,
rcases surj M b₁ with ⟨⟨a₁, ⟨m₁, hm₁⟩⟩, H₁⟩,
rcases surj M b₂ with ⟨⟨a₂, ⟨m₂, hm₂⟩⟩, H₂⟩,
dsimp at *,
have : ∃ m : M, a₁ * m₂ * n * m = a₂ * m₁ * n * m,
refine (eq_iff_exists M B).mp _,
simp only [ring_hom.map_mul],
rw H',
rw [<- H₁, <- H₂],
exact calc b₁ * (algebra_map A B) m₁ * (algebra_map A B) m₂ * n'
= b₁ * n' * (algebra_map A B) m₁ * (algebra_map A B) m₂ : by ring
... = b₂ * n' * (algebra_map A B) m₁ * (algebra_map A B) m₂ : by rw H
... = b₂ * (algebra_map A B) m₂ * (algebra_map A B) m₁ * n' : by ring,
rcases this with ⟨⟨m, hm⟩, H''⟩,
dsimp at H'',
have p : algebra_map A C (a₁ * m₂) = algebra_map A C (a₂ * m₁),
refine (eq_iff_exists (M ⊔ N) C).mpr _,
use ⟨n * m, mul_comm m n ▸ submonoid.mul_mem _ (submonoid.mem_sup_left hm) (submonoid.mem_sup_right hn)⟩,
dsimp,
repeat {rw <- mul_assoc},
exact H'',
repeat {rw eq_comp_map_of_lift_of_sup M N B C at p},
simp only [ring_hom.map_mul] at p,
rw [<- H₁, <- H₂] at p,
refine (is_unit.mul_left_inj _).mp _,
exact algebra_map A C (m₁ * m₂),
have : m₁ * m₂ ∈ M ⊔ N,
refine submonoid.mul_mem _ (submonoid.mem_sup_left hm₁) (submonoid.mem_sup_left hm₂),
exact map_units C ⟨m₁ * m₂, this⟩,
repeat {rw eq_comp_map_of_lift_of_sup M N B C},
simp only [ring_hom.map_mul] at *,
repeat {rw mul_assoc at *},
nth_rewrite 3 mul_comm,
exact p }
end, }
end
section
variables
{A : Type*} [comm_ring A]
{M : submonoid A} {N : submonoid A}
(B : Type*) [comm_ring B] (C : Type*) [comm_ring C]
[algebra A B] [algebra A C]
[is_localization M B] [is_localization N C]
(h : M ≤ N)
include h
noncomputable def lift_of_le : B →+* C :=
@lift_of_sup A _ M N B _ C _ _ _ _ (by rw sup_eq_right.mpr h; by apply_instance)
noncomputable def algebra_of_lift_of_le : algebra B C :=
ring_hom.to_algebra (lift_of_le B C h)
lemma eq_comp_map_of_lift_of_le (a : A) :
algebra_map A C a = @algebra_map B C _ _ (algebra_of_lift_of_le B C h) (algebra_map A B a) :=
begin
have : @algebra_map B C _ _ (algebra_of_lift_of_le B C h) = lift_of_le B C h := by refl,
rw this,
dunfold lift_of_le lift_of_sup,
rw lift_eq,
end
def is_localization_of_lift_of_le (h : M ≤ N) :
@is_localization _ _ (N.map (algebra_map A B) : submonoid B) C _ (algebra_of_lift_of_le B C h) :=
@is_localization_of_lift_of_sup A _ M N B _ C _ _ _ _ (by rw sup_eq_right.mpr h; apply_instance)
end
section
variables
{A : Type*} [comm_ring A] {M N : submonoid A}
(B : Type*) [comm_ring B]
[algebra A B] [is_localization M B]
lemma is_localization_of_le_of_exists_mul_mem (h_le : M ≤ N) (h : ∀ n : N, ∃ a : A, ↑n * a ∈ M) :
is_localization N B :=
begin
split,
{ rintros ⟨n, hn⟩,
rcases h ⟨n, hn⟩ with ⟨a, hm⟩,
let p := map_units B ⟨n * a, hm⟩,
simp only [set_like.coe_mk, is_unit.mul_iff, ring_hom.map_mul] at p,
exact p.left },
{ intros b,
rcases surj M b with ⟨⟨a, ⟨m, hm⟩⟩, H⟩,
use ⟨a, ⟨m, set_like.le_def.mp h_le hm⟩⟩,
exact H },
{ intros a₁ a₂,
split,
intros ha,
rcases (eq_iff_exists M B).mp ha with ⟨⟨m, hm⟩, H⟩,
use ⟨m, set_like.le_def.mp h_le hm⟩,
exact H,
rintros ⟨⟨n, hn⟩, H⟩,
rcases h ⟨n, hn⟩ with ⟨a, hm⟩,
apply (eq_iff_exists M B).mpr _,
use ⟨n * a, hm⟩,
rw [set_like.coe_mk, <-mul_assoc, <-mul_assoc],
congr' 1 }
end
end
section
variables {A : Type*} [integral_domain A] {f : A} (h_ne : f ≠ 0)
(B : Type*) [integral_domain B] (C : Type*) [integral_domain C]
[algebra A B] [algebra A C]
[is_localization.away f B] [is_fraction_ring A C]
--local attribute[instance] algebra_of_lift_of_le
include f h_ne
noncomputable def lift_of_away_frac : B →+* C :=
lift_of_le B C (powers_le_non_zero_divisors_of_no_zero_divisors h_ne)
noncomputable def algebra_of_away_frac : algebra B C :=
ring_hom.to_algebra (lift_of_away_frac h_ne B C)
--local attribute [instance] algebra_of_away_frac
lemma eq_comp_map_of_lift_of_of_away_frac (a : A) : algebra_map A C a =
@algebra_map B C _ _ (algebra_of_away_frac h_ne B C) (algebra_map A B a) :=
begin
have : @algebra_map B C _ _ (algebra_of_away_frac h_ne B C) = lift_of_away_frac h_ne B C := by refl,
rw this,
dunfold lift_of_away_frac lift_of_le lift_of_sup,
rw lift_eq,
end
def is_localization_of_away :
@is_localization B _ ((non_zero_divisors A).map (algebra_map A B) : submonoid B) C _
(algebra_of_lift_of_le B C
(powers_le_non_zero_divisors_of_no_zero_divisors h_ne)) :=
is_localization_of_lift_of_le B C _
lemma non_zero_map_le_non_zero :
((non_zero_divisors A).map (algebra_map A B) : submonoid B) ≤ non_zero_divisors B :=
begin
rintros x ⟨a, ⟨ha, H⟩⟩,
rw <- H,
refine ring_hom.map_mem_non_zero_divisors _ _ ha,
refine is_localization.injective B (powers_le_non_zero_divisors_of_no_zero_divisors h_ne),
end
lemma exists_mul_mem_of_away_of_ne_zero (g : non_zero_divisors B) :
∃ b : B, ↑g * b ∈ ((non_zero_divisors A).map (algebra_map A B) : submonoid B) :=
begin
rcases is_localization.surj (submonoid.powers f) (g : B) with ⟨⟨gn, ⟨gd, hg⟩⟩, H⟩,
dsimp at H,
use algebra_map A B gd,
rw H,
simp only [submonoid.mem_map],
refine ⟨gn, _, rfl⟩,
rw mem_non_zero_divisors_iff_ne_zero,
intros h,
let p := (is_localization.to_map_eq_zero_iff B (powers_le_non_zero_divisors_of_no_zero_divisors h_ne)).mpr h,
rw <- H at p,
have hgd : (algebra_map A B) gd ∈ non_zero_divisors B,
rw mem_non_zero_divisors_iff_ne_zero,
refine is_localization.to_map_ne_zero_of_mem_non_zero_divisors B (powers_le_non_zero_divisors_of_no_zero_divisors h_ne) _,
refine set_like.le_def.mp (powers_le_non_zero_divisors_of_no_zero_divisors h_ne) hg,
let q := (non_zero_divisors B).mul_mem' g.2 hgd,
simp at q,
rw mem_non_zero_divisors_iff_ne_zero at q,
refine q p,
end
set_option pp.implicit false
def is_fraction_of_algebra_of_away_frac :
@is_fraction_ring B _ C _ (algebra_of_away_frac h_ne B C):=
begin
letI : algebra B C := (algebra_of_away_frac h_ne B C),
haveI := is_localization_of_away h_ne B C,
exact is_localization_of_le_of_exists_mul_mem C (non_zero_map_le_non_zero h_ne B)
(λ n, exists_mul_mem_of_away_of_ne_zero h_ne B n),
end
end
end is_localization |
9b239e2918d12ecfcc7b61734b1c9bb9dcc8b5bb | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/group_theory/order_of_element.lean | e6181e443c3aafcb3c249c0d29f6c4e55abfba7b | [] | 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 | 10,549 | 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
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.big_operators.order
import Mathlib.group_theory.coset
import Mathlib.data.nat.totient
import Mathlib.data.int.gcd
import Mathlib.data.set.finite
import Mathlib.PostPort
universes u_1 u_2 l
namespace Mathlib
-- TODO mem_range_iff_mem_finset_range_of_mod_eq should be moved elsewhere.
namespace finset
theorem mem_range_iff_mem_finset_range_of_mod_eq {α : Type u_1} [DecidableEq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀ (i : ℤ), f (i % ↑n) = f i) : a ∈ set.range f ↔ a ∈ image (fun (i : ℕ) => f ↑i) (range n) := sorry
end finset
theorem mem_normalizer_fintype {α : Type u_1} [group α] {s : set α} [fintype ↥s] {x : α} (h : ∀ (n : α), n ∈ s → x * n * (x⁻¹) ∈ s) : x ∈ subgroup.set_normalizer s := sorry
protected instance fintype_bot {α : Type u_1} [group α] : fintype ↥⊥ :=
fintype.mk (singleton 1) sorry
@[simp] theorem card_trivial {α : Type u_1} [group α] : fintype.card ↥⊥ = 1 := sorry
theorem card_eq_card_quotient_mul_card_subgroup {α : Type u_1} [group α] [fintype α] (s : subgroup α) [fintype ↥s] [decidable_pred fun (a : α) => a ∈ s] : fintype.card α = fintype.card (quotient_group.quotient s) * fintype.card ↥s := sorry
theorem card_subgroup_dvd_card {α : Type u_1} [group α] [fintype α] (s : subgroup α) [fintype ↥s] : fintype.card ↥s ∣ fintype.card α := sorry
theorem card_quotient_dvd_card {α : Type u_1} [group α] [fintype α] (s : subgroup α) [decidable_pred fun (a : α) => a ∈ s] [fintype ↥s] : fintype.card (quotient_group.quotient s) ∣ fintype.card α := sorry
theorem exists_gpow_eq_one {α : Type u_1} [group α] [fintype α] (a : α) : ∃ (i : ℤ), ∃ (H : i ≠ 0), a ^ i = 1 := sorry
theorem exists_pow_eq_one {α : Type u_1} [group α] [fintype α] (a : α) : ∃ (i : ℕ), ∃ (H : i > 0), a ^ i = 1 := sorry
/-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/
def order_of {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] (a : α) : ℕ :=
nat.find (exists_pow_eq_one a)
theorem pow_order_of_eq_one {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] (a : α) : a ^ order_of a = 1 := sorry
theorem order_of_pos {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] (a : α) : 0 < order_of a := sorry
theorem pow_injective_of_lt_order_of {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} {m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m :=
or.elim (le_total n m) (fun (h : n ≤ m) => pow_injective_aux a h hn hm eq)
fun (h : m ≤ n) => Eq.symm (pow_injective_aux a h hm hn (Eq.symm eq))
theorem order_of_le_card_univ {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] : order_of a ≤ fintype.card α :=
finset.card_le_of_inj_on (pow a) (fun (n : ℕ) (_x : n < order_of a) => fintype.complete (a ^ n))
fun (i j : ℕ) => pow_injective_of_lt_order_of a
theorem pow_eq_mod_order_of {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} : a ^ n = a ^ (n % order_of a) := sorry
theorem gpow_eq_mod_order_of {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {i : ℤ} : a ^ i = a ^ (i % ↑(order_of a)) := sorry
theorem mem_gpowers_iff_mem_range_order_of {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] {a : α} {a' : α} : a' ∈ subgroup.gpowers a ↔ a' ∈ finset.image (pow a) (finset.range (order_of a)) :=
finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) fun (i : ℤ) => Eq.symm gpow_eq_mod_order_of
protected instance decidable_gpowers {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] : decidable_pred ↑(subgroup.gpowers a) :=
fun (a' : α) => decidable_of_iff' (a' ∈ finset.image (pow a) (finset.range (order_of a))) sorry
theorem order_of_dvd_of_pow_eq_one {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := sorry
theorem order_of_dvd_iff_pow_eq_one {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} : order_of a ∣ n ↔ a ^ n = 1 := sorry
theorem order_of_le_of_pow_eq_one {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n :=
nat.find_min' (exists_pow_eq_one a) (Exists.intro hn h)
theorem sum_card_order_of_eq_card_pow_eq_one {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] {n : ℕ} (hn : 0 < n) : (finset.sum (finset.filter (fun (_x : ℕ) => _x ∣ n) (finset.range (Nat.succ n)))
fun (m : ℕ) => finset.card (finset.filter (fun (a : α) => order_of a = m) finset.univ)) =
finset.card (finset.filter (fun (a : α) => a ^ n = 1) finset.univ) := sorry
theorem order_eq_card_gpowers {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] : order_of a = fintype.card ↥↑(subgroup.gpowers a) := sorry
@[simp] theorem order_of_one {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] : order_of 1 = 1 := sorry
@[simp] theorem order_of_eq_one_iff {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] : order_of a = 1 ↔ a = 1 := sorry
theorem order_of_eq_prime {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] {p : ℕ} [hp : fact (nat.prime p)] (hg : a ^ p = 1) (hg1 : a ≠ 1) : order_of a = p :=
or.resolve_left (and.right hp (order_of a) (order_of_dvd_of_pow_eq_one hg)) (mt (iff.mp order_of_eq_one_iff) hg1)
/- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/
theorem order_of_dvd_card_univ {α : Type u_1} {a : α} [group α] [fintype α] [dec : DecidableEq α] : order_of a ∣ fintype.card α := sorry
@[simp] theorem pow_card_eq_one {α : Type u_1} [group α] [fintype α] (a : α) : a ^ fintype.card α = 1 := sorry
theorem mem_powers_iff_mem_gpowers {α : Type u_1} [group α] [fintype α] {a : α} {x : α} : x ∈ submonoid.powers a ↔ x ∈ subgroup.gpowers a := sorry
theorem powers_eq_gpowers {α : Type u_1} [group α] [fintype α] (a : α) : ↑(submonoid.powers a) = ↑(subgroup.gpowers a) :=
set.ext fun (x : α) => mem_powers_iff_mem_gpowers
theorem order_of_pow {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / nat.gcd (order_of a) n := sorry
theorem image_range_order_of {α : Type u_1} [group α] [fintype α] [dec : DecidableEq α] (a : α) : finset.image (fun (i : ℕ) => a ^ i) (finset.range (order_of a)) = set.to_finset ↑(subgroup.gpowers a) := sorry
theorem pow_gcd_card_eq_one_iff {α : Type u_1} [group α] [fintype α] {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ nat.gcd n (fintype.card α) = 1 := sorry
/-- A group is called *cyclic* if it is generated by a single element. -/
class is_cyclic (α : Type u_2) [group α]
where
exists_generator : ∃ (g : α), ∀ (x : α), x ∈ subgroup.gpowers g
/-- A cyclic group is always commutative. This is not an `instance` because often we have a better
proof of `comm_group`. -/
def is_cyclic.comm_group {α : Type u_1} [hg : group α] [is_cyclic α] : comm_group α :=
comm_group.mk group.mul group.mul_assoc group.one group.one_mul group.mul_one group.inv group.div group.mul_left_inv
sorry
theorem is_cyclic_of_order_of_eq_card {α : Type u_1} [group α] [DecidableEq α] [fintype α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := sorry
theorem is_cyclic_of_prime_card {α : Type u_1} [group α] [fintype α] {p : ℕ} [hp : fact (nat.prime p)] (h : fintype.card α = p) : is_cyclic α := sorry
theorem order_of_eq_card_of_forall_mem_gpowers {α : Type u_1} [group α] [DecidableEq α] [fintype α] {g : α} (hx : ∀ (x : α), x ∈ subgroup.gpowers g) : order_of g = fintype.card α := sorry
protected instance bot.is_cyclic {α : Type u_1} [group α] : is_cyclic ↥⊥ :=
is_cyclic.mk
(Exists.intro 1 fun (x : ↥⊥) => Exists.intro 0 (subtype.eq (Eq.symm (iff.mp subgroup.mem_bot (subtype.property x)))))
protected instance subgroup.is_cyclic {α : Type u_1} [group α] [is_cyclic α] (H : subgroup α) : is_cyclic ↥H :=
sorry
theorem is_cyclic.card_pow_eq_one_le {α : Type u_1} [group α] [DecidableEq α] [fintype α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : finset.card (finset.filter (fun (a : α) => a ^ n = 1) finset.univ) ≤ n := sorry
theorem is_cyclic.exists_monoid_generator (α : Type u_1) [group α] [fintype α] [is_cyclic α] : ∃ (x : α), ∀ (y : α), y ∈ submonoid.powers x := sorry
theorem is_cyclic.image_range_order_of {α : Type u_1} {a : α} [group α] [DecidableEq α] [fintype α] (ha : ∀ (x : α), x ∈ subgroup.gpowers a) : finset.image (fun (i : ℕ) => a ^ i) (finset.range (order_of a)) = finset.univ := sorry
theorem is_cyclic.image_range_card {α : Type u_1} {a : α} [group α] [DecidableEq α] [fintype α] (ha : ∀ (x : α), x ∈ subgroup.gpowers a) : finset.image (fun (i : ℕ) => a ^ i) (finset.range (fintype.card α)) = finset.univ := sorry
theorem card_pow_eq_one_eq_order_of_aux {α : Type u_1} [group α] [DecidableEq α] [fintype α] (hn : ∀ (n : ℕ), 0 < n → finset.card (finset.filter (fun (a : α) => a ^ n = 1) finset.univ) ≤ n) (a : α) : finset.card (finset.filter (fun (b : α) => b ^ order_of a = 1) finset.univ) = order_of a := sorry
theorem card_order_of_eq_totient_aux₂ {α : Type u_1} [group α] [DecidableEq α] [fintype α] (hn : ∀ (n : ℕ), 0 < n → finset.card (finset.filter (fun (a : α) => a ^ n = 1) finset.univ) ≤ n) {d : ℕ} (hd : d ∣ fintype.card α) : finset.card (finset.filter (fun (a : α) => order_of a = d) finset.univ) = nat.totient d := sorry
theorem is_cyclic_of_card_pow_eq_one_le {α : Type u_1} [group α] [DecidableEq α] [fintype α] (hn : ∀ (n : ℕ), 0 < n → finset.card (finset.filter (fun (a : α) => a ^ n = 1) finset.univ) ≤ n) : is_cyclic α := sorry
theorem is_cyclic.card_order_of_eq_totient {α : Type u_1} [group α] [is_cyclic α] [DecidableEq α] [fintype α] {d : ℕ} (hd : d ∣ fintype.card α) : finset.card (finset.filter (fun (a : α) => order_of a = d) finset.univ) = nat.totient d :=
card_order_of_eq_totient_aux₂ (fun (n : ℕ) => is_cyclic.card_pow_eq_one_le) hd
|
b426d7172430a42a1cdb2fe16ed8ad02766f90f5 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/localization/module.lean | bca0672c79990260bf20f3210d155674a4001834 | [
"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 | 3,028 | lean | /-
Copyright (c) 2022 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu, Anne Baanen
-/
import linear_algebra.linear_independent
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
/-!
# Modules / vector spaces over localizations / fraction fields
This file contains some results about vector spaces over the field of fractions of a ring.
## Main results
* `linear_independent.localization`: `b` is linear independent over a localization of `R`
if it is linear independent over `R` itself
* `basis.localization`: promote an `R`-basis `b` to an `Rₛ`-basis,
where `Rₛ` is a localization of `R`
* `linear_independent.iff_fraction_ring`: `b` is linear independent over `R` iff it is
linear independent over `Frac(R)`
-/
open_locale big_operators
open_locale non_zero_divisors
section localization
variables {R : Type*} (Rₛ : Type*) [comm_ring R] [comm_ring Rₛ] [algebra R Rₛ]
variables (S : submonoid R) [hT : is_localization S Rₛ]
include hT
section add_comm_monoid
variables {M : Type*} [add_comm_monoid M] [module R M] [module Rₛ M] [is_scalar_tower R Rₛ M]
lemma linear_independent.localization {ι : Type*} {b : ι → M} (hli : linear_independent R b) :
linear_independent Rₛ b :=
begin
rw linear_independent_iff' at ⊢ hli,
intros s g hg i hi,
choose a g' hg' using is_localization.exist_integer_multiples S s g,
letI := λ i, classical.prop_decidable (i ∈ s),
specialize hli s (λ i, if hi : i ∈ s then g' i hi else 0) _ i hi,
{ rw [← @smul_zero _ M _ _ _ (a : R), ← hg, finset.smul_sum],
refine finset.sum_congr rfl (λ i hi, _),
dsimp only,
rw [dif_pos hi, ← is_scalar_tower.algebra_map_smul Rₛ, hg' i hi, smul_assoc],
apply_instance },
refine ((is_localization.map_units Rₛ a).mul_right_eq_zero).mp _,
rw [← algebra.smul_def, ← map_zero (algebra_map R Rₛ), ← hli],
simp [hi, hg']
end
end add_comm_monoid
section add_comm_group
variables {M : Type*} [add_comm_group M] [module R M] [module Rₛ M] [is_scalar_tower R Rₛ M]
/-- Promote a basis for `M` over `R` to a basis for `M` over the localization `Rₛ` -/
noncomputable def basis.localization {ι : Type*} (b : basis ι R M) : basis ι Rₛ M :=
basis.mk (b.linear_independent.localization Rₛ S) $
by { rw [← eq_top_iff, ← @submodule.restrict_scalars_eq_top_iff Rₛ R, eq_top_iff, ← b.span_eq],
apply submodule.span_le_restrict_scalars }
end add_comm_group
end localization
section fraction_ring
variables (R K : Type*) [comm_ring R] [field K] [algebra R K] [is_fraction_ring R K]
variables {V : Type*} [add_comm_group V] [module R V] [module K V] [is_scalar_tower R K V]
lemma linear_independent.iff_fraction_ring {ι : Type*} {b : ι → V} :
linear_independent R b ↔ linear_independent K b :=
⟨linear_independent.localization K (R⁰),
linear_independent.restrict_scalars (smul_left_injective R one_ne_zero)⟩
end fraction_ring
|
0f289ccbfa0e8039efbc6cd118863c1edd488de6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/list/rotate.lean | ad57d2f6e96bd4e5b9653e88a18156cc2c612f78 | [] | 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,685 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.list.basic
import Mathlib.PostPort
universes u
namespace Mathlib
namespace list
theorem rotate_mod {α : Type u} (l : List α) (n : ℕ) : rotate l (n % length l) = rotate l n := sorry
@[simp] theorem rotate_nil {α : Type u} (n : ℕ) : rotate [] n = [] :=
nat.cases_on n (Eq.refl (rotate [] 0)) fun (n : ℕ) => Eq.refl (rotate [] (Nat.succ n))
@[simp] theorem rotate_zero {α : Type u} (l : List α) : rotate l 0 = l := sorry
@[simp] theorem rotate'_nil {α : Type u} (n : ℕ) : rotate' [] n = [] :=
nat.cases_on n (Eq.refl (rotate' [] 0)) fun (n : ℕ) => Eq.refl (rotate' [] (Nat.succ n))
@[simp] theorem rotate'_zero {α : Type u} (l : List α) : rotate' l 0 = l :=
list.cases_on l (Eq.refl (rotate' [] 0)) fun (l_hd : α) (l_tl : List α) => Eq.refl (rotate' (l_hd :: l_tl) 0)
theorem rotate'_cons_succ {α : Type u} (l : List α) (a : α) (n : ℕ) : rotate' (a :: l) (Nat.succ n) = rotate' (l ++ [a]) n := sorry
@[simp] theorem length_rotate' {α : Type u} (l : List α) (n : ℕ) : length (rotate' l n) = length l := sorry
theorem rotate'_eq_take_append_drop {α : Type u} {l : List α} {n : ℕ} : n ≤ length l → rotate' l n = drop n l ++ take n l := sorry
theorem rotate'_rotate' {α : Type u} (l : List α) (n : ℕ) (m : ℕ) : rotate' (rotate' l n) m = rotate' l (n + m) := sorry
@[simp] theorem rotate'_length {α : Type u} (l : List α) : rotate' l (length l) = l := sorry
@[simp] theorem rotate'_length_mul {α : Type u} (l : List α) (n : ℕ) : rotate' l (length l * n) = l := sorry
theorem rotate'_mod {α : Type u} (l : List α) (n : ℕ) : rotate' l (n % length l) = rotate' l n := sorry
theorem rotate_eq_rotate' {α : Type u} (l : List α) (n : ℕ) : rotate l n = rotate' l n := sorry
theorem rotate_cons_succ {α : Type u} (l : List α) (a : α) (n : ℕ) : rotate (a :: l) (Nat.succ n) = rotate (l ++ [a]) n := sorry
@[simp] theorem mem_rotate {α : Type u} {l : List α} {a : α} {n : ℕ} : a ∈ rotate l n ↔ a ∈ l := sorry
@[simp] theorem length_rotate {α : Type u} (l : List α) (n : ℕ) : length (rotate l n) = length l :=
eq.mpr (id (Eq._oldrec (Eq.refl (length (rotate l n) = length l)) (rotate_eq_rotate' l n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (length (rotate' l n) = length l)) (length_rotate' l n))) (Eq.refl (length l)))
theorem rotate_eq_take_append_drop {α : Type u} {l : List α} {n : ℕ} : n ≤ length l → rotate l n = drop n l ++ take n l :=
eq.mpr (id (Eq._oldrec (Eq.refl (n ≤ length l → rotate l n = drop n l ++ take n l)) (rotate_eq_rotate' l n)))
rotate'_eq_take_append_drop
theorem rotate_rotate {α : Type u} (l : List α) (n : ℕ) (m : ℕ) : rotate (rotate l n) m = rotate l (n + m) := sorry
@[simp] theorem rotate_length {α : Type u} (l : List α) : rotate l (length l) = l :=
eq.mpr (id (Eq._oldrec (Eq.refl (rotate l (length l) = l)) (rotate_eq_rotate' l (length l))))
(eq.mpr (id (Eq._oldrec (Eq.refl (rotate' l (length l) = l)) (rotate'_length l))) (Eq.refl l))
@[simp] theorem rotate_length_mul {α : Type u} (l : List α) (n : ℕ) : rotate l (length l * n) = l :=
eq.mpr (id (Eq._oldrec (Eq.refl (rotate l (length l * n) = l)) (rotate_eq_rotate' l (length l * n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (rotate' l (length l * n) = l)) (rotate'_length_mul l n))) (Eq.refl l))
theorem prod_rotate_eq_one_of_prod_eq_one {α : Type u} [group α] {l : List α} (hl : prod l = 1) (n : ℕ) : prod (rotate l n) = 1 := sorry
|
5598b75762d61d5d9b7a763bcffe7a02aef38d5e | 735bb6d9c54e20a6bdc031c27bff1717e68886b9 | /data/list/set.lean | c73a52f36d19f4d91edc38c48e5df946d7b69620 | [] | no_license | digama0/library_dev | 3ea441564c4d7eca54a562b701febaa4db6a1061 | 56520d5d1dda46d87c98bf3acdf850672fdab00f | refs/heads/master | 1,611,047,574,219 | 1,500,469,648,000 | 1,500,469,648,000 | 87,738,883 | 0 | 0 | null | 1,491,771,880,000 | 1,491,771,879,000 | null | UTF-8 | Lean | false | false | 31,854 | lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
Set-like operations on lists.
-/
import data.list.basic data.list.comb .basic .comb
open nat function decidable
universe variables uu vv
variables {α : Type uu} {β : Type vv}
namespace list
section insert
variable [decidable_eq α]
@[simp]
theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else concat l a := rfl
@[simp]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by rw [insert.def, if_pos h]
@[simp]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = concat l a :=
by rw [insert.def, if_neg h]
@[simp]
theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
by by_cases a ∈ l with h; simp [h]
@[simp]
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
by by_cases b ∈ l with h'; simp [h, h']
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
if h' : b ∈ l then
begin simp [h'] at h, simp [h] end
else
begin simp [h'] at h, assumption end
@[simp]
theorem mem_insert_iff (a b : α) (l : list α) : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
iff.intro eq_or_mem_of_mem_insert
(λ h, or.elim h (begin intro h', simp [h'] end) mem_insert_of_mem)
@[simp]
theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by simp [h]
@[simp]
theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by simp [h]
theorem forall_mem_insert_of_forall_mem {p : α → Prop} {a : α} {l : list α}
(h₁ : p a) (h₂ : ∀ x ∈ l, p x) :
∀ x ∈ insert a l, p x :=
if h : a ∈ l then begin simp [h], exact h₂ end
else begin simp [h], intros b hb, cases hb with h₃ h₃, {rw h₃, assumption}, exact h₂ _ h₃ end
end insert
section erase
variable [decidable_eq α]
@[simp]
lemma erase_nil (a : α) : [].erase a = [] :=
rfl
lemma erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a :=
rfl
@[simp]
lemma erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp [erase_cons, if_pos]
@[simp]
lemma erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp [erase_cons, if_neg, h]
@[simp]
lemma length_erase_of_mem {a : α} : ∀{l:list α}, a ∈ l → length (l.erase a) = pred (length l)
| [] h := rfl
| [x] h := begin simp at h, simp [h] end
| (x::y::xs) h := if h' : x = a then
by simp [h', one_add]
else
have ainyxs : a ∈ y::xs, from or_resolve_right h $ by cc,
by simp [h', length_erase_of_mem ainyxs, one_add]
@[simp]
lemma erase_of_not_mem {a : α} : ∀{l : list α}, a ∉ l → l.erase a = l
| [] h := rfl
| (x::xs) h :=
have anex : x ≠ a, from λ aeqx : x = a, absurd (or.inl aeqx.symm) h,
have aninxs : a ∉ xs, from λ ainxs : a ∈ xs, absurd (or.inr ainxs) h,
by simp [anex, erase_of_not_mem aninxs]
lemma erase_append_left {a : α} : ∀ {l₁:list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂
| [] l₂ h := absurd h (not_mem_nil a)
| (x::xs) l₂ h := if h' : x = a then by simp [h']
else
have a ∈ xs, from mem_of_ne_of_mem (assume h, h' h.symm) h,
by simp [erase_append_left l₂ this, h']
lemma erase_append_right {a : α} : ∀{l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a
| [] l₂ h := rfl
| (x::xs) l₂ h := if h' : x = a then begin simp [h'] at h, contradiction end
else
have a ∉ xs, from not_mem_of_not_mem_cons h,
by simp [erase_append_right l₂ this, h']
lemma erase_sublist (a : α) : ∀(l : list α), l.erase a <+ l
| [] := sublist.refl nil
| (x :: xs) := if h : x = a then
by simp [h]
else
begin simp [h], apply cons_sublist_cons, apply erase_sublist xs end
lemma erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem mem_erase_of_ne_of_mem {a b : α} : ∀ {l : list α}, a ≠ b → a ∈ l → a ∈ l.erase b
| [] aneb anil := begin simp at anil, contradiction end
| (c :: l) aneb acl := if h : c = b then
begin simp [h, aneb] at acl, simp [h, acl] end
else
begin
simp [h], simp at acl, cases acl with h' h',
{ simp [h'] },
simp [mem_erase_of_ne_of_mem aneb h']
end
theorem mem_of_mem_erase {a b : α} : ∀{l:list α}, a ∈ l.erase b → a ∈ l
| [] h := begin simp at h, contradiction end
| (c :: l) h := if h' : c = b then
begin simp [h'] at h, simp [h] end
else
begin
simp [h'] at h, cases h with h'' h'',
{ simp [h''] },
simp [mem_of_mem_erase h'']
end
end erase
/- disjoint -/
section disjoint
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, (a ∈ l₁ → a ∈ l₂ → false)
lemma disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₁ → a ∉ l₂ :=
λ d, d
lemma disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
λ d a i₂ i₁, d i₁ i₂
lemma disjoint.comm {l₁ l₂ : list α} : disjoint l₁ l₂ → disjoint l₂ l₁ :=
λ d a i₂ i₁, d i₁ i₂
lemma disjoint_of_subset_left {l₁ l₂ l : list α} : l₁ ⊆ l → disjoint l l₂ → disjoint l₁ l₂ :=
λ ss d x xinl₁, d (ss xinl₁)
lemma disjoint_of_subset_right {l₁ l₂ l : list α} : l₂ ⊆ l → disjoint l₁ l → disjoint l₁ l₂ :=
λ ss d x xinl xinl₁, d xinl (ss xinl₁)
lemma disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
lemma disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
lemma disjoint_nil_left (l : list α) : disjoint [] l :=
λ a ab, absurd ab (not_mem_nil a)
lemma disjoint_nil_right (l : list α) : disjoint l [] :=
disjoint.comm (disjoint_nil_left l)
lemma disjoint_cons_of_not_mem_of_disjoint {a : α} {l₁ l₂ : list α} :
a ∉ l₂ → disjoint l₁ l₂ → disjoint (a::l₁) l₂ :=
λ nainl₂ d x (xinal₁ : x ∈ a::l₁),
or.elim (eq_or_mem_of_mem_cons xinal₁)
(λ xeqa : x = a, eq.symm xeqa ▸ nainl₂)
(λ xinl₁ : x ∈ l₁, disjoint_left d xinl₁)
lemma disjoint_append_of_disjoint_left {l₁ l₂ l : list α} :
disjoint l₁ l → disjoint l₂ l → disjoint (l₁++l₂) l :=
λ d₁ d₂ x h, or.elim (mem_or_mem_of_mem_append h) (@d₁ x) (@d₂ x)
lemma disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l → disjoint l₁ l :=
disjoint_of_subset_left (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} : disjoint (l₁++l₂) l → disjoint l₂ l :=
disjoint_of_subset_left (list.subset_append_right _ _)
lemma disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} : disjoint l (l₁++l₂) → disjoint l l₁ :=
disjoint_of_subset_right (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) → disjoint l l₂ :=
disjoint_of_subset_right (list.subset_append_right _ _)
end disjoint
/- upto -/
def upto : nat → list nat
| 0 := []
| (n+1) := n :: upto n
@[simp]
theorem upto_nil : upto 0 = nil := rfl
@[simp]
theorem upto_succ (n : nat) : upto (succ n) = n :: upto n := rfl
@[simp]
theorem length_upto : ∀ n, length (upto n) = n
| 0 := rfl
| (succ n) := begin rw [upto_succ, length_cons, length_upto] end
theorem upto_ne_nil_of_ne_zero {n : ℕ} (h : n ≠ 0) : upto n ≠ nil :=
assume : upto n = nil,
have upto n = upto 0, from upto_nil ▸ this,
have n = 0, from calc
n = length (upto n) : by rw length_upto
... = length (upto 0) : by rw this
... = 0 : by rw length_upto,
h this
theorem lt_of_mem_upto : ∀ ⦃n i⦄, i ∈ upto n → i < n
| 0 := assume i imem, absurd imem (not_mem_nil _)
| (succ n) := assume i imem,
or.elim (eq_or_mem_of_mem_cons imem)
(λ h, begin rw h, apply lt_succ_self end)
(λ h, lt.trans (lt_of_mem_upto h) (lt_succ_self n))
theorem mem_upto_succ_of_mem_upto {n i : nat} : i ∈ upto n → i ∈ upto (succ n) :=
assume i, mem_cons_of_mem _ i
theorem mem_upto_of_lt : ∀ ⦃n i : nat⦄, i < n → i ∈ upto n
| 0 := λ i h, absurd h (not_lt_zero i)
| (succ n) := λ i h,
begin
cases nat.lt_or_eq_of_le (le_of_lt_succ h) with ilt ieq,
{ apply mem_upto_succ_of_mem_upto, apply mem_upto_of_lt ilt },
simp [ieq]
end
lemma upto_step : ∀ (n : nat), upto (succ n) = (map succ (upto n)) ++ [0]
| 0 := rfl
| (succ n) := by simp [(upto_step n)^.symm]
/- union -/
section union
variable [decidable_eq α]
@[simp]
theorem union_nil (l : list α) : l ∪ [] = l := rfl
@[simp]
theorem union_cons (l₁ l₂ : list α) (a : α) : l₁ ∪ (a :: l₂) = insert a l₁ ∪ l₂ := rfl
theorem mem_or_mem_of_mem_union : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ ∪ l₂ → a ∈ l₁ ∨ a ∈ l₂
| l₁ [] a h := begin simp at h, simp [h] end
| l₁ (b :: l₂) a h := if h' : b ∈ l₂ then
begin
simp at h,
cases mem_or_mem_of_mem_union h with h₀ h₀,
{ simp at h₀, cases h₀ with h₁ h₁, simp [h₁], simp [h₁] },
simp [h₀]
end
else
begin
simp [union_cons] at h,
cases mem_or_mem_of_mem_union h with h₀ h₀,
{ simp at h₀, cases h₀ with h₁ h₁, repeat { simp [h₁] } },
simp [h₀]
end
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
begin
revert h,
generalize l₁ l,
induction l₂ with b l₂ ih,
{ simp, intros, assumption },
intros, apply ih, simp [h]
end
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
begin
generalize l₁ l, induction l₂ with b l₂ ih,
{ simp at h, contradiction },
intro l, simp, simp at h,
cases h with h₀ h₀,
{ simp [h₀], apply mem_union_left, simp },
apply ih h₀
end
@[simp]
theorem mem_union_iff (a : α) (l₁ l₂ : list α) : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
iff.intro mem_or_mem_of_mem_union (λ h, or.elim h (λ h', mem_union_left h' l₂) (mem_union_right l₁))
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} (h₁ : ∀ x ∈ l₁, p x) (h₂ : ∀ x ∈ l₂, p x) :
∀ x ∈ l₁ ∪ l₂, p x :=
begin
intro x, simp, intro h, cases h,
{ apply h₁, assumption },
apply h₂, assumption
end
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) :
∀ x ∈ l₁, p x :=
begin intros x xl₁, apply h, apply mem_union_left xl₁ end
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) :
∀ x ∈ l₂, p x :=
begin intros x xl₂, apply h, apply mem_union_right l₁ xl₂ end
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp]
theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp]
theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp]
theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ ∩ l₂ → a ∈ l₁
| [] l₂ a i := absurd i (not_mem_nil a)
| (b::l₁) l₂ a i := by_cases
(λ binl₂ : b ∈ l₂,
have aux : a ∈ b :: l₁ ∩ l₂, begin rw [inter_cons_of_mem _ binl₂] at i, exact i end,
or.elim (eq_or_mem_of_mem_cons aux)
(λ aeqb : a = b, begin rw [aeqb], apply mem_cons_self end)
(λ aini, mem_cons_of_mem _ (mem_of_mem_inter_left aini)))
(λ nbinl₂ : b ∉ l₂,
have ainl₁ : a ∈ l₁,
begin rw [inter_cons_of_not_mem _ nbinl₂] at i, exact (mem_of_mem_inter_left i) end,
mem_cons_of_mem _ ainl₁)
theorem mem_of_mem_inter_right : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ ∩ l₂ → a ∈ l₂
| [] l₂ a i := absurd i (not_mem_nil _)
| (b::l₁) l₂ a i := by_cases
(λ binl₂ : b ∈ l₂,
have aux : a ∈ b :: l₁ ∩ l₂, begin rw [inter_cons_of_mem _ binl₂] at i, exact i end,
or.elim (eq_or_mem_of_mem_cons aux)
(λ aeqb : a = b, begin rw [aeqb], exact binl₂ end)
(λ aini : a ∈ l₁ ∩ l₂, mem_of_mem_inter_right aini))
(λ nbinl₂ : b ∉ l₂,
begin rw [inter_cons_of_not_mem _ nbinl₂] at i, exact (mem_of_mem_inter_right i) end)
theorem mem_inter_of_mem_of_mem : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂
| [] l₂ a i₁ i₂ := absurd i₁ (not_mem_nil _)
| (b::l₁) l₂ a i₁ i₂ := by_cases
(λ binl₂ : b ∈ l₂,
or.elim (eq_or_mem_of_mem_cons i₁)
(λ aeqb : a = b,
begin rw [inter_cons_of_mem _ binl₂, aeqb], apply mem_cons_self end)
(λ ainl₁ : a ∈ l₁,
begin
rw [inter_cons_of_mem _ binl₂],
apply mem_cons_of_mem,
exact (mem_inter_of_mem_of_mem ainl₁ i₂)
end))
(λ nbinl₂ : b ∉ l₂,
or.elim (eq_or_mem_of_mem_cons i₁)
(λ aeqb : a = b,
begin rw aeqb at i₂, exact absurd i₂ nbinl₂ end)
(λ ainl₁ : a ∈ l₁,
begin rw [inter_cons_of_not_mem _ nbinl₂], exact (mem_inter_of_mem_of_mem ainl₁ i₂) end))
@[simp]
theorem mem_inter_iff (a : α) (l₁ l₂ : list α) : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
iff.intro
(λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h))
(λ h, mem_inter_of_mem_of_mem h^.left h^.right)
theorem inter_eq_nil_of_disjoint : ∀ {l₁ l₂ : list α}, disjoint l₁ l₂ → l₁ ∩ l₂ = []
| [] l₂ d := rfl
| (a::l₁) l₂ d :=
have aux_eq : l₁ ∩ l₂ = [], from inter_eq_nil_of_disjoint (disjoint_of_disjoint_cons_left d),
have nainl₂ : a ∉ l₂, from disjoint_left d (mem_cons_self _ _),
by rw [inter_cons_of_not_mem _ nainl₂, aux_eq]
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
λ x xl₁l₂, h x (mem_of_mem_inter_left xl₁l₂)
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
λ x xl₁l₂, h x (mem_of_mem_inter_right xl₁l₂)
end inter
/- no duplicates predicate -/
inductive nodup {α : Type uu} : list α → Prop
| ndnil : nodup []
| ndcons : ∀ {a : α} {l : list α}, a ∉ l → nodup l → nodup (a::l)
section nodup
open nodup
theorem nodup_nil : @nodup α [] :=
ndnil
theorem nodup_cons {a : α} {l : list α} : a ∉ l → nodup l → nodup (a::l) :=
λ i n, ndcons i n
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → nodup l
| a xs (ndcons i n) := n
theorem not_mem_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → a ∉ l
| a xs (ndcons i n) := i
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
λ ainl d, absurd ainl (not_mem_of_nodup_cons d)
theorem nodup_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → nodup l₂ → nodup l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (ndcons i n) := nodup_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (ndcons i n) :=
ndcons (λh, i (subset_of_sublist s h)) (nodup_of_sublist s n)
theorem not_nodup_cons_of_not_nodup {a : α} {l : list α} : ¬ nodup l → ¬ nodup (a :: l) :=
mt nodup_of_nodup_cons
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → nodup l₂
| [] l₂ n := n
| (x::xs) l₂ n := nodup_of_nodup_append_right (nodup_of_nodup_cons n)
theorem disjoint_of_nodup_append : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → disjoint l₁ l₂
| [] l₂ d := disjoint_nil_left l₂
| (x::xs) l₂ d :=
have nodup (x::(xs++l₂)), from d,
have x ∉ xs++l₂, from not_mem_of_nodup_cons this,
have nxinl₂ : x ∉ l₂, from not_mem_of_not_mem_append_right this,
assume a, assume : a ∈ x::xs,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = x, eq.symm this ▸ nxinl₂)
(assume ainxs : a ∈ xs,
have nodup (x::(xs++l₂)), from d,
have nodup (xs++l₂), from nodup_of_nodup_cons this,
have disjoint xs l₂, from disjoint_of_nodup_append this,
disjoint_left this ainxs)
theorem nodup_append_of_nodup_of_nodup_of_disjoint :
∀ {l₁ l₂ : list α}, nodup l₁ → nodup l₂ → disjoint l₁ l₂ → nodup (l₁++l₂)
| [] l₂ d₁ d₂ dsj := begin rw [nil_append], exact d₂ end
| (x::xs) l₂ d₁ d₂ dsj :=
have ndxs : nodup xs, from nodup_of_nodup_cons d₁,
have disjoint xs l₂, from disjoint_of_disjoint_cons_left dsj,
have ndxsl₂ : nodup (xs++l₂), from nodup_append_of_nodup_of_nodup_of_disjoint ndxs d₂ this,
have nxinxs : x ∉ xs, from not_mem_of_nodup_cons d₁,
have x ∉ l₂, from disjoint_left dsj (mem_cons_self x xs),
have x ∉ xs++l₂, from not_mem_append nxinxs this,
nodup_cons this ndxsl₂
theorem nodup_app_comm {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : nodup (l₂++l₁) :=
have d₁ : nodup l₁, from nodup_of_nodup_append_left d,
have d₂ : nodup l₂, from nodup_of_nodup_append_right d,
have dsj : disjoint l₁ l₂, from disjoint_of_nodup_append d,
nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₁ (disjoint.comm dsj)
theorem nodup_head {a : α} {l₁ l₂ : list α} (d : nodup (l₁++(a::l₂))) : nodup (a::(l₁++l₂)) :=
have d₁ : nodup (a::(l₂++l₁)), from nodup_app_comm d,
have d₂ : nodup (l₂++l₁), from nodup_of_nodup_cons d₁,
have d₃ : nodup (l₁++l₂), from nodup_app_comm d₂,
have nain : a ∉ l₂++l₁, from not_mem_of_nodup_cons d₁,
have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_left nain,
have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_right nain,
nodup_cons (not_mem_append nain₁ nain₂) d₃
theorem nodup_middle {a : α} {l₁ l₂ : list α} (d : nodup (a::(l₁++l₂))) : nodup (l₁++(a::l₂)) :=
have d₁ : nodup (l₁++l₂), from nodup_of_nodup_cons d,
have nain : a ∉ l₁++l₂, from not_mem_of_nodup_cons d,
have disj : disjoint l₁ l₂, from disjoint_of_nodup_append d₁,
have d₂ : nodup l₁, from nodup_of_nodup_append_left d₁,
have d₃ : nodup l₂, from nodup_of_nodup_append_right d₁,
have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_right nain,
have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_left nain,
have d₄ : nodup (a::l₂), from nodup_cons nain₂ d₃,
have disj₂ : disjoint l₁ (a::l₂), from disjoint.comm (disjoint_cons_of_not_mem_of_disjoint nain₁
(disjoint.comm disj)),
nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₄ disj₂
theorem nodup_map {f : α → β} (inj : injective f) : ∀ {l : list α}, nodup l → nodup (map f l)
| [] n := begin apply nodup_nil end
| (x::xs) n :=
have nxinxs : x ∉ xs, from not_mem_of_nodup_cons n,
have ndxs : nodup xs, from nodup_of_nodup_cons n,
have ndmfxs : nodup (map f xs), from nodup_map ndxs,
have nfxinm : f x ∉ map f xs, from
λ ab : f x ∈ map f xs,
match (exists_of_mem_map ab) with
| ⟨(y : α), (yinxs : y ∈ xs), (fyfx : f y = f x)⟩ :=
have yeqx : y = x, from inj fyfx,
begin subst y, contradiction end
end,
nodup_cons nfxinm ndmfxs
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) : ∀ {l}, nodup l → nodup (l.erase a)
| [] n := nodup_nil
| (b::l) n := by_cases
(λ aeqb : b = a, begin rw [aeqb, erase_cons_head], exact (nodup_of_nodup_cons n) end)
(λ aneb : b ≠ a,
have nbinl : b ∉ l, from not_mem_of_nodup_cons n,
have ndl : nodup l, from nodup_of_nodup_cons n,
have ndeal : nodup (l.erase a), from nodup_erase_of_nodup ndl,
have nbineal : b ∉ l.erase a, from λ i, absurd (erase_subset _ _ i) nbinl,
have aux : nodup (b :: l.erase a), from nodup_cons nbineal ndeal,
begin rw [erase_cons_tail _ aneb], exact aux end)
theorem mem_erase_of_nodup [decidable_eq α] (a : α) : ∀ {l}, nodup l → a ∉ l.erase a
| [] n := (not_mem_nil _)
| (b::l) n :=
have ndl : nodup l, from nodup_of_nodup_cons n,
have naineal : a ∉ l.erase a, from mem_erase_of_nodup ndl,
have nbinl : b ∉ l, from not_mem_of_nodup_cons n,
by_cases
(λ aeqb : b = a, begin rw [aeqb.symm, erase_cons_head], exact nbinl end)
(λ aneb : b ≠ a,
have aux : a ∉ b :: l.erase a, from
assume ainbeal : a ∈ b :: l.erase a, or.elim (eq_or_mem_of_mem_cons ainbeal)
(λ aeqb : a = b, absurd aeqb.symm aneb)
(λ aineal : a ∈ l.erase a, absurd aineal naineal),
begin rw [erase_cons_tail _ aneb], exact aux end)
def erase_dup [decidable_eq α] : list α → list α
| [] := []
| (x :: xs) := if x ∈ xs then erase_dup xs else x :: erase_dup xs
theorem erase_dup_nil [decidable_eq α] : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem [decidable_eq α] {a : α} {l : list α} :
a ∈ l → erase_dup (a::l) = erase_dup l :=
assume ainl, calc
erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl
... = erase_dup l : if_pos ainl
theorem erase_dup_cons_of_not_mem [decidable_eq α] {a : α} {l : list α} :
a ∉ l → erase_dup (a::l) = a :: erase_dup l :=
assume nainl, calc
erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl
... = a :: erase_dup l : if_neg nainl
theorem mem_erase_dup [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ l → a ∈ erase_dup l
| [] h := absurd h (not_mem_nil _)
| (b::l) h := by_cases
(λ binl : b ∈ l, or.elim (eq_or_mem_of_mem_cons h)
(λ aeqb : a = b,
begin rw [erase_dup_cons_of_mem binl], rw ←aeqb at binl, exact (mem_erase_dup binl) end)
(λ ainl : a ∈ l,
begin rw [erase_dup_cons_of_mem binl], exact (mem_erase_dup ainl) end))
(λ nbinl : b ∉ l, or.elim (eq_or_mem_of_mem_cons h)
(λ aeqb : a = b,
begin rw [erase_dup_cons_of_not_mem nbinl, aeqb], apply mem_cons_self end)
(λ ainl : a ∈ l,
begin rw [erase_dup_cons_of_not_mem nbinl], exact (or.inr (mem_erase_dup ainl)) end))
theorem erase_dup_sublist [decidable_eq α] : ∀ (l : list α), erase_dup l <+ l
| [] := sublist.slnil
| (b::l) := if h : b ∈ l then
by simp[erase_dup, h]; exact sublist_cons_of_sublist _ (erase_dup_sublist l)
else
by simp[erase_dup, h]; exact cons_sublist_cons _ (erase_dup_sublist l)
theorem mem_of_mem_erase_dup [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ erase_dup l → a ∈ l
| [] h := begin rw [erase_dup_nil] at h, exact h end
| (b::l) h := by_cases
(λ binl : b ∈ l,
have h₁ : a ∈ erase_dup l,
begin rw [erase_dup_cons_of_mem binl] at h, exact h end,
or.inr (mem_of_mem_erase_dup h₁))
(λ nbinl : b ∉ l,
have h₁ : a ∈ b :: erase_dup l,
begin rw [erase_dup_cons_of_not_mem nbinl] at h, exact h end,
or.elim (eq_or_mem_of_mem_cons h₁)
(λ aeqb : a = b, begin rw aeqb, apply mem_cons_self end)
(λ ainel : a ∈ erase_dup l, or.inr (mem_of_mem_erase_dup ainel)))
@[simp]
theorem mem_erase_dup_iff [decidable_eq α] (a : α) (l : list α) : a ∈ erase_dup l ↔ a ∈ l :=
iff.intro mem_of_mem_erase_dup mem_erase_dup
theorem erase_dup_sub [decidable_eq α] (l : list α) : erase_dup l ⊆ l :=
λ a i, mem_of_mem_erase_dup i
theorem sub_erase_dup [decidable_eq α] (l : list α) : l ⊆ erase_dup l :=
λ a i, mem_erase_dup i
theorem nodup_erase_dup [decidable_eq α] : ∀ l : list α, nodup (erase_dup l)
| [] := begin rw erase_dup_nil, exact nodup_nil end
| (a::l) := by_cases
(λ ainl : a ∈ l, begin rw [erase_dup_cons_of_mem ainl], exact (nodup_erase_dup l) end)
(λ nainl : a ∉ l,
have r : nodup (erase_dup l), from nodup_erase_dup l,
have nin : a ∉ erase_dup l, from
assume ab : a ∈ erase_dup l, absurd (mem_of_mem_erase_dup ab) nainl,
begin rw [erase_dup_cons_of_not_mem nainl], exact (nodup_cons nin r) end)
theorem erase_dup_eq_of_nodup [decidable_eq α] : ∀ {l : list α}, nodup l → erase_dup l = l
| [] d := rfl
| (a::l) d :=
have nainl : a ∉ l, from not_mem_of_nodup_cons d,
have dl : nodup l, from nodup_of_nodup_cons d,
by rw [erase_dup_cons_of_not_mem nainl, erase_dup_eq_of_nodup dl]
attribute [instance]
def decidable_nodup [decidable_eq α] : ∀ (l : list α), decidable (nodup l)
| [] := is_true nodup_nil
| (a::l) :=
if h : a ∈ l then
is_false (not_nodup_cons_of_mem h)
else
match (decidable_nodup l) with
| (is_true nd) := is_true (nodup_cons h nd)
| (is_false d) := is_false (not_nodup_cons_of_not_nodup d)
end
private def dgen (a : α) : ∀ l, nodup l → nodup (map (λ b : β, (a, b)) l)
| [] h := nodup_nil
| (x::l) h :=
have dl : nodup l, from nodup_of_nodup_cons h,
have dm : nodup (map (λ b : β, (a, b)) l), from dgen l dl,
have nxin : x ∉ l, from not_mem_of_nodup_cons h,
have npin : (a, x) ∉ map (λ b, (a, b)) l, from
assume pin, absurd (mem_of_mem_map_pair₁ pin) nxin,
nodup_cons npin dm
theorem nodup_product : ∀ {l₁ : list α} {l₂ : list β}, nodup l₁ → nodup l₂ → nodup (product l₁ l₂)
| [] l₂ n₁ n₂ := nodup_nil
| (a::l₁) l₂ n₁ n₂ :=
have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons n₁,
have n₃ : nodup l₁, from nodup_of_nodup_cons n₁,
have n₄ : nodup (product l₁ l₂), from nodup_product n₃ n₂,
have dm : nodup (map (λ b : β, (a, b)) l₂), from dgen a l₂ n₂,
have dsj : disjoint (map (λ b : β, (a, b)) l₂) (product l₁ l₂), from
λ p : α × β, match p with
| (a₁, b₁) :=
λ (i₁ : (a₁, b₁) ∈ map (λ b, (a, b)) l₂) (i₂ : (a₁, b₁) ∈ product l₁ l₂),
have a₁inl₁ : a₁ ∈ l₁, from mem_of_mem_product_left i₂,
have a₁ = a, from eq_of_mem_map_pair₁ i₁,
have a ∈ l₁, begin rw ←this, assumption end,
absurd this nainl₁
end,
nodup_append_of_nodup_of_nodup_of_disjoint dm n₄ dsj
theorem nodup_filter (p : α → Prop) [decidable_pred p] :
∀ {l : list α}, nodup l → nodup (filter p l)
| [] nd := nodup_nil
| (a::l) nd :=
have nainl : a ∉ l, from not_mem_of_nodup_cons nd,
have ndl : nodup l, from nodup_of_nodup_cons nd,
have ndf : nodup (filter p l), from nodup_filter ndl,
have nainf : a ∉ filter p l, from
assume ainf, absurd (mem_of_mem_filter ainf) nainl,
by_cases
(λ pa : p a, begin rw [filter_cons_of_pos _ pa], exact (nodup_cons nainf ndf) end)
(λ npa : ¬ p a, begin rw [filter_cons_of_neg _ npa], exact ndf end)
lemma dmap_nodup_of_dinj {p : α → Prop} [h : decidable_pred p] {f : Π a, p a → β} (pdi : dinj p f) :
∀ {l : list α}, nodup l → nodup (dmap p f l)
| [] := assume P, nodup.ndnil
| (a::l) := assume Pnodup,
if pa : p a then
begin
rw [dmap_cons_of_pos pa],
apply nodup_cons,
apply (not_mem_dmap_of_dinj_of_not_mem pdi pa),
exact not_mem_of_nodup_cons Pnodup,
exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup)
end
else
begin
rw [dmap_cons_of_neg pa],
exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup)
end
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
begin
revert h, induction l with b l ih,
{ intro h₀, apply nodup_singleton },
intro h₀, rw [concat_cons], apply nodup_cons,
{ simp, intro h₁, apply h₀, simp, cases h₁ with h₂ h₂, simp [h₂],
exact absurd h₂ (not_mem_of_nodup_cons h') },
apply ih,
{ apply nodup_of_nodup_cons h' },
intro h₁, apply h₀, exact mem_cons_of_mem _ h₁
end
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
if h' : a ∈ l then by simp [h', h]
else begin rw [insert_of_not_mem h'], apply nodup_concat, repeat {assumption} end
theorem nodup_upto : ∀ n, nodup (upto n)
| 0 := nodup_nil
| (n+1) :=
have d : nodup (upto n), from nodup_upto n,
have n : n ∉ upto n, from
assume i : n ∈ upto n, absurd (lt_of_mem_upto i) (nat.lt_irrefl n),
nodup_cons n d
theorem nodup_union_of_nodup_of_nodup [decidable_eq α] {l₁ l₂ : list α}
(h₁ : nodup l₁) (h₂ : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
revert h₁,
generalize l₁ l,
induction l₂ with a l₂ ih,
{ intros l nodupl, exact nodupl },
intros l nodupl, simp,
apply ih,
{ apply nodup_of_nodup_cons h₂},
apply nodup_insert nodupl
end
theorem nodup_inter_of_nodup [decidable_eq α] : ∀ {l₁ : list α} (l₂), nodup l₁ → nodup (l₁ ∩ l₂)
| [] l₂ d := nodup_nil
| (a::l₁) l₂ d :=
have d₁ : nodup l₁, from nodup_of_nodup_cons d,
have d₂ : nodup (l₁ ∩ l₂), from nodup_inter_of_nodup _ d₁,
have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons d,
have naini : a ∉ l₁ ∩ l₂, from λ i, absurd (mem_of_mem_inter_left i) nainl₁,
by_cases
(λ ainl₂ : a ∈ l₂, begin rw [inter_cons_of_mem _ ainl₂], exact (nodup_cons naini d₂) end)
(λ nainl₂ : a ∉ l₂, begin rw [inter_cons_of_not_mem _ nainl₂], exact d₂ end)
end nodup
end list
|
1bb4a6cb707b79b628d88c5dc0c3e77db0e75df0 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/linear_algebra/tensor_product.lean | ff2ab898d86e2043fa8720237c6bb23975034667 | [
"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 | 15,537 | 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
Tensor product of modules over commutative rings.
-/
import group_theory.free_abelian_group
import linear_algebra.direct_sum_module
variables {R : Type*} [comm_ring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q]
variables [module R M] [module R N] [module R P] [module R Q]
include R
set_option class.instance_max_depth 100
namespace linear_map
variables (R)
def mk₂ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P :=
⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩,
λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
λ c m, linear_map.ext $ H2 c m⟩
variables {R}
@[simp] theorem mk₂_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ P) m n = f m n := rfl
variables (f : M →ₗ[R] N →ₗ[R] P)
theorem ext₂ {f g : M →ₗ[R] N →ₗ[R] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
def flip : N →ₗ M →ₗ P :=
mk₂ R (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smul _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smul; refl)
@[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl
variables {R}
theorem flip_inj {f g : M →ₗ[R] N →ₗ P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
variables (R M N P)
def lflip : (M →ₗ[R] N →ₗ P) →ₗ[R] N →ₗ M →ₗ P :=
⟨flip, λ _ _, rfl, λ _ _, rfl⟩
variables {R M N P}
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero
theorem map_neg₂ (x y) : f (-x) y = -f x y := (flip f y).map_neg _
theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _
theorem map_smul₂ (r:R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _
variables (R P)
def lcomp (f : M →ₗ[R] N) : (N →ₗ P) →ₗ M →ₗ P :=
flip $ (flip id).comp f
variables {R P}
@[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) :
lcomp R P f g x = g (f x) := rfl
variables (R M N P)
def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P :=
flip ⟨lcomp R P,
λ f f', ext₂ $ λ g x, g.map_add _ _,
λ c f, ext₂ $ λ g x, g.map_smul _ _⟩
variables {R M N P}
section
@[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) :
llcomp R M N P f g x = f (g x) := rfl
end
def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f
@[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q :=
linear_map.comp (llcomp R N P Q g) f
@[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
def lsmul : R →ₗ M →ₗ M :=
mk₂ R (•) add_smul (λ _ _ _, eq.symm $ smul_smul _ _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end linear_map
variables (M N)
namespace tensor_product
section
open free_abelian_group
variables (R)
def relators : set (free_abelian_group (M × N)) :=
add_group.closure { x : free_abelian_group (M × N) |
(∃ (m₁ m₂ : M) (n : N), x = of (m₁, n) + of (m₂, n) - of (m₁ + m₂, n)) ∨
(∃ (m : M) (n₁ n₂ : N), x = of (m, n₁) + of (m, n₂) - of (m, n₁ + n₂)) ∨
(∃ (r : R) (m : M) (n : N), x = of (r • m, n) - of (m, r • n)) }
end
namespace relators
instance : normal_add_subgroup (relators R M N) :=
by unfold relators; apply normal_add_subgroup_of_add_comm_group
end relators
end tensor_product
variables (R)
def tensor_product : Type* :=
quotient_add_group.quotient (tensor_product.relators R M N)
variables {R}
local infix ` ⊗ `:100 := tensor_product _
local notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N
namespace tensor_product
section module
local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup
instance : add_comm_group (M ⊗[R] N) := quotient_add_group.add_comm_group _
instance quotient.mk.is_add_group_hom :
is_add_group_hom (quotient.mk : free_abelian_group (M × N) → M ⊗ N) :=
quotient_add_group.is_add_group_hom _
variables (R) {M N}
def tmul (m : M) (n : N) : M ⊗[R] N := quotient_add_group.mk $ free_abelian_group.of (m, n)
variables {R}
infix ` ⊗ₜ `:100 := tmul _
notation x ` ⊗ₜ[`:100 R `] ` y := tmul R x y
lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n :=
eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $
group.in_closure.basic $ or.inl $ ⟨m₁, m₂, n, rfl⟩
lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ :=
eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $
group.in_closure.basic $ or.inr $ or.inl $ ⟨m, n₁, n₂, rfl⟩
lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) :=
sub_eq_zero.1 $ eq.symm $ quotient.sound $
group.in_closure.basic $ or.inr $ or.inr $ ⟨r, m, n, rfl⟩
local attribute [instance] quotient_add_group.is_add_group_hom_quotient_lift
def smul.aux (r : R) : free_abelian_group (M × N) → M ⊗[R] N :=
free_abelian_group.lift (λ (y : M × N), (r • y.1) ⊗ₜ y.2)
instance (r : R) : is_add_group_hom (smul.aux r : _ → M ⊗ N) :=
by unfold smul.aux; apply_instance
instance : has_scalar R (M ⊗ N) :=
⟨λ r, quotient_add_group.lift _ (smul.aux r) $ λ x hx, begin
refine (is_add_group_hom.mem_ker (smul.aux r : _ → M ⊗ N)).1
(add_group.closure_subset _ hx),
clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩);
simp only [smul.aux, is_add_group_hom.mem_ker, -sub_eq_add_neg,
sub_self, add_tmul, tmul_add, smul_tmul,
smul_add, smul_smul, mul_comm, free_abelian_group.lift.of,
free_abelian_group.lift.add, free_abelian_group.lift.sub]
end⟩
instance smul.is_add_group_hom (r : R) : is_add_group_hom ((•) r : M ⊗[R] N → M ⊗[R] N) :=
by unfold has_scalar.smul; apply_instance
protected theorem smul_add (r : R) (x y : M ⊗[R] N) :
r • (x + y) = r • x + r • y :=
is_add_hom.map_add _ _ _
instance : module R (M ⊗ N) := module.of_core
{ smul := (•),
smul_add := tensor_product.smul_add,
add_smul := begin
intros r s x,
apply quotient_add_group.induction_on' x,
intro z,
symmetry,
refine @free_abelian_group.lift.unique _ _ _ _ _ (is_add_group_hom.mk' $ λ p q, _) _ z,
{ simp [tensor_product.smul_add] },
rintro ⟨m, n⟩,
change (r • m) ⊗ₜ n + (s • m) ⊗ₜ n = ((r + s) • m) ⊗ₜ n,
rw [add_smul, add_tmul]
end,
mul_smul := begin
intros r s x,
apply quotient_add_group.induction_on' x,
intro z,
symmetry,
refine @free_abelian_group.lift.unique _ _ _ _ _
(is_add_group_hom.mk' $ λ p q, _) _ z,
{ simp [tensor_product.smul_add] },
rintro ⟨m, n⟩,
change r • s • (m ⊗ₜ n) = ((r * s) • m) ⊗ₜ n,
rw mul_smul, refl
end,
one_smul := λ x, quotient.induction_on x $ λ _,
eq.symm $ free_abelian_group.lift.unique _ _ $ λ ⟨p, q⟩,
by rw one_smul; refl }
@[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) :=
(smul_tmul _ _ _).symm
variables (R M N)
def mk : M →ₗ N →ₗ M ⊗ N :=
linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul
variables {R M N}
@[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl
lemma zero_tmul (n : N) : (0 ⊗ₜ[R] n : M ⊗ N) = 0 := (mk R M N).map_zero₂ _
lemma tmul_zero (m : M) : (m ⊗ₜ[R] 0 : M ⊗ N) = 0 := (mk R M N _).map_zero
lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := (mk R M N).map_neg₂ _ _
lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _
end module
local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup
@[elab_as_eliminator]
protected theorem induction_on
{C : (M ⊗[R] N) → Prop}
(z : M ⊗[R] N)
(C0 : C 0)
(C1 : ∀ x y, C $ x ⊗ₜ[R] y)
(Cp : ∀ x y, C x → C y → C (x + y)) : C z :=
quotient.induction_on z $ λ x, free_abelian_group.induction_on x
C0 (λ ⟨p, q⟩, C1 p q)
(λ ⟨p, q⟩ _, show C (-(p ⊗ₜ q)), by rw ← neg_tmul; from C1 (-p) q)
(λ _ _, Cp _ _)
section UMP
variables {M N P Q}
variables (f : M →ₗ[R] N →ₗ[R] P)
local attribute [instance] free_abelian_group.lift.is_add_group_hom
def lift_aux : (M ⊗[R] N) → P :=
quotient_add_group.lift _
(free_abelian_group.lift $ λ z, f z.1 z.2) $ λ x hx,
begin
refine (is_add_group_hom.mem_ker _).1 (add_group.closure_subset _ hx),
clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩);
simp [is_add_group_hom.mem_ker, -sub_eq_add_neg,
f.map_add, f.map_add₂, f.map_smul, f.map_smul₂, sub_self],
end
variable {f}
local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup
@[simp] lemma lift_aux.add (x y) : lift_aux f (x + y) = lift_aux f x + lift_aux f y :=
quotient.induction_on₂ x y $ λ m n, free_abelian_group.lift.add _ _ _
@[simp] lemma lift_aux.smul (r:R) (x) : lift_aux f (r • x) = r • lift_aux f x :=
tensor_product.induction_on _ _ x (smul_zero _).symm
(λ p q, by rw [← tmul_smul]; simp [lift_aux, tmul])
(λ p q ih1 ih2, by simp [@smul_add _ _ _ _ _ _ p _,
lift_aux.add, ih1, ih2, smul_add])
variable (f)
def lift : M ⊗ N →ₗ P :=
{ to_fun := lift_aux f,
add := lift_aux.add,
smul := lift_aux.smul }
variable {f}
@[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y :=
zero_add _
@[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y :=
lift.tmul _ _
theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) :
g = lift f :=
linear_map.ext $ λ z, begin
apply quotient_add_group.induction_on' z,
intro z,
refine @free_abelian_group.lift.unique _ _ _ _ _ (is_add_group_hom.mk' $ λ p q, _) _ z,
{ simp [g.2] },
exact λ ⟨m, n⟩, H m n
end
theorem lift_mk : lift (mk R M N) = linear_map.id :=
eq.symm $ lift.unique $ λ x y, rfl
theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) :=
eq.symm $ lift.unique $ λ x y, by simp
theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f :=
by rw [lift_compr₂, lift_mk, linear_map.comp_id]
theorem ext {g h : (M ⊗[R] N) →ₗ[R] P}
(H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h :=
by rw ← lift_mk_compr₂ h; exact lift.unique H
theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P}
(H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h :=
by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂]
example : M → N → (M → N → P) → P :=
λ m, flip $ λ f, f m
variables (R M N P)
def uncurry : (M →ₗ N →ₗ[R] P) →ₗ M ⊗ N →ₗ P :=
linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp linear_map.id.flip
variables {R M N P}
@[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
uncurry R M N P f (m ⊗ₜ n) = f m n :=
by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl
variables (R M N P)
def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) :=
{ inv_fun := λ f, (mk R M N).compr₂ f,
left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _,
right_inv := λ f, ext $ λ m n, lift.tmul _ _,
.. uncurry R M N P }
def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P :=
(lift.equiv R M N P).symm
variables {R M N P}
@[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) :
lcurry R M N P f m n = f (m ⊗ₜ n) := rfl
def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f
@[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) :
curry f m n = f (m ⊗ₜ n) := rfl
end UMP
variables {M N}
protected def lid : R ⊗ M ≃ₗ M :=
linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1)
(linear_map.ext $ λ _, by simp)
(ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one])
protected def comm : M ⊗ N ≃ₗ N ⊗ M :=
linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip)
(ext $ λ m n, rfl)
(ext $ λ m n, rfl)
open linear_map
protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) :=
begin
refine linear_equiv.of_linear
(lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _)
(lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _)
(mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _)
(mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _);
repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|>
rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|>
rw uncurry_apply <|> rw curry_apply <|> rw id_apply }
end
def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ P ⊗ Q :=
lift $ comp (compl₂ (mk _ _ _) g) f
@[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q :=
linear_equiv.of_linear (map f g) (map f.symm g.symm)
(ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply])
(ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply])
variables (ι₁ : Type*) (ι₂ : Type*)
variables [decidable_eq ι₁] [decidable_eq ι₂]
variables (β₁ : ι₁ → Type*) (β₂ : ι₂ → Type*)
variables [Π i₁, add_comm_group (β₁ i₁)] [Π i₂, add_comm_group (β₂ i₂)]
variables [Π i₁, module R (β₁ i₁)] [Π i₂, module R (β₂ i₂)]
def direct_sum : direct_sum ι₁ β₁ ⊗[R] direct_sum ι₂ β₂
≃ₗ[R] direct_sum (ι₁ × ι₂) (λ i, β₁ i.1 ⊗[R] β₂ i.2) :=
begin
refine linear_equiv.of_linear
(lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂,
flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, β₁ i.1 ⊗[R] β₂ i.2) (i₁, i₂))
(direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _))
(linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $
linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _)
(mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁,
linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _);
repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|>
rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|>
rw curry_apply },
cases i; refl
end
end tensor_product
|
b55d0e5d12517dbb2e433a93884895203718db6d | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/list/nat_antidiagonal.lean | baa368e6e35a5ce88dcc312df15912f280c8735f | [
"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 | 2,300 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.list.range
/-!
# Antidiagonals in ℕ × ℕ as lists
This file defines the antidiagonals of ℕ × ℕ as lists: the `n`-th antidiagonal is the list of
pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more
generally for sums going from `0` to `n`.
## Notes
Files `data.multiset.nat_antidiagonal` and `data.finset.nat_antidiagonal` successively turn the
`list` definition we have here into `multiset` and `finset`.
-/
open list function nat
namespace list
namespace nat
/-- The antidiagonal of a natural number `n` is the list of pairs `(i, j)` such that `i + j = n`. -/
def antidiagonal (n : ℕ) : list (ℕ × ℕ) :=
(range (n+1)).map (λ i, (i, n - i))
/-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
begin
rw [antidiagonal, mem_map], split,
{ rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_tsub_cancel_of_le hi },
{ rintro rfl, refine ⟨x.fst, _, _⟩,
{ rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ },
{ exact prod.ext rfl (add_tsub_cancel_left _ _) } }
end
/-- The length of the antidiagonal of `n` is `n + 1`. -/
@[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 :=
by rw [antidiagonal, length_map, length_range]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] :=
rfl
/-- The antidiagonal of `n` does not contain duplicate entries. -/
lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
nodup_map (@left_inverse.injective ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _)
@[simp] lemma antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) = (0, n + 1) :: ((antidiagonal n).map (prod.map nat.succ id) ) :=
begin
simp only [antidiagonal, range_succ_eq_map, map_cons, true_and, nat.add_succ_sub_one, add_zero,
id.def, eq_self_iff_true, tsub_zero, map_map, prod.map_mk],
apply congr (congr rfl _) rfl,
ext; simp,
end
end nat
end list
|
57e8d468b71121ae25837b9b16de30393187034d | 4fa161becb8ce7378a709f5992a594764699e268 | /src/linear_algebra/bilinear_form.lean | 0e83e49bc614f7a3ac3a44bac9d98db2961222a6 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 25,630 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Andreas Swerdlow
-/
import linear_algebra.matrix
import linear_algebra.tensor_product
/-!
# Bilinear form
This file defines a bilinear form over a module. Basic ideas
such as orthogonality are also introduced, as well as reflexivive,
symmetric and alternating bilinear forms. Adjoints of linear maps
with respect to a bilinear form are also introduced.
A bilinear form on an R-module M, is a function from M x M to R,
that is linear in both arguments
## Notations
Given any term B of type bilin_form, due to a coercion, can use
the notation B x y to refer to the function field, ie. B x y = B.bilin x y.
## References
* <https://en.wikipedia.org/wiki/Bilinear_form>
## Tags
Bilinear form,
-/
open_locale big_operators
universes u v w
/-- A bilinear form over a module -/
structure bilin_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] :=
(bilin : M → M → R)
(bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z)
(bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y))
(bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z)
(bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y))
/-- A map with two arguments that is linear in both is a bilinear form -/
def linear_map.to_bilin {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M]
(f : M →ₗ[R] M →ₗ[R] R) : bilin_form R M :=
{ bilin := λ x y, f x y,
bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z,
bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul},
bilin_add_right := λ x y z, linear_map.map_add (f x) y z,
bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y }
namespace bilin_form
variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
instance : has_coe_to_fun (bilin_form R M) :=
⟨_, λ B, B.bilin⟩
@[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) :
(bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f :=
rfl
lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y'
| _ _ _ _ rfl rfl := rfl
lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z
lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y
lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z
lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y
lemma zero_left (x : M) :
B 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]}
lemma zero_right (x : M) :
B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, ring.zero_mul]
lemma neg_left (x y : M) :
B (-x) y = -(B x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul]
lemma neg_right (x y : M) :
B x (-y) = -(B x y) := by rw [←@neg_one_smul R _ _, smul_right, neg_one_mul]
lemma sub_left (x y z : M) :
B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl
lemma sub_right (x y z : M) :
B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl
variable {D : bilin_form R M}
@[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _}
instance : add_comm_group (bilin_form R M) :=
{ add := λ B D, { bilin := λ x y, B x y + D x y,
bilin_add_left := λ x y z, by {rw add_left, rw add_left, ac_refl},
bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]},
bilin_add_right := λ x y z, by {rw add_right, rw add_right, ac_refl},
bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} },
add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc},
zero := { bilin := λ x y, 0,
bilin_add_left := λ x y z, (add_zero 0).symm,
bilin_smul_left := λ a x y, (mul_zero a).symm,
bilin_add_right := λ x y z, (zero_add 0).symm,
bilin_smul_right := λ a x y, (mul_zero a).symm },
zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add},
add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero},
neg := λ B, { bilin := λ x y, - (B.1 x y),
bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add],
bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm],
bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add],
bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] },
add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self},
add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} }
lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl
lemma neg_apply (x y : M) : (-B) x y = -(B x y) := rfl
instance : inhabited (bilin_form R M) := ⟨0⟩
section
variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] (F : bilin_form R₂ M) (f : M → M)
instance to_module : module R₂ (bilin_form R₂ M) :=
{ smul := λ c B,
{ bilin := λ x y, c * B x y,
bilin_add_left := λ x y z,
by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]},
bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]},
bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_add_right, left_distrib]},
bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} },
smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib},
add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib},
mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc},
one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul},
zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul},
smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} }
lemma smul_apply (a : R₂) (x y : M) : (a • F) x y = a • (F x y) := rfl
/-- `B.to_linear_map` applies B on the left argument, then the right. -/
def to_linear_map : M →ₗ[R₂] M →ₗ[R₂] R₂ :=
linear_map.mk₂ R₂ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F)
/-- Bilinear forms are equivalent to maps with two arguments that is linear in both. -/
def bilin_linear_map_equiv : (bilin_form R₂ M) ≃ₗ[R₂] (M →ₗ[R₂] M →ₗ[R₂] R₂) :=
{ to_fun := to_linear_map,
map_add' := λ B D, rfl,
map_smul' := λ a B, rfl,
inv_fun := linear_map.to_bilin,
left_inv := λ B, by {ext, refl},
right_inv := λ B, by {ext, refl} }
@[norm_cast]
lemma coe_fn_to_linear_map (x : M) : ⇑(F.to_linear_map x) = F x := rfl
lemma map_sum_left {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (w : M) :
B (∑ i in t, g i) w = ∑ i in t, B (g i) w :=
show B.to_linear_map (∑ i in t, g i) w = ∑ i in t, B.to_linear_map (g i) w,
by rw [B.to_linear_map.map_sum, linear_map.coe_fn_sum, finset.sum_apply]
lemma map_sum_right {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (v : M) :
B v (∑ i in t, g i) = ∑ i in t, B v (g i) :=
(B.to_linear_map v).map_sum
end
section comp
variables {N : Type w} [add_comm_group N] [module R N]
/-- Apply a linear map on the left and right argument of a bilinear form. -/
def comp (B : bilin_form R N) (l r : M →ₗ[R] N) : bilin_form R M :=
{ bilin := λ x y, B (l x) (r y),
bilin_add_left := λ x y z, by simp [add_left],
bilin_smul_left := λ x y z, by simp [smul_left],
bilin_add_right := λ x y z, by simp [add_right],
bilin_smul_right := λ x y z, by simp [smul_right] }
/-- Apply a linear map to the left argument of a bilinear form. -/
def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp f linear_map.id
/-- Apply a linear map to the right argument of a bilinear form. -/
def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp linear_map.id f
@[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_left l).comp_right r = B.comp l r := rfl
@[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_right r).comp_left l = B.comp l r := rfl
@[simp] lemma comp_apply (B : bilin_form R N) (l r : M →ₗ[R] N) (v w) :
B.comp l r v w = B (l v) (r w) := rfl
@[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_left f v w = B (f v) w := rfl
@[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_right f v w = B v (f w) := rfl
end comp
section lin_mul_lin
variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] {N : Type w} [add_comm_group N] [module R₂ N]
/-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/
def lin_mul_lin (f g : M →ₗ[R₂] R₂) : bilin_form R₂ M :=
{ bilin := λ x y, f x * g y,
bilin_add_left := λ x y z, by simp [add_mul],
bilin_smul_left := λ x y z, by simp [mul_assoc],
bilin_add_right := λ x y z, by simp [mul_add],
bilin_smul_right := λ x y z, by simp [mul_left_comm] }
variables {f g : M →ₗ[R₂] R₂}
@[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl
@[simp] lemma lin_mul_lin_comp (l r : N →ₗ[R₂] M) :
(lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) :=
rfl
@[simp] lemma lin_mul_lin_comp_left (l : M →ₗ[R₂] M) :
(lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g :=
rfl
@[simp] lemma lin_mul_lin_comp_right (r : M →ₗ[R₂] M) :
(lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) :=
rfl
end lin_mul_lin
/-- The proposition that two elements of a bilinear form space are orthogonal -/
def is_ortho (B : bilin_form R M) (x y : M) : Prop :=
B x y = 0
lemma ortho_zero (x : M) :
is_ortho B (0 : M) x := zero_left x
section
variables {R₃ : Type*} [domain R₃] [module R₃ M] {G : bilin_form R₃ M}
theorem ortho_smul_left {x y : M} {a : R₃} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G (a • x) y) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_left, H, ring.mul_zero] },
{ rw [smul_left, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }}
end
theorem ortho_smul_right {x y : M} {a : R₃} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G x (a • y)) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_right, H, ring.mul_zero] },
{ rw [smul_right, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }}
end
end
end bilin_form
section matrix
variables {R : Type u} [comm_ring R]
variables {n o : Type w} [fintype n] [fintype o]
open bilin_form finset matrix
open_locale matrix
/-- The linear map from `matrix n n R` to bilinear forms on `n → R`. -/
def matrix.to_bilin_formₗ : matrix n n R →ₗ[R] bilin_form R (n → R) :=
{ to_fun := λ M,
{ bilin := λ v w, (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩,
bilin_add_left := λ x y z, by simp [matrix.add_mul],
bilin_smul_left := λ a x y, by simp,
bilin_add_right := λ x y z, by simp [matrix.mul_add],
bilin_smul_right := λ a x y, by simp },
map_add' := λ f g, by { ext, simp [add_apply, matrix.mul_add, matrix.add_mul] },
map_smul' := λ f g, by { ext, simp [smul_apply] } }
/-- The map from `matrix n n R` to bilinear forms on `n → R`. -/
def matrix.to_bilin_form : matrix n n R → bilin_form R (n → R) :=
matrix.to_bilin_formₗ.to_fun
lemma matrix.to_bilin_form_apply (M : matrix n n R) (v w : n → R) :
(M.to_bilin_form : (n → R) → (n → R) → R) v w = (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩ := rfl
variables [decidable_eq n] [decidable_eq o]
/-- The linear map from bilinear forms on `n → R` to `matrix n n R`. -/
def bilin_form.to_matrixₗ : bilin_form R (n → R) →ₗ[R] matrix n n R :=
{ to_fun := λ B i j, B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0),
map_add' := λ f g, rfl,
map_smul' := λ f g, rfl }
/-- The map from bilinear forms on `n → R` to `matrix n n R`. -/
def bilin_form.to_matrix : bilin_form R (n → R) → matrix n n R :=
bilin_form.to_matrixₗ.to_fun
lemma bilin_form.to_matrix_apply (B : bilin_form R (n → R)) (i j : n) :
B.to_matrix i j = B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0) := rfl
lemma bilin_form.to_matrix_smul (B : bilin_form R (n → R)) (x : R) :
(x • B).to_matrix = x • B.to_matrix :=
by { ext, refl }
open bilin_form
lemma bilin_form.to_matrix_comp (B : bilin_form R (n → R)) (l r : (o → R) →ₗ[R] (n → R)) :
(B.comp l r).to_matrix = l.to_matrixᵀ ⬝ B.to_matrix ⬝ r.to_matrix :=
begin
ext i j,
simp only [to_matrix_apply, comp_apply, mul_val, sum_mul],
have sum_smul_eq : Π (f : (o → R) →ₗ[R] (n → R)) (i : o),
f (λ n, ite (n = i) 1 0) = ∑ k, f.to_matrix k i • λ n, ite (n = k) (1 : R) 0,
{ intros f i,
ext j,
change f (λ n, ite (n = i) 1 0) j = (∑ k, λ n, f.to_matrix k i * ite (n = k) (1 : R) 0) j,
simp [linear_map.to_matrix, linear_map.to_matrixₗ, eq_comm] },
simp_rw [sum_smul_eq, map_sum_right, map_sum_left, smul_right, mul_comm, smul_left],
refl
end
lemma bilin_form.to_matrix_comp_left (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) :
(B.comp_left f).to_matrix = f.to_matrixᵀ ⬝ B.to_matrix :=
by simp [comp_left, bilin_form.to_matrix_comp]
lemma bilin_form.to_matrix_comp_right (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) :
(B.comp_right f).to_matrix = B.to_matrix ⬝ f.to_matrix :=
by simp [comp_right, bilin_form.to_matrix_comp]
lemma bilin_form.mul_to_matrix_mul (B : bilin_form R (n → R)) (M : matrix o n R) (N : matrix n o R) :
M ⬝ B.to_matrix ⬝ N = (B.comp (Mᵀ.to_lin) (N.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp (Mᵀ.to_lin) (N.to_lin), to_lin_to_matrix] }
lemma bilin_form.mul_to_matrix (B : bilin_form R (n → R)) (M : matrix n n R) :
M ⬝ B.to_matrix = (B.comp_left (Mᵀ.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp_left (Mᵀ.to_lin), to_lin_to_matrix] }
lemma bilin_form.to_matrix_mul (B : bilin_form R (n → R)) (M : matrix n n R) :
B.to_matrix ⬝ M = (B.comp_right (M.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp_right (M.to_lin), to_lin_to_matrix] }
@[simp] lemma to_matrix_to_bilin_form (B : bilin_form R (n → R)) :
B.to_matrix.to_bilin_form = B :=
begin
ext,
rw [matrix.to_bilin_form_apply, B.mul_to_matrix_mul, bilin_form.to_matrix_apply, comp_apply],
{ apply coe_fn_congr; ext; simp [mul_vec], },
{ apply_instance, },
end
@[simp] lemma to_bilin_form_to_matrix (M : matrix n n R) :
M.to_bilin_form.to_matrix = M :=
by { ext, simp [bilin_form.to_matrix_apply, matrix.to_bilin_form_apply, mul_val], }
/-- Bilinear forms are linearly equivalent to matrices. -/
def bilin_form_equiv_matrix : bilin_form R (n → R) ≃ₗ[R] matrix n n R :=
{ inv_fun := matrix.to_bilin_form,
left_inv := to_matrix_to_bilin_form,
right_inv := to_bilin_form_to_matrix,
..bilin_form.to_matrixₗ }
end matrix
namespace refl_bilin_form
open refl_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is reflexive -/
def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0
variable (H : is_refl B)
lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩
end refl_bilin_form
namespace sym_bilin_form
open sym_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is symmetric -/
def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x
variable (H : is_sym B)
lemma sym (x y : M) : B x y = B y x := H x y
lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H)
end sym_bilin_form
namespace alt_bilin_form
open alt_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is alternating -/
def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0
variable (H : is_alt B)
include H
lemma self_eq_zero (x : M) : B x x = 0 := H x
lemma neg (x y : M) :
- B x y = B y x :=
begin
have H1 : B (x + y) (x + y) = 0,
{ exact self_eq_zero H (x + y) },
rw [add_left, add_right, add_right,
self_eq_zero H, self_eq_zero H, ring.zero_add,
ring.add_zero, add_eq_zero_iff_neg_eq] at H1,
exact H1,
end
end alt_bilin_form
namespace bilin_form
section linear_adjoints
variables {R : Type u} [comm_ring R]
variables {M : Type v} [add_comm_group M] [module R M]
variables {M₂ : Type v} [add_comm_group M₂] [module R M₂]
variables (B B' : bilin_form R M) (B₂ : bilin_form R M₂)
variables (f f' : M →ₗ[R] M₂) (g g' : M₂ →ₗ[R] M)
/-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of
maps between them to be mutually adjoint. -/
def is_adjoint_pair := ∀ ⦃x y⦄, B₂ (f x) y = B x (g y)
variables {B B' B₂ f f' g g'}
lemma is_adjoint_pair.eq (h : is_adjoint_pair B B₂ f g) :
∀ {x y}, B₂ (f x) y = B x (g y) := h
lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) :
is_adjoint_pair B B' f g ↔ B'.comp_left f = B.comp_right g :=
begin
split; intros h,
{ ext x y, rw [comp_left_apply, comp_right_apply], apply h, },
{ intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, },
end
lemma is_adjoint_pair_zero : is_adjoint_pair B B₂ 0 0 :=
λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply]
lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl
lemma is_adjoint_pair.add (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') :
is_adjoint_pair B B₂ (f + f') (g + g') :=
λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h']
lemma is_adjoint_pair.sub (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') :
is_adjoint_pair B B₂ (f - f') (g - g') :=
λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h']
lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B₂ f g) :
is_adjoint_pair B B₂ (c • f) (c • g) :=
λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h]
lemma is_adjoint_pair.comp {M₃ : Type v} [add_comm_group M₃] [module R M₃] {B₃ : bilin_form R M₃}
{f' : M₂ →ₗ[R] M₃} {g' : M₃ →ₗ[R] M₂}
(h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B₂ B₃ f' g') :
is_adjoint_pair B B₃ (f'.comp f) (g.comp g') :=
λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h]
lemma is_adjoint_pair.mul
{f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') :
is_adjoint_pair B B (f * f') (g' * g) :=
λ x y, by rw [linear_map.mul_app, linear_map.mul_app, h, h']
variables (B B' B₂)
/-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms
on the underlying module. In the case that these two forms are identical, this is the usual concept
of self adjointness. In the case that one of the forms is the negation of the other, this is the
usual concept of skew adjointness. -/
def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B B' f f
/-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/
def is_pair_self_adjoint_submodule : submodule R (module.End R M) :=
{ carrier := { f | is_pair_self_adjoint B B' f },
zero_mem' := is_adjoint_pair_zero,
add_mem' := λ f g hf hg, hf.add hg,
smul_mem' := λ c f h, h.smul c, }
/-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an
adjoint for itself. -/
def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f
/-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation
serves as an adjoint. -/
def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f)
lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) :
B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f :=
show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y),
by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right]
/-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Jordan subalgebra.) -/
def self_adjoint_submodule := is_pair_self_adjoint_submodule B B
@[simp] lemma mem_self_adjoint_submodule (f : module.End R M) :
f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl
/-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Lie subalgebra.) -/
def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B
@[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) :
f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f :=
by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, }
end linear_adjoints
end bilin_form
section matrix_adjoints
open_locale matrix
variables {R : Type u} [comm_ring R]
variables {n : Type w} [fintype n]
variables (J J₂ A B : matrix n n R)
/-- The condition for the square matrices `A`, `B` to be an adjoint pair with respect to the square
matrices `J`, `J₂`. -/
def matrix.is_adjoint_pair := Aᵀ ⬝ J₂ = J ⬝ B
/-- The condition for a square matrix `A` to be self-adjoint with respect to the square matrix
`J`. -/
def matrix.is_self_adjoint := matrix.is_adjoint_pair J J A A
/-- The condition for a square matrix `A` to be skew-adjoint with respect to the square matrix
`J`. -/
def matrix.is_skew_adjoint := matrix.is_adjoint_pair J J A (-A)
lemma matrix_is_adjoint_pair_bilin_form :
matrix.is_adjoint_pair J J₂ A B ↔
bilin_form.is_adjoint_pair J.to_bilin_form J₂.to_bilin_form A.to_lin B.to_lin :=
begin
classical,
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R (n → R)), B = B' ↔ B.to_matrix = B'.to_matrix := λ B B', by {
split; intros h, { rw h, }, { rw [←to_matrix_to_bilin_form B, h, to_matrix_to_bilin_form B'], }, },
rw [h, J₂.to_bilin_form.to_matrix_comp_left A.to_lin, J.to_bilin_form.to_matrix_comp_right B.to_lin,
to_lin_to_matrix, to_lin_to_matrix, to_bilin_form_to_matrix, to_bilin_form_to_matrix],
refl,
end
variables [decidable_eq n]
/-- Given a pair of square matrices `J`, `J₂` defining bilinear forms on the free module, there
is a natural embedding from the corresponding submodule of pair-self-adjoint endomorphisms into the
module of matrices. -/
def pair_self_adjoint_matrices_linear_embedding :
bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form →ₗ[R] matrix n n R :=
linear_equiv_matrix'.to_linear_map.comp
(bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form).subtype
lemma pair_self_adjoint_matrices_linear_embedding_apply
(f : bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form) :
(pair_self_adjoint_matrices_linear_embedding J J₂ : _ →ₗ _) f = (f : module.End R (n → R)).to_matrix := rfl
lemma pair_self_adjoint_matrices_linear_embedding_injective :
function.injective (pair_self_adjoint_matrices_linear_embedding J J₂) :=
λ f g h, by { apply set_coe.ext, exact linear_equiv_matrix'.injective h, }
/-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to
given matrices `J`, `J₂`. -/
def pair_self_adjoint_matrices_submodule : submodule R (matrix n n R) :=
(pair_self_adjoint_matrices_linear_embedding J J₂).range
@[simp] lemma mem_pair_self_adjoint_matrices_submodule :
A ∈ (pair_self_adjoint_matrices_submodule J J₂) ↔ matrix.is_adjoint_pair J J₂ A A :=
begin
change A ∈ (pair_self_adjoint_matrices_linear_embedding J J₂).range ↔ matrix.is_adjoint_pair J J₂ A A,
rw [matrix_is_adjoint_pair_bilin_form, linear_map.mem_range],
simp only [pair_self_adjoint_matrices_linear_embedding_apply], split,
{ rintros ⟨⟨A', hA'⟩, h⟩, rw ←h, rw to_matrix_to_lin, exact hA', },
{ intros h, exact ⟨⟨A.to_lin, h⟩, to_lin_to_matrix⟩, },
end
/-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def self_adjoint_matrices_submodule : submodule R (matrix n n R) :=
pair_self_adjoint_matrices_submodule J J
/-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def skew_adjoint_matrices_submodule : submodule R (matrix n n R) :=
pair_self_adjoint_matrices_submodule (-J) J
end matrix_adjoints
|
c4ca9eacd3466642982fabb714435ca55362fb24 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/apply_auto_opt.lean | 0827d2300b10f2489d78730be98d9be00007ddbb | [
"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 | 333 | lean | def p (a : nat) (b := tt) : nat :=
a + cond b 1 2
def q (a b : nat) (h : a ≠ b . tactic.contradiction) : nat :=
a + b
def val1 : nat :=
begin
refine @p _ _,
exact 2,
apply_opt_param
end
example : val1 = 3 :=
rfl
def val2 : nat :=
begin
fapply @q,
exact 1,
exact 0,
apply_auto_param
end
example : val2 = 1 :=
rfl
|
094a60f0d3e95d08c09a1fa8d4e989c9b3848517 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/metric_space/baire.lean | cdfeb57f517e89ff50c0efe2f40eb12b53459e65 | [] | 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 | 7,293 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.specific_limits
import Mathlib.order.filter.countable_Inter
import Mathlib.topology.G_delta
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Baire theorem
In a complete metric space, a countable intersection of dense open subsets is dense.
The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection
of open sets. Then Baire theorem can also be formulated as the fact that a countable
intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different
formulations that can be handy. We also prove the important consequence that, if the space is
covered by a countable union of closed sets, then the union of their interiors is dense.
The names of the theorems do not contain the string "Baire", but are instead built from the form of
the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches.
We also define the filter `residual α` generated by dense `Gδ` sets and prove that this filter
has the countable intersection property.
-/
/-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when
the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any
encodable source space). -/
theorem dense_Inter_of_open_nat {α : Type u_1} [emetric_space α] [complete_space α] {f : ℕ → set α} (ho : ∀ (n : ℕ), is_open (f n)) (hd : ∀ (n : ℕ), dense (f n)) : dense (set.Inter fun (n : ℕ) => f n) := sorry
/-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/
theorem dense_sInter_of_open {α : Type u_1} [emetric_space α] [complete_space α] {S : set (set α)} (ho : ∀ (s : set α), s ∈ S → is_open s) (hS : set.countable S) (hd : ∀ (s : set α), s ∈ S → dense s) : dense (⋂₀S) := sorry
/-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with
an index set which is a countable set in any type. -/
theorem dense_bInter_of_open {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] {S : set β} {f : β → set α} (ho : ∀ (s : β), s ∈ S → is_open (f s)) (hS : set.countable S) (hd : ∀ (s : β), s ∈ S → dense (f s)) : dense (set.Inter fun (s : β) => set.Inter fun (H : s ∈ S) => f s) := sorry
/-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with
an index set which is an encodable type. -/
theorem dense_Inter_of_open {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] [encodable β] {f : β → set α} (ho : ∀ (s : β), is_open (f s)) (hd : ∀ (s : β), dense (f s)) : dense (set.Inter fun (s : β) => f s) := sorry
/-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/
theorem dense_sInter_of_Gδ {α : Type u_1} [emetric_space α] [complete_space α] {S : set (set α)} (ho : ∀ (s : set α), s ∈ S → is_Gδ s) (hS : set.countable S) (hd : ∀ (s : set α), s ∈ S → dense s) : dense (⋂₀S) := sorry
/-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with
an index set which is an encodable type. -/
theorem dense_Inter_of_Gδ {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] [encodable β] {f : β → set α} (ho : ∀ (s : β), is_Gδ (f s)) (hd : ∀ (s : β), dense (f s)) : dense (set.Inter fun (s : β) => f s) := sorry
/-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with
an index set which is a countable set in any type. -/
theorem dense_bInter_of_Gδ {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] {S : set β} {f : (x : β) → x ∈ S → set α} (ho : ∀ (s : β) (H : s ∈ S), is_Gδ (f s H)) (hS : set.countable S) (hd : ∀ (s : β) (H : s ∈ S), dense (f s H)) : dense (set.Inter fun (s : β) => set.Inter fun (H : s ∈ S) => f s H) := sorry
/-- Baire theorem: the intersection of two dense Gδ sets is dense. -/
theorem dense.inter_of_Gδ {α : Type u_1} [emetric_space α] [complete_space α] {s : set α} {t : set α} (hs : is_Gδ s) (ht : is_Gδ t) (hsc : dense s) (htc : dense t) : dense (s ∩ t) := sorry
/-- A property holds on a residual (comeagre) set if and only if it holds on some dense `Gδ` set. -/
theorem eventually_residual {α : Type u_1} [emetric_space α] [complete_space α] {p : α → Prop} : filter.eventually (fun (x : α) => p x) (residual α) ↔ ∃ (t : set α), is_Gδ t ∧ dense t ∧ ∀ (x : α), x ∈ t → p x := sorry
/-- A set is residual (comeagre) if and only if it includes a dense `Gδ` set. -/
theorem mem_residual {α : Type u_1} [emetric_space α] [complete_space α] {s : set α} : s ∈ residual α ↔ ∃ (t : set α), ∃ (H : t ⊆ s), is_Gδ t ∧ dense t := sorry
protected instance residual.countable_Inter_filter {α : Type u_1} [emetric_space α] [complete_space α] : countable_Inter_filter (residual α) := sorry
/-- Baire theorem: if countably many closed sets cover the whole space, then their interiors
are dense. Formulated here with an index set which is a countable set in any type. -/
theorem dense_bUnion_interior_of_closed {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] {S : set β} {f : β → set α} (hc : ∀ (s : β), s ∈ S → is_closed (f s)) (hS : set.countable S) (hU : (set.Union fun (s : β) => set.Union fun (H : s ∈ S) => f s) = set.univ) : dense (set.Union fun (s : β) => set.Union fun (H : s ∈ S) => interior (f s)) := sorry
/-- Baire theorem: if countably many closed sets cover the whole space, then their interiors
are dense. Formulated here with `⋃₀`. -/
theorem dense_sUnion_interior_of_closed {α : Type u_1} [emetric_space α] [complete_space α] {S : set (set α)} (hc : ∀ (s : set α), s ∈ S → is_closed s) (hS : set.countable S) (hU : ⋃₀S = set.univ) : dense (set.Union fun (s : set α) => set.Union fun (H : s ∈ S) => interior s) :=
dense_bUnion_interior_of_closed hc hS (eq.mp (Eq._oldrec (Eq.refl (⋃₀S = set.univ)) set.sUnion_eq_bUnion) hU)
/-- Baire theorem: if countably many closed sets cover the whole space, then their interiors
are dense. Formulated here with an index set which is an encodable type. -/
theorem dense_Union_interior_of_closed {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] [encodable β] {f : β → set α} (hc : ∀ (s : β), is_closed (f s)) (hU : (set.Union fun (s : β) => f s) = set.univ) : dense (set.Union fun (s : β) => interior (f s)) := sorry
/-- One of the most useful consequences of Baire theorem: if a countable union of closed sets
covers the space, then one of the sets has nonempty interior. -/
theorem nonempty_interior_of_Union_of_closed {α : Type u_1} {β : Type u_2} [emetric_space α] [complete_space α] [Nonempty α] [encodable β] {f : β → set α} (hc : ∀ (s : β), is_closed (f s)) (hU : (set.Union fun (s : β) => f s) = set.univ) : ∃ (s : β), set.nonempty (interior (f s)) := sorry
|
5124d3908617316d2febab937c16501776518776 | 297c4ceafbbaed2a59b6215504d09e6bf201a2ee | /higman.lean | 42a272ba236717d3392d506311989b1a66b7d091 | [] | no_license | minchaowu/Kruskal.lean3 | 559c91b82033ce44ea61593adcec9cfff725c88d | a14516f47b21e636e9df914fc6ebe64cbe5cd38d | refs/heads/master | 1,611,010,001,429 | 1,497,935,421,000 | 1,497,935,421,000 | 82,000,982 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,490 | lean | import .lemmas .dickson
open classical nat function prod set subtype
noncomputable theory
definition inj_from_to {A B: Type} (f : A → B) (S1 : set A) (S2 : set B) := maps_to f S1 S2 ∧ inj_on f S1
theorem inj_from_to_id {A : Type} (S1 : set A) : (∀ a, a ∈ S1 → id a ∈ S1) ∧ ∀ a₁ a₂, a₁ ∈ S1 → a₂ ∈ S1 → id a₁ = id a₂ → a₁ = a₂ :=
begin split, intros, simp, assumption, intros; assumption end
theorem inj_from_to_compose {A B C : Type} {g : B → C} {f : A → B} {S1 : set A} {S2 : set B} {S3 : set C}
(Hg : inj_from_to g S2 S3) (Hf : inj_from_to f S1 S2) : inj_from_to (g ∘ f) S1 S3 :=
have Hl : ∀ a, a ∈ S1 → g (f a) ∈ S3, from λ a Ha, Hg^.left (Hf^.left Ha),
have ∀ a₁ a₂, a₁ ∈ S1 → a₂ ∈ S1 → g (f a₁) = g (f a₂) → a₁ = a₂, from
λ a₁ a₂ Ha₁ Ha₂ Heq,
have in1 : f a₁ ∈ S2, from Hf^.left Ha₁,
have in2 : f a₂ ∈ S2, from Hf^.left Ha₂,
have f a₁ = f a₂, from Hg^.right in1 in2 Heq,
Hf^.right Ha₁ Ha₂ this,
⟨Hl, this⟩
theorem gt_of_gt_pred {a b : ℕ} (H : pred b < a) : b ≤ a :=
by_cases
(suppose b = 0, by simp [this,zero_le])
(suppose b ≠ 0,
have ∃ k, b = succ k, from exists_eq_succ_of_ne_zero this,
let ⟨k,hk⟩ := this in
have pred (succ k) < a, by rw hk at H;exact H,
have k < a, by super,
have succ k ≤ a, from succ_le_of_lt this,
by simp [this, hk])
theorem sub_gt_of_gt_ge {a b c : ℕ} (H1 : a > b) (H2 : b ≥ c) : a - c > b - c :=
have c ≤ a, from le_of_lt (lt_of_le_of_lt H2 H1),
have eq₁ : a - c + c = a, from nat.sub_add_cancel this,
have eq₂ : b - c + c = b, from nat.sub_add_cancel H2,
have b ≤ a, from le_of_lt H1,
have b - c ≤ a - c, from nat.sub_le_sub_right this c,
or.elim (nat.lt_or_eq_of_le this)
(assume Hl, Hl)
(assume Hr, have refl : a > a, by super,
absurd refl (lt_irrefl a))
theorem lt_pred_nonzero_self {n : ℕ} (H : n ≠ 0) : pred n < n :=
have ∃ k, n = succ k, from exists_eq_succ_of_ne_zero H,
let ⟨k,hk⟩ := this in begin simp [hk, self_lt_succ] end
-- theorem ne_empty_of_mem {X : Type} {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ :=
-- begin intro Hs, rw Hs at H, apply set.not_mem_empty _ H end
theorem image_nonempty {A B : Type} {f : A → B} {S : set A} (H : S ≠ ∅) : image f S ≠ ∅ :=
have ∃ s, s ∈ S, from exists_mem_of_ne_empty H,
let ⟨s,h⟩ := this in
have f s ∈ image f S, from ⟨s, ⟨h,rfl⟩⟩,
set.ne_empty_of_mem this
theorem not_mem_singleton {A : Type} (x a : A) (H : x ≠ a) : x ∉ insert a (∅ : set A) :=
suppose x ∈ insert a ∅, H (eq_of_mem_singleton this)
theorem refl_of_diff_of_ins_singleton {A : Type} {a : A} {S : set A} (H : a ∉ S) : S = (insert a S) \ insert a ∅ :=
subset.antisymm
(λ x h, ⟨or.inr h,(λ neg, have x = a, from eq_of_mem_singleton neg,by super)⟩)
(λ x ⟨hl,hr⟩, or.elim hl (λ l,
have x ∈ insert a (∅ : set A), begin rw l, apply mem_singleton end,
by contradiction) (λ r,r))
namespace kruskal
#check good_pairs
section
-- Given a countable set of objects A (which is ordered by f), and assuming that there exists a bad sequence (i.e., f ∘ g) of these objects, we can find a (sub)sequence (f ∘ h) which is bad and ∀ i, h 0 ≤ h i.
parameter {A : Type}
parameter f : ℕ → A
parameter g : ℕ → ℕ
parameter o : A → A → Prop
parameter H : ¬ is_good (f ∘ g) o
definition ran_g : set ℕ := {x : ℕ | ∃ i, g i = x}
theorem ne_empty_ran : ran_g ≠ ∅ := set.ne_empty_of_mem ⟨0,rfl⟩
private definition min : ℕ := least ran_g ne_empty_ran
definition index_of_min : ℕ :=
have min ∈ ran_g, from least_is_mem ran_g ne_empty_ran,
some this
theorem minimality_of_min (n : ℕ) : g index_of_min ≤ g n :=
have H1 : g index_of_min = min, from some_spec (least_is_mem ran_g ne_empty_ran),
have least ran_g ne_empty_ran ≤ g n, from minimality _ (g n) ⟨n,rfl⟩,
begin simp [H1], exact this end
private definition h (n : ℕ) : ℕ := g (index_of_min + n)
theorem exists_sub_bad : ∃ h : ℕ → ℕ, ¬ is_good (f ∘ h) o ∧ ∀ i : ℕ, h 0 ≤ h i :=
have badness : ¬ is_good (f ∘ h) o, from
suppose is_good (f ∘ h) o,
let ⟨i,j,hij⟩ := this in
have index_of_min + i < index_of_min + j, from add_lt_add_left (and.left hij) _,
have is_good (f ∘ g) o, from ⟨index_of_min + i,⟨index_of_min + j,⟨this,hij^.right⟩⟩⟩,
H this,
have ∀ i : ℕ, h 0 ≤ h i, from λ i, minimality_of_min (index_of_min + i),
⟨h,⟨badness,this⟩⟩
end
definition finite_subsets (Q : Type) : Type := {x : set Q // finite x}
definition non_descending {Q : Type} (A B : finite_subsets Q) (o : Q → Q → Prop) (f : Q → Q) := ∀ a : Q, a ∈ A.1 → o a (f a) ∧ f a ∈ B.1
definition star {Q : Type} (o : Q → Q → Prop) (A B : finite_subsets Q) := ∃ f, inj_from_to f A.1 B.1 ∧ non_descending A B o f
definition extends_at {A : Type} (n : ℕ) (f : ℕ → A) (g : ℕ → A) : Prop := ∀ m ≤ n, g m = f m
theorem extends_at.refl {A : Type} {n : ℕ} {f : ℕ → A} : extends_at n f f := λ m H, rfl
theorem extends_at.trans {A : Type} {n m : ℕ} {f g h: ℕ → A} (H1 : extends_at n f g) (H2 : extends_at m g h) (H3 : n ≤ m) :
extends_at n f h := λ k H,
have g k = f k, from H1 k H,
have k ≤ m, from nat.le_trans H H3,
have h k = g k, from H2 k this,
by super
-- definition induced_set_of_exists {A : Type} {P : A → Prop} (H : ∃ x, P x) : set A := {x | P x}
-- theorem nonempty_induced_set {A : Type} {P : A → Prop} (H : ∃ x, P x) : induced_set_of_exists H ≠ ∅ := let ⟨a,h⟩ := H in set.ne_empty_of_mem h
-- theorem property_of_induced_set {A : Type} {P : A → Prop} (H : ∃ x, P x) : ∀ s, s ∈ induced_set_of_exists H → P s :=
-- λ s h, h
theorem least_seq_at_n {S : set (ℕ → ℕ)} (H : S ≠ ∅) (n : ℕ) : ∃ f, f ∈ S ∧ ∀ g, g ∈ S → f n ≤ g n :=
let T : set ℕ := {x | ∃ f, f ∈ S ∧ f n = x} in
have ∃ f, f ∈ S, from exists_mem_of_ne_empty H,
let ⟨f,h⟩ := this in
have nemp : T ≠ ∅, from set.ne_empty_of_mem ⟨f,⟨h,rfl⟩⟩,
let a := least T nemp in
have a ∈ T, from least_is_mem T nemp,
let ⟨f',h⟩ := this in
have ∀ g, g ∈ S → f' n ≤ g n, from λ g Hg,
have a ≤ g n, from minimality _ _ ⟨g,⟨Hg,rfl⟩⟩,
by super,
⟨f',⟨h^.left, this⟩⟩
section
-- given an n, take an f from {f | P f} such that |f n| is as small as possible.
parameter {A : Type}
parameter {P : (ℕ → A) → Prop}
parameter g : A → ℕ -- a function which calculates the cardinality of a : A in some sense.
parameter H : ∃ f : ℕ → A, P f
-- definition card_of_f (f : ℕ → A) (n : ℕ) : ℕ := g (f n)
definition colle : set (ℕ → A) := {f | P f}
lemma nonempty_colle : colle ≠ ∅ := let ⟨a,h⟩ := H in set.ne_empty_of_mem h
definition S : set (ℕ → ℕ) := image (λ f, g ∘ f) colle
lemma nonempty_S : S ≠ ∅ := image_nonempty nonempty_colle
theorem exists_min_func (n : ℕ) : ∃ f, f ∈ S ∧ ∀ g, g ∈ S → f n ≤ g n := least_seq_at_n nonempty_S n
-- let ⟨l,r⟩ := some_spec (exists_min_func n) does not work
definition min_func (n : ℕ) : ℕ → A :=
let fc := some (exists_min_func n) in
have fc ∈ S ∧ ∀ g, g ∈ S → fc n ≤ g n, from (some_spec (exists_min_func n)),
some this^.left
theorem min_func_property (n : ℕ) : P (min_func n) :=
let fc := some (exists_min_func n) in
let ⟨l,r⟩ := some_spec (exists_min_func n) in
have min_func n ∈ colle ∧ (λ f, g ∘ f) (min_func n) = fc, from some_spec l ,
this^.left
-- For every f satisfying P, we have the inequality. Intuitively, it says that |(min_func n) n| is always less than or equal to |f n|.
theorem min_func_minimality (f : ℕ → A) (Hp : P f) (n : ℕ) : g (min_func n n) ≤ g (f n) :=
let fc := some (exists_min_func n) in
let ⟨l,r⟩ := some_spec (exists_min_func n) in
have min_func n ∈ colle ∧ (λ f, g ∘ f) (min_func n) = fc, from some_spec l,
have (λ f, g ∘ f) (min_func n) = fc, from this^.right,
have eq2 : (λ f, g ∘ f) (min_func n) n = fc n, by rw this,
have Hr : ∀ g, g ∈ S → fc n ≤ g n, from (some_spec (exists_min_func n))^.right,
have le : fc n ≤ (λ f, g ∘ f) f n, from Hr _ ⟨f,⟨Hp,rfl⟩⟩,
-- have (λ f, g ∘ f) (min_func n) n = g (min_func n n), from rfl,
-- have (λ f, g ∘ f) f n = g (f n), from rfl,
have (λ f, g ∘ f) (min_func n) n ≤ (λ f, g ∘ f) f n, by rw -eq2 at le;exact le,
by super
end
section
parameter {A : Type}
parameter {P : (ℕ → A) → Prop} -- some property about f
parameter g : A → ℕ -- a measure of cardinality of A
parameter H : ∃ f, P f
-- construct a sequence of functions with property P such that each one extends its predecessor and is the minimal one at n.
noncomputable definition mbs_helper (n : ℕ) : {f : ℕ → A // P f} :=
nat.rec_on n
(let f₀ := min_func g H 0 in
have P f₀, from min_func_property g H 0,
⟨f₀,this⟩)
(λ pred h',
let f' := h'.1 in
have H1 : extends_at pred f' f', from extends_at.refl,
have H2 : P f', from h'.2,
have HP : ∃ f, extends_at pred f' f ∧ P f, from ⟨f',⟨H1,H2⟩⟩,
let fn := min_func g HP (succ pred) in
have extends_at pred f' fn ∧ P fn, from min_func_property g HP (succ pred),
have P fn, from this^.right,
⟨fn,this⟩)
section
parameter n : ℕ
definition helper_elt := (mbs_helper n).1
definition helper_succ := (mbs_helper (succ n)).1
lemma helper_ext_refl : extends_at n helper_elt helper_elt := extends_at.refl
lemma helper_has_property : P helper_elt := (mbs_helper n).2
lemma helper_inner_hyp : ∃ g, extends_at n helper_elt g ∧ P g := ⟨helper_elt, ⟨helper_ext_refl, helper_has_property⟩⟩
theorem succ_ext_of_mbs_helper : extends_at n helper_elt helper_succ := (min_func_property g helper_inner_hyp (succ n))^.left
end
theorem ext_of_mbs_helper (n : ℕ) : ∀ m, m ≤ n → extends_at m (mbs_helper m).1 (mbs_helper n).1 :=
nat.rec_on n
(take m, assume H,
have eq : m = 0, from eq_zero_of_le_zero H,
have extends_at 0 (mbs_helper 0).1 (mbs_helper 0).1, from extends_at.refl,
by simp [eq,this])
(λ a IH m H,
by_cases
(suppose m = succ a,
have extends_at m (mbs_helper (succ a)).1 (mbs_helper (succ a)).1, from extends_at.refl, by super)
(suppose m ≠ succ a,
have m < succ a, from lt_of_le_of_ne H this,
have Hle : m ≤ a, from (iff.mp (lt_succ_iff_le m a)) this,
have H1 : extends_at m (mbs_helper m).1 (mbs_helper a).1, from IH m Hle,
have extends_at a (mbs_helper a).1 (mbs_helper (succ a)).1, from succ_ext_of_mbs_helper a,
extends_at.trans H1 this Hle))
theorem congruence_of_mbs_helper {n m : ℕ} (H : m ≤ n) : (mbs_helper n).1 m = (mbs_helper m).1 m :=
have extends_at m (mbs_helper m).1 (mbs_helper n).1, from ext_of_mbs_helper n m H,
this m (nat.le_refl m)
end
section
-- construction and properties of mbs.
parameter {A : Type}
parameter {o : A → A → Prop}
parameter g : A → ℕ
parameter H : ∃ f : ℕ → A, ¬ is_good f o
noncomputable definition seq_of_bad_seq (n : ℕ) : {f : ℕ → A // ¬ is_good f o} := mbs_helper g H n
definition minimal_bad_seq (n : ℕ) : A := (seq_of_bad_seq n).1 n
definition ext_of_seq_of_bad_seq := ext_of_mbs_helper g H
definition congruence_of_seq_of_bad_seq {n m : ℕ} (Hnm : m ≤ n) := congruence_of_mbs_helper g H Hnm
definition bad_seq_elt := helper_elt g H
definition bad_seq_inner_hyp := helper_inner_hyp g H
theorem badness_of_mbs : ¬ is_good minimal_bad_seq o :=
suppose is_good minimal_bad_seq o,
let ⟨i,j,h⟩ := this in
have i ≤ j, from le_of_lt_or_eq (or.inl h^.left),
have ext : extends_at i (seq_of_bad_seq i).1 (seq_of_bad_seq j).1, from ext_of_seq_of_bad_seq j i this,
have i ≤ i, from nat.le_refl i,
have (seq_of_bad_seq j).1 i = (minimal_bad_seq i), from ext i this,
have o ((seq_of_bad_seq j).1 i) (minimal_bad_seq j), by rw this; exact h^.right,
have i < j ∧ o ((seq_of_bad_seq j).1 i) ((seq_of_bad_seq j).1 j), from ⟨h^.left, this⟩,
have good : is_good (seq_of_bad_seq j).1 o, from ⟨i,⟨j, this⟩⟩,
have ¬ is_good (seq_of_bad_seq j).1 o, from (seq_of_bad_seq j).2,
this good
theorem minimality_of_mbs_0 (f : ℕ → A) (Hf : ¬ is_good f o) : g (minimal_bad_seq 0) ≤ g (f 0) := min_func_minimality g H f Hf 0
theorem minimality_of_mbs (n : ℕ) (f : ℕ → A) (H1 : extends_at n minimal_bad_seq f ∧ ¬ is_good f o) : g (minimal_bad_seq (succ n)) ≤ g (f (succ n)) :=
have Hl : ∀ m, m ≤ n → f m = (bad_seq_elt n) m, from
λ m Hle, have f m = minimal_bad_seq m, from H1^.left m Hle,
have bad_seq_elt n m = minimal_bad_seq m, from congruence_of_seq_of_bad_seq Hle,
by super, --by+ simp,
have ins_P : extends_at n (bad_seq_elt n) f ∧ ¬ is_good f o, from ⟨Hl, H1^.right⟩,
have ineq : g (min_func g (bad_seq_inner_hyp n) (succ n) (succ n)) ≤ g (f (succ n)), from min_func_minimality g (bad_seq_inner_hyp n) f ins_P (succ n),
-- have minimal_bad_seq (succ n) = min_func g (bad_seq_inner_hyp n) (succ n) (succ n), from rfl,
-- by+ rw (eq.symm this) at ineq; exact ineq
by super
end
section
-- Given two sequences f and g, a function h which modifies indices so that h 0 is the break point, construct a new sequence 'combined_seq' by concatenating f and g at (h 0).
parameter {Q :Type}
parameter {o : Q → Q → Prop}
parameters f g : ℕ → Q
parameter h : ℕ → ℕ
parameter Hh : ∀ i, h 0 ≤ h i
parameter Hf : ¬ is_good f o
parameter Hg : ¬ is_good g o
-- in Higman's lemma in Williams 1963, h is f, g is the bad sequence B ∘ f
parameter H : ∀ i j, o (f i) (g (j - h 0)) → o (f i) (f (h (j - h 0)))
-- definition comb (n : ℕ) : Q := if h 0 ≠ 0 ∧ n ≤ pred (h 0) then f n else g (n - (h 0))
-- -- def comb' (n : ℕ) : Q := if n < h 0 then f n else g (n - (h 0))
-- -- theorem g_part_of_comb' (H : (h 0) = 0) : ∀ x, comb' x = g x :=
-- -- λ n, have ¬ n < h 0, by rw H; apply not_lt_zero ,
-- -- have comb' n = g (n - (h 0)), from if_neg this,
-- -- by simp [this, H]
-- theorem g_part_of_comb (H : (h 0) = 0) : ∀ x, comb x = g x :=
-- take n, have ¬ (h 0) ≠ 0, from not_not_intro H,
-- have ¬ ((h 0) ≠ 0 ∧ n ≤ pred (h 0)), from not_and_of_not_left (n ≤ pred (h 0)) this,
-- have comb n = g (n - (h 0)), from if_neg this,
-- by simp [this, H]
-- theorem badness_of_comb : ¬ is_good comb o :=
-- λ good,
-- let ⟨i,j,hw⟩ := good in
-- by_cases
-- (suppose (h 0) = 0,
-- have comb = g, begin apply funext, apply g_part_of_comb, exact this end,
-- have is_good g o, by rw this at good;exact good,
-- Hg this)
-- (assume ne,
-- by_cases
-- (assume Hposi : i ≤ pred (h 0),
-- have eq1i : comb i = f i, from if_pos ⟨ne, Hposi⟩,
-- by_cases
-- (suppose j ≤ pred (h 0),
-- have eq1j : comb j = f j, from if_pos ⟨ne, this⟩,
-- have o (comb i) (comb j), from hw^.right,
-- have o (comb i) (f j), by rw eq1j at this; exact this,
-- have o (f i) (f j), begin rw -eq1i, exact this end,
-- have is_good f o, from ⟨i, ⟨j,⟨hw^.left,this⟩⟩⟩,
-- show _, from Hf this)
-- (suppose ¬ j ≤ pred (h 0),
-- have ¬ ((h 0) ≠ 0 ∧ j ≤ pred (h 0)), from not_and_of_not_right ((h 0) ≠ 0) this,
-- have eq2j : comb j = g (j - (h 0)), from if_neg this,
-- have o (f i) (g (j - (h 0))), begin rw [-eq2j,-eq1i], exact hw^.right end,
-- have Hr : o (f i) (f (h (j - (h 0)))), from H _ _ this,
-- have i < h (j - (h 0)), from
-- have ilth0 : i < h 0, from lt_of_le_of_lt Hposi (lt_pred_nonzero_self ne),
-- have h 0 ≤ h (j - h 0), from Hh (j - h 0),
-- show _, from lt_of_lt_of_le ilth0 this,
-- have is_good f o, from ⟨i, ⟨h (j - h 0), ⟨this, Hr⟩⟩⟩,
-- show _, from Hf this))
-- (assume Hnegi,
-- have iht : pred (h 0) < i, from lt_of_not_ge Hnegi,
-- have ¬ (h 0 ≠ 0 ∧ i ≤ pred (h 0)), from not_and_of_not_right (h 0 ≠ 0) Hnegi,
-- have eq2i : comb i = g (i - h 0), from if_neg this,
-- by_cases
-- (assume Hposj : j ≤ pred (h 0),
-- have j < i, from lt_of_le_of_lt Hposj iht,
-- show _, from (not_lt_of_gt hw^.left) this)
-- (assume Hnegj,
-- have pred (h 0) < j, from lt_of_not_ge Hnegj,
-- have ¬ (h 0 ≠ 0 ∧ j ≤ pred (h 0)), from not_and_of_not_right (h 0 ≠ 0) Hnegj,
-- have eq2j : comb j = g (j - h 0), from if_neg this,
-- have o (comb i) (comb j), from hw^.right,
-- have o (comb i) (g (j - h 0)), begin rw -eq2j, exact this end, --by simp,
-- have Hr2 : o (g (i - h 0)) (g (j - h 0)), begin rw -eq2i, exact this end,-- by simp,
-- have ige : h 0 ≤ i, from gt_of_gt_pred iht,
-- have jgt : h 0 < j, from lt_of_le_of_lt ige hw^.left,
-- have i - h 0 < j - h 0, from
-- or.elim (lt_or_eq_of_le ige)
-- (assume hl, sub_gt_of_gt hw^.left hl)
-- (assume hr, have 0 < j - h 0, from nat.sub_pos_of_lt jgt,
-- have i - h 0 = 0, begin rw hr, apply nat.sub_self end,
-- begin rw this, assumption end),
-- have is_good g o, from ⟨(i - h 0), ⟨(j - h 0),⟨this, Hr2⟩⟩⟩,
-- show _, from Hg this)))
-- new comb --
definition comb (n : ℕ) : Q := if n < h 0 then f n else g (n - h 0)
theorem g_part_of_comb (H : (h 0) = 0) : ∀ x, comb x = g x :=
λ n, have ¬ n < h 0, by rw H; apply not_lt_zero ,
have comb n = g (n - (h 0)), from if_neg this,
by simp [this, H]
include Hh
theorem badness_of_comb : ¬ is_good comb o :=
λ good, let ⟨i,j,hw⟩ := good in
by_cases
(assume Hposi : i < h 0,
have eq1i : comb i = f i, from if_pos Hposi,
by_cases
(suppose j < h 0,
have eq1j : comb j = f j, from if_pos this,
have o (f i) (f j),by rw [-eq1j,-eq1i]; exact hw^.right,
have is_good f o, from ⟨i, ⟨j,⟨hw^.left,this⟩⟩⟩,
show _, from Hf this)
(suppose ¬ j < h 0,
have eq2j : comb j = g (j - (h 0)), from if_neg this,
have o (f i) (g (j - (h 0))), by rw [-eq2j,-eq1i]; exact hw^.right,
have Hr : o (f i) (f (h (j - (h 0)))), from H _ _ this,
have i < h (j - (h 0)), from lt_of_lt_of_le Hposi (Hh _),
have is_good f o, from ⟨i, ⟨h (j - h 0), ⟨this, Hr⟩⟩⟩,
show _, from Hf this))
(assume Hnegi,
have eq2i : comb i = g (i - h 0), from if_neg Hnegi,
by_cases
(suppose j < h 0,
have j < i, from lt_of_lt_of_le this (le_of_not_gt Hnegi),
show _, from (not_lt_of_gt hw^.left) this)
(suppose ¬ j < h 0,
have eq2j : comb j = g (j - h 0), from if_neg this,
have Hr2 : o (g (i - h 0)) (g (j - h 0)), by rw [-eq2i,-eq2j]; exact hw^.right,
have i - h 0 < j - h 0, from sub_gt_of_gt_ge hw^.left (le_of_not_gt Hnegi),
have is_good g o, from ⟨(i - h 0), ⟨(j - h 0),⟨this, Hr2⟩⟩⟩,
show _, from Hg this))
end
section
-- further assume that f is a minimal bad sequence and card (g 0) < card (f (h 0))
-- In other words, this section says, assuming that there is a bad sequence of Q, if g is a bad sequence such that H holds, then there is a contradiction.
parameter {Q :Type}
parameter {o : Q → Q → Prop}
parameters {g : ℕ → Q}
parameter h : ℕ → ℕ
parameter m : Q → ℕ -- a measure of cardinality
parameter Hh : ∀ i, h 0 ≤ h i
parameter Hex : ∃ f, ¬ is_good f o
parameter Hg : ¬ is_good g o
parameter H : ∀ i j, o (minimal_bad_seq m Hex i) (g (j - h 0)) → o (minimal_bad_seq m Hex i) ((minimal_bad_seq m Hex) (h (j - h 0)))
parameter Hbp : m (g 0) < m (minimal_bad_seq m Hex (h 0))
definition comb_seq_with_mbs := comb (minimal_bad_seq m Hex) g h
theorem g_part_of_comb_seq_with_mbs (H1 : (h 0) = 0) : ∀ x, comb_seq_with_mbs x = g x :=
begin apply g_part_of_comb, assumption end
theorem badness_of_comb_seq_with_mbs : ¬ is_good comb_seq_with_mbs o :=
badness_of_comb (minimal_bad_seq m Hex) g h Hh (badness_of_mbs m Hex) Hg H
-- theorem comb_seq_extends_mbs_at_pred_bp (H : h 0 ≠ 0): extends_at (pred (h 0)) (minimal_bad_seq m Hex) comb_seq_with_mbs :=
-- λ m Hm, if_pos ⟨H, Hm⟩
theorem lt_of_le_pred' {n m : ℕ} : n ≤ pred m → n < m ∨ n = 0 :=
nat.rec_on m (λ h, or.elim (lt_or_eq_of_le h) (λ l, by super) (λ r, or.inr r))
(λ a ih h, or.inl (lt_succ_of_le h))
theorem lt_of_le_pred {n m : ℕ} : n ≤ pred m → n < m ∨ m = 0 :=
nat.rec_on m (λ h, or.inr rfl) (λ a ih h, or.inl (lt_succ_of_le h))
theorem comb_seq_extends_mbs_at_pred_bp (H : h 0 ≠ 0): extends_at (pred (h 0)) (minimal_bad_seq m Hex) comb_seq_with_mbs :=
λ m Hm, if_pos (or_resolve_left (lt_of_le_pred Hm) H)
#check succ_le_succ
lemma comb_seq_h0 : comb_seq_with_mbs (h 0) = g 0 :=
have comb_seq_with_mbs (h 0) = g (h 0 - h 0), begin apply if_neg, rw lt_self_iff_false, trivial end,
by simp [this,nat.sub_self]
-- by_cases
-- (suppose h 0 = 0,
-- have comb_seq_with_mbs (h 0) = g (h 0), from g_part_of_comb_seq_with_mbs this (h 0),
-- by super)
-- (suppose h 0 ≠ 0,
-- have pred (h 0) < h 0, from lt_pred_nonzero_self this,
-- have ¬ h 0 ≤ pred (h 0), from not_le_of_gt this,
-- have ¬ ((h 0) ≠ 0 ∧ h 0 ≤ pred (h 0)), from not_and_of_not_right ((h 0) ≠ 0) this,
-- have comb_seq_with_mbs (h 0) = g (h 0 - h 0), from if_neg this,
-- by simp [this,nat.sub_self])
include Hbp Hex
theorem local_contra_of_comb_seq_with_mbs : false :=
by_cases
(suppose eq0 : h 0 = 0,
have eq : comb_seq_with_mbs 0 = g 0, begin apply g_part_of_comb_seq_with_mbs, assumption end,
have m (comb_seq_with_mbs 0) < m (minimal_bad_seq m Hex (h 0)), by rw -eq at Hbp;exact Hbp,
have le : m (comb_seq_with_mbs 0) < m (minimal_bad_seq m Hex 0), by super,
have m (minimal_bad_seq m Hex 0) ≤ m (comb_seq_with_mbs 0), from minimality_of_mbs_0 m Hex comb_seq_with_mbs badness_of_comb_seq_with_mbs,
(not_le_of_gt le) this)
(assume Hneg,
-- have le : m (minimal_bad_seq m Hex (succ (pred (h 0)))) ≤ m (comb_seq_with_mbs (succ (pred (h 0)))), begin apply minimality_of_mbs, split, end,
have le : m (minimal_bad_seq m Hex (succ (pred (h 0)))) ≤ m (comb_seq_with_mbs (succ (pred (h 0)))), from minimality_of_mbs m _ _ _ ⟨begin apply comb_seq_extends_mbs_at_pred_bp, exact Hneg end,badness_of_comb_seq_with_mbs⟩,
have h 0 > 0, from nat.pos_of_ne_zero Hneg,
have succ (pred (h 0)) = h 0, from succ_pred_of_pos this,
have m (minimal_bad_seq m Hex (h 0)) ≤ m (comb_seq_with_mbs (h 0)), by rw this at le;exact le,
have m (minimal_bad_seq m Hex (h 0)) ≤ m (g 0), by rw comb_seq_h0 at this;exact this,
have ¬ m (g 0) < m (minimal_bad_seq m Hex (h 0)), from not_lt_of_ge this,
this Hbp)
end
-- #check local_contra_of_comb_seq_with_mbs
section
parameter {Q : Type}
parameter [o : wqo Q]
definition sub := @star Q o.le
theorem sub_refl (q : finite_subsets Q) : sub q q :=
have ∀ a : Q, a ∈ q.1 → a ≤ (id a) ∧ id a ∈ q.1, begin intros, split, simp, apply quasiorder.refl, simp, assumption end,
⟨id, ⟨inj_from_to_id q.1,this⟩⟩
theorem sub_trans (a b c : finite_subsets Q) (H1 : sub a b) (H2 : sub b c) : sub a c :=
let ⟨f,hf⟩ := H1, ⟨g,hg⟩ := H2 in
have inj : inj_from_to (g ∘ f) a.1 c.1, from inj_from_to_compose hg^.left hf^.left,
have ∀ q : Q, q ∈ a.1 → q ≤ ((g ∘ f) q) ∧ (g ∘ f) q ∈ c.1, from
λ q Hq,
have le1 : q ≤ (f q), from (hf^.right q Hq)^.left,
have fqin : f q ∈ b.1, from (hf^.right q Hq)^.right,
have le2 : (f q) ≤ ((g ∘ f) q), from (hg^.right (f q) fqin)^.left,
have qle : q ≤ ((g ∘ f) q), from quasiorder.trans le1 le2,
have (g ∘ f) q ∈ c.1, from (hg^.right (f q) fqin)^.right,
⟨qle, this⟩,
⟨g ∘ f,⟨inj,this⟩⟩
parameter H : ∃ f : ℕ → finite_subsets Q, ¬ is_good f sub
definition card_of_finite_subsets {A : Type} (s : finite_subsets A) := card s.1
definition Higman's_mbs (n : ℕ) : finite_subsets Q := minimal_bad_seq card_of_finite_subsets H n
theorem badness_of_Higman's_mbs : ¬ is_good Higman's_mbs sub := badness_of_mbs card_of_finite_subsets H
theorem nonempty_mem_of_mbs (n : ℕ) : (Higman's_mbs n).1 ≠ ∅ :=
suppose (Higman's_mbs n).1 = ∅,
have lt : n < succ n, from lt_succ_self n,
have nond : ∀ a : Q, a ∈ (Higman's_mbs n).1 → a ≤ (id a) ∧ id a ∈ (Higman's_mbs (succ n)).1, from
λ a, λ H, have a ∉ (∅ : set Q), from set.not_mem_empty a, by super,
have sub (Higman's_mbs n) (Higman's_mbs (succ n)),
from ⟨id, ⟨⟨λ a Ha,((nond a Ha)^.right),λ b Hb h1 h2 h3,by assumption⟩,nond⟩⟩,
have is_good Higman's_mbs sub, from ⟨n, ⟨succ n,⟨lt,this⟩⟩⟩,
badness_of_Higman's_mbs this
definition B_pairs (n : ℕ) : Q × finite_subsets Q :=
have ∃ a : Q, a ∈ (Higman's_mbs n).1, from exists_mem_of_ne_empty (nonempty_mem_of_mbs n),
let q := some this in
let b := (Higman's_mbs n).1 \ insert q ∅ in
have finite (Higman's_mbs n).1, from (Higman's_mbs n).2,
have finite b, from @finite_diff _ _ _ this,
(q, ⟨b,this⟩)
private definition B (n : ℕ) : finite_subsets Q := (B_pairs n).2
definition qn (n : ℕ) : Q := (B_pairs n).1
theorem qn_in_mbs (n : ℕ) : qn n ∈ (Higman's_mbs n).val :=
some_spec (exists_mem_of_ne_empty (nonempty_mem_of_mbs n))
theorem qn_not_in_Bn (n : ℕ) : ¬ set.mem (qn n) (B n).val :=
suppose qn n ∈ (B n).val, this^.right (mem_singleton (qn n))
theorem ins_B_pairs (n : ℕ) : insert (qn n) (B n).val = (Higman's_mbs n).val :=
have ∃ a : Q, a ∈ (Higman's_mbs n).val, from exists_mem_of_ne_empty (nonempty_mem_of_mbs n),
have qnin : qn n ∈ (Higman's_mbs n).val, from some_spec this,
have (B n).val = (Higman's_mbs n).val \ insert (qn n) ∅, from rfl,
begin apply subset.antisymm, intros x H1, apply or.elim H1,
intro h, simph, intro h1, rw this at h1, exact h1^.left,
intros x h2, cases (decidable.em (x = qn H n)) with H3 H4,
apply or.inl,exact H3,
apply or.inr, rw this,apply and.intro, exact h2,
apply not_mem_singleton, exact H4
end
theorem sub_B_mbs (n : ℕ) : (B n).val ⊆ (Higman's_mbs n).val :=
by intros; intro; rw -ins_B_pairs; apply or.inr; assumption
theorem trans_of_B (i j : ℕ) (H1 : sub (Higman's_mbs i) (B j)) : sub (Higman's_mbs i) (Higman's_mbs j) :=
let ⟨f,hf⟩ := H1 in
have inj_from_to f (Higman's_mbs i).val (B j).val, from and.left hf,
have Hl : ∀ a, a ∈ (Higman's_mbs i).val → f a ∈ (Higman's_mbs j).val, from
λ a Ha, have f a ∈ (B j).val, from this^.left Ha,
(sub_B_mbs j) this,
have inj : inj_from_to f (Higman's_mbs i).val (Higman's_mbs j).val, from ⟨Hl, hf^.left^.right⟩,
have non_descending (Higman's_mbs i) (Higman's_mbs j) o.le f, from
λ a Ha, have Hl : a ≤ (f a), from (hf^.right a Ha)^.left,
have f a ∈ (B j).val, from (hf^.right a Ha)^.right,
have fain : f a ∈ insert (qn j) (B j).val, from or.inr this,
have insert (qn j) (B j).val = (Higman's_mbs j).val, from ins_B_pairs j,
have f a ∈ (Higman's_mbs j).val, by rw this at fain;exact fain,
⟨Hl, this⟩,
⟨f, ⟨inj, this⟩⟩
section
parameter Hg : ∃ g : ℕ → ℕ, ¬ is_good (B ∘ g) sub ∧ ∀ i : ℕ, g 0 ≤ g i
private definition g := some Hg
theorem Higman's_Hg : ¬ is_good (B ∘ g) sub :=
let ⟨l,r⟩ := some_spec Hg in l
theorem Higman's_Hex : ∃ f, ¬ is_good f sub := ⟨(B ∘ g),Higman's_Hg⟩
theorem Higman's_Hh : ∀ i : ℕ, g 0 ≤ g i := (some_spec Hg)^.right
theorem Higman's_H : ∀ i j, sub (Higman's_mbs i) ((B ∘ g) (j - g 0)) → sub (Higman's_mbs i) (Higman's_mbs (g (j - g 0))) :=
λ i j, λ H1, trans_of_B i (g (j - g 0)) H1
definition Higman's_comb_seq (n : ℕ) : finite_subsets Q :=
@comb_seq_with_mbs _ sub (B ∘ g) g card_of_finite_subsets Higman's_Hex n
theorem card_B_lt_mbs (n : ℕ) : card (B n).val < card (Higman's_mbs n).val :=
have finite (B n).val, from (B n).2,
have eq : card (insert (qn n) (B n).val) = card (B n).val + 1, from @card_insert_of_not_mem _ _ _ this (qn_not_in_Bn n),
have card (B n).val < card (B n).val + 1, from lt_succ_self (card (B n).val),
have card (B n).val < card (insert (qn n) (B n).1), begin rw eq, exact this end,-- by simp,
have insert (qn n) ((B n).val) = (Higman's_mbs n).val, from ins_B_pairs n,
by super
theorem Higman's_Hbp : card_of_finite_subsets (B (g 0)) < card_of_finite_subsets (Higman's_mbs (g 0)) := card_B_lt_mbs (g 0)
theorem Higman's_local_contradition : false :=
local_contra_of_comb_seq_with_mbs g card_of_finite_subsets Higman's_Hh Higman's_Hex Higman's_Hg Higman's_H Higman's_Hbp
end
-- #check Higman's_local_contradition
definition ClassB : Type := {x : finite_subsets Q // ∃ i, B i = x}
definition oB (b1 : ClassB) (b2 : ClassB) : Prop := sub b1.val b2.val
theorem oB_refl (q : ClassB) : oB q q := sub_refl q.val
theorem oB_trans (a b c : ClassB) (H1 : oB a b) (H2 : oB b c) : oB a c :=
sub_trans _ _ _ H1 H2
section
-- Suppose there exists a bad sequence of objects in ClassB. We show that we can construct a g : ℕ → ℕ such that ¬ is_good (B ∘ g) o. Then we can apply 'exists_sub_bad'. We cannot directly apply this theorem because ClassB is a type distinct from finite_subsets Q.
parameter HfB : ∃ f, ¬ is_good f oB
private definition f' : ℕ → ClassB := some HfB
private theorem bad_f' : ¬ is_good f' oB := some_spec HfB
private definition g' (n : ℕ) := (f' n).val
theorem exists_bad_B_seq : ¬ is_good g' sub :=
suppose is_good g' sub,
let ⟨i,j,hg'⟩ := this in
have is_good f' oB, from ⟨i, ⟨j, ⟨hg'^.left, hg'^.right⟩⟩⟩,
bad_f' this
private definition g (n : ℕ) : ℕ :=
have ∃ i, B i = g' n, from (f' n).2,
some this
private theorem comp_eq_g' : B ∘ g = g' :=
have ∀ x, B (g x) = g' x, from λ x, some_spec (f' x).2,
funext this
private theorem bad_comp : ¬ is_good (B ∘ g) sub :=
have ¬ is_good g' sub, from exists_bad_B_seq,
by rw -comp_eq_g' at this;exact this
theorem exists_sub_bad_B_seq : ∃ h : ℕ → ℕ, ¬ is_good (B ∘ h) sub ∧ ∀ i : ℕ, h 0 ≤ h i := exists_sub_bad B g sub bad_comp
end
theorem oB_is_good : ∀ f, is_good f oB :=
by_contradiction
(suppose ¬ ∀ f, is_good f oB,
have ∃ f, ¬ is_good f oB, from classical.exists_not_of_not_forall this,
have ∃ h : ℕ → ℕ, ¬ is_good (B ∘ h) sub ∧ ∀ i : ℕ, h 0 ≤ h i, from exists_sub_bad_B_seq this,
Higman's_local_contradition this)
instance wqo_ClassB : wqo ClassB := wqo.mk (quasiorder.mk (has_le.mk oB) oB_refl oB_trans) oB_is_good
instance wqo_prod_Q_ClassB : wqo (Q × ClassB) := wqo_prod
theorem good_prod_Q_ClassB : ∀ f : ℕ → Q × ClassB, is_good f (prod_order o.le oB) := wqo.is_good
lemma B_refl (n : ℕ) : ∃ i, B i = B n := ⟨n, rfl⟩
definition fB (n : ℕ) : ClassB := ⟨B n,B_refl n⟩
private definition p (n : ℕ) : Q × ClassB := (qn n, fB n)
theorem good_p : is_good p (prod_order o.le oB) := good_prod_Q_ClassB p
theorem Hij : ∃ i j, i < j ∧ ((qn i) ≤ (qn j) ∧ oB (fB i) (fB j)) := good_p
theorem exists_embeds : ∃ i j, i < j ∧ sub (Higman's_mbs i) (Higman's_mbs j) :=
let ⟨i,j,hij⟩ := good_p in
have oB (fB i) (fB j), from hij^.right^.right,
let ⟨f₁,⟨injf₁,rhf1⟩⟩ := this in
let f₂ (q : Q) : Q := if q = qn i then qn j else f₁ q in
have nond : ∀ a : Q, a ∈ (Higman's_mbs i).val → a ≤ (f₂ a) ∧ f₂ a ∈ (Higman's_mbs j).val, from λ a Ha,
have Hor : a = qn i ∨ a ∈ (B i).val, by rw -(ins_B_pairs H i) at Ha;exact Ha,
or.elim (em (a = qn i))
(λ l, have eqf₂a : f₂ a = qn j, from if_pos l, ⟨begin rw [eqf₂a,l], exact hij^.right^.left end, begin rw [eqf₂a], apply qn_in_mbs end⟩)
(λ r,have f₂ a=f₁ a, from if_neg r,
have conj : a ≤ (f₂ a) ∧ f₂ a ∈ (B j).val, begin rw this, apply rhf1, super end,
⟨conj^.left,begin apply sub_B_mbs, exact conj^.right end⟩),
have Hmapsto : ∀ a, a ∈ (Higman's_mbs i).val → f₂ a ∈ (Higman's_mbs j).val, from
λ a Ha, and.right (nond a Ha),
have ∀ a₁ a₂, a₁ ∈ (Higman's_mbs i).val → a₂ ∈ (Higman's_mbs i).val → f₂ a₁ = f₂ a₂ → a₁ = a₂, from
λ a₁ a₂ Ha₁ Ha₂ Heq,
have Hora₁ : a₁ = qn i ∨ a₁ ∈ (B i).val, by rw -(ins_B_pairs H i) at Ha₁;exact Ha₁,
have Hora₂ : a₂ = qn i ∨ a₂ ∈ (B i).val, by rw -(ins_B_pairs H i) at Ha₂;exact Ha₂,
by_cases
(assume Hpos : a₁ = qn i, -- level-1 subcase // pos
have eq21j : f₂ a₁ = qn j, from if_pos Hpos,
by_contradiction
(suppose a₁ ≠ a₂,
have neq : qn i ≠ a₂, by rw Hpos at this;exact this,
have eq2212 : f₂ a₂ = f₁ a₂, from if_neg (ne.symm neq),
have qn j ∈ (B j).val, begin rw [-eq21j, Heq, eq2212], apply and.left injf₁,
exact or_resolve_right Hora₂ (ne.symm neq) end,
(qn_not_in_Bn j) this))
(assume Hneg, -- level-1 subcase // neg
have eq2111 : f₂ a₁ = f₁ a₁, from if_neg Hneg,
have a1inBi : a₁ ∈ (B i).val, from or_resolve_right Hora₁ Hneg,
by_cases
(assume Hposa₂ : a₂ = qn i, -- level-2 subcase // pos
have eq21j : f₂ a₂ = qn j, from if_pos Hposa₂,
by_contradiction
(suppose a₁ ≠ a₂,
have neq2 : a₁ ≠ qn i, by rw Hposa₂ at this;exact this,
have eq2111 : f₂ a₁ = f₁ a₁, from if_neg neq2,
have qn j ∈ (B j).val,
begin rw [-eq21j, -Heq, eq2111], apply and.left injf₁,
exact or_resolve_right Hora₁ neq2 end,
(qn_not_in_Bn j) this))
(assume Hnega₂, -- level-2 subcase // neg
have eq2212 : f₂ a₂ = f₁ a₂, from if_neg Hnega₂,
have f₁ a₁ = f₂ a₂, by rw eq2111 at Heq;exact Heq,
have eq1112 : f₁ a₁ = f₁ a₂, from eq.trans this eq2212,
have a₂ ∈ (B i).val, from or_resolve_right Hora₂ Hnega₂,
(and.right injf₁) a1inBi this eq1112)),
have inj_from_to f₂ (Higman's_mbs i).val (Higman's_mbs j).val, from ⟨Hmapsto, this⟩,
have sub (Higman's_mbs i) (Higman's_mbs j), from ⟨f₂,⟨this, nond⟩⟩,
⟨i,⟨j, ⟨hij^.left, this⟩⟩⟩
theorem goodness_of_Higman's_mbs : is_good Higman's_mbs sub := exists_embeds
theorem Higman's_contradiction : false := badness_of_Higman's_mbs goodness_of_Higman's_mbs
end
-- #check Higman's_contradiction
variable {Q : Type}
variable [wqo Q]
theorem good_star : ∀ f : ℕ → finite_subsets Q , is_good f sub :=
by_contradiction
(suppose ¬ ∀ f, is_good f sub,
have ∃ f, ¬ is_good f sub, from classical.exists_not_of_not_forall this,
Higman's_contradiction this)
def wqo_finite_subsets : wqo (finite_subsets Q) :=
⟨⟨⟨sub⟩,sub_refl,sub_trans⟩,good_star⟩
#check wqo_finite_subsets.is_good
-- example : wqo.le (finite_subsets Q) _ = sub := rfl
-- #check wqo_finite_subsets
end kruskal
|
435bef0ceade776f6858c40e1423c33fad75c6c7 | 7c2dd01406c42053207061adb11703dc7ce0b5e5 | /src/solutions/03_forall_or.lean | 713f6eecf2b3ee2f9a3cd46af4f378a7a9223385 | [
"Apache-2.0"
] | permissive | leanprover-community/tutorials | 50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8 | 79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1 | refs/heads/master | 1,687,466,144,386 | 1,672,061,276,000 | 1,672,061,276,000 | 189,169,918 | 186 | 81 | Apache-2.0 | 1,686,350,300,000 | 1,559,113,678,000 | Lean | UTF-8 | Lean | false | false | 9,253 | lean | import data.real.basic
import algebra.group.pi
set_option pp.beta true
/-
In this file, we'll learn about the ∀ quantifier, and the disjunction
operator ∨ (logical OR).
Let P be a predicate on a type X. This means for every mathematical
object x with type X, we get a mathematical statement P x.
In Lean, P x has type Prop.
Lean sees a proof h of `∀ x, P x` as a function sending any `x : X` to
a proof `h x` of `P x`.
This already explains the main way to use an assumption or lemma which
starts with a ∀.
In order to prove `∀ x, P x`, we use `intros x` to fix an arbitrary object
with type X, and call it x.
Note also we don't need to give the type of x in the expression `∀ x, P x`
as long as the type of P is clear to Lean, which can then infer the type of x.
Let's define two predicates to play with ∀.
-/
def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x
def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = -f x
/-
In the next proof, we also take the opportunity to introduce the
`unfold` tactic, which simply unfolds definitions. Here this is purely
for didactic reason, Lean doesn't need those `unfold` invocations.
We will also use `rfl` which is a term proving equalities that are true
by definition (in a very strong sense to be discussed later).
-/
example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) :=
begin
-- Assume f is even
intros hf,
-- which means ∀ x, f (-x) = f x
unfold even_fun at hf,
-- and the same for g
intros hg,
unfold even_fun at hg,
-- We need to prove ∀ x, (f+g)(-x) = (f+g)(x)
unfold even_fun,
-- Let x be any real number
intros x,
-- and let's compute
calc (f + g) (-x) = f (-x) + g (-x) : rfl
... = f x + g (-x) : by rw hf x
... = f x + g x : by rw hg x
... = (f + g) x : rfl
end
/-
In the preceding proof, all `unfold` lines are purely for
psychological comfort.
Sometimes unfolding is necessary because we want to apply a tactic
that operates purely on the syntactical level.
The main such tactic is `rw`.
The same property of `rw` explain why the first computation line
is necessary, although its proof is simply `rfl`.
Before that line, `rw hf x` won't find anything like `f (-x)` hence
will give up.
The last line is not necessary however, since it only proves
something that is true by definition, and is not followed by
a `rw`.
Also, Lean doesn't need to be told that hf should be specialized to
x before rewriting, exactly as in the first file 01_equality_rewriting.
We can also gather several rewrites using a list of expressions.
One last trick is that `rw` can take a list of expressions to use for
rewriting. For instance `rw [h₁, h₂, h₃]` is equivalent to three
lines `rw h₁`, `rw h₂` and `rw h₃`. Note that you can inspect the tactic
state between those rewrites when reading a proof using this syntax. You
simply need to move the cursor inside the list.
Hence we can compress the above proof to:
-/
example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) :=
begin
intros hf hg x,
calc (f + g) (-x) = f (-x) + g (-x) : rfl
... = f x + g x : by rw [hf, hg]
end
/-
Now let's practice. If you need to learn how to type a unicode symbol,
you can put your mouse cursor above the symbol and wait for one second.
-/
-- 0023
example (f g : ℝ → ℝ) : even_fun f → even_fun (g ∘ f) :=
begin
-- sorry
intros hf x,
calc (g ∘ f) (-x) = g (f (-x)) : rfl
... = g (f x) : by rw hf
-- sorry
end
-- 0024
example (f g : ℝ → ℝ) : odd_fun f → odd_fun g → odd_fun (g ∘ f) :=
begin
-- sorry
intros hf hg x,
calc (g ∘ f) (-x) = g (f (-x)) : rfl
... = - (g ∘ f) x : by rw [hf, hg],
-- sorry
end
/-
Let's have more quantifiers, and play with forward and backward reasoning.
In the next definitions, note how `∀ x₁, ∀ x₂` is abreviated to `∀ x₁ x₂`.
-/
def non_decreasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≤ f x₂
def non_increasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≥ f x₂
/- Let's be very explicit and use forward reasoning first. -/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
-- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂
intros x₁ x₂ h,
-- Since f is non-decreasing, f x₁ ≤ f x₂.
have step₁ : f x₁ ≤ f x₂,
exact hf x₁ x₂ h,
-- Since g is non-decreasing, we then get g (f x₁) ≤ g (f x₂).
exact hg (f x₁) (f x₂) step₁,
end
/-
In the above proof, note how inconvenient it is to specify x₁ and x₂ in `hf x₁ x₂ h` since
they could be inferred from the type of h.
We could have written `hf _ _ h` and Lean would have filled the holes denoted by _.
Even better we could have written the definition
of `non_decreasing` as: ∀ {x₁ x₂}, x₁ ≤ x₂ → f x₁ ≤ f x₂, with curly braces to denote
implicit arguments.
But let's leave that aside for now. One possible variation on the above proof is to
use the `specialize` tactic to replace hf by its specialization to the relevant value.
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
intros x₁ x₂ h,
specialize hf x₁ x₂ h,
exact hg (f x₁) (f x₂) hf,
end
/-
This `specialize` tactic is mostly useful for exploration, or in preparation for rewriting
in the assumption. One can very often replace its use by using more complicated expressions
directly involving the original assumption, as in the next variation:
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
intros x₁ x₂ h,
exact hg (f x₁) (f x₂) (hf x₁ x₂ h),
end
/-
Since the above proof uses only `intros` and `exact`, we could very easily replace it by the
raw proof term:
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
λ x₁ x₂ h, hg (f x₁) (f x₂) (hf x₁ x₂ h)
/-
Of course the above proof is difficult to decipher. The principle in mathlib is to use
such a proof when the result is obvious and you don't want to read the proof anyway.
Instead of pursuing this style, let's see how backward reasoning would look like here.
As usual with this style, we use `apply` and enjoy Lean specializing assumptions for us
using unification.
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
-- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂
intros x₁ x₂ h,
-- We need to prove (g ∘ f) x₁ ≤ (g ∘ f) x₂.
-- Since g is non-decreasing, it suffices to prove f x₁ ≤ f x₂
apply hg,
-- which follows from our assumption on f
apply hf,
-- and on x₁ and x₂
exact h
end
-- 0025
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_increasing g) : non_increasing (g ∘ f) :=
begin
-- sorry
intros x₁ x₂ h,
apply hg,
exact hf x₁ x₂ h
-- sorry
end
/-
Let's switch to disjunctions now. Lean denotes by ∨ the
logical OR operator.
In order to make use of an assumption
hyp : P ∨ Q
we use the cases tactic:
cases hyp with hP hQ
which creates two proof branches: one branch assuming hP : P,
and one branch assuming hQ : Q.
In order to directly prove a goal P ∨ Q,
we use either the `left` tactic and prove P or the `right`
tactic and prove Q.
In the next proof we use `ring` and `linarith` to get rid of
easy computations or inequalities, as well as one lemma:
mul_eq_zero : a*b = 0 ↔ a = 0 ∨ b = 0
-/
example (a b : ℝ) : a = a*b → a = 0 ∨ b = 1 :=
begin
intro hyp,
have H : a*(1 - b) = 0,
{ calc a*(1 - b) = a - a*b : by ring
... = 0 : by linarith, },
rw mul_eq_zero at H,
cases H with Ha Hb,
{ left,
exact Ha, },
{ right,
linarith, },
end
-- 0026
example (x y : ℝ) : x^2 = y^2 → x = y ∨ x = -y :=
begin
-- sorry
intros hyp,
have H : (x-y)*(x+y) = 0,
calc (x-y)*(x+y) = x^2 - y^2 : by ring
... = y^2 - y^2 : by rw hyp
... = 0 : by ring,
rw mul_eq_zero at H,
cases H with h1 h2,
{ left,
linarith, },
{ right,
linarith, },
-- sorry
end
/-
In the next exercise, we can use:
eq_or_lt_of_le : x ≤ y → x = y ∨ x < y
-/
-- 0027
example (f : ℝ → ℝ) : non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y :=
begin
-- sorry
split,
{ intros hf x y hxy,
apply hf,
linarith, },
{ intros hf x y hxy,
have clef : x = y ∨ x < y,
{ exact eq_or_lt_of_le hxy },
cases clef with hxy hxy,
rw hxy,
exact hf x y hxy, },
-- sorry
end
/-
In the next exercise, we can use:
le_total x y : x ≤ y ∨ y ≤ x
-/
-- 0028
example (f : ℝ → ℝ) (h : non_decreasing f) (h' : ∀ x, f (f x) = x) : ∀ x, f x = x :=
begin
-- sorry
intro x,
have : f (f x) = x,
{ rw h' },
have : (f x ≤ x) ∨ (x ≤ f x),
{ exact le_total (f x) x },
cases this with hx hx,
{ have f1: f (f x) ≤ f x,
{ exact h (f x) x hx, },
rw h' at f1,
linarith, },
{ have f1: f x ≤ f (f x),
{ exact h x (f x) hx, },
rw h' x at f1,
linarith, },
-- sorry
end
|
aa100b42d77579a37b9f5bc3d497a6a23bb497e6 | cabd1ea95170493667c024ef2045eb86d981b133 | /src/super/misc_preprocessing.lean | 75171fad57e6601444379b5cd38e418283bea38b | [] | no_license | semorrison/super | 31db4b5aa5ef4c2313dc5803b8c79a95f809815b | 0c6c03ba9c7470f801eb4d055294f424ff090308 | refs/heads/master | 1,630,272,140,541 | 1,511,054,739,000 | 1,511,054,756,000 | 114,317,807 | 0 | 0 | null | 1,513,304,776,000 | 1,513,304,775,000 | null | UTF-8 | Lean | false | false | 1,137 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .prover_state
open expr list monad
namespace super
meta def is_taut (c : clause) : tactic bool := do
qf ← c.open_constn c.num_quants,
return $ list.bor $ do
l1 ← qf.1.get_lits, guard l1.is_neg,
l2 ← qf.1.get_lits, guard l2.is_pos,
[decidable.to_bool $ l1.formula = l2.formula]
meta def tautology_removal_pre : prover unit :=
preprocessing_rule $ λnew, filter (λc, lift bnot $ is_taut c.c) new
meta def remove_duplicates : list derived_clause → list derived_clause
| [] := []
| (c :: cs) :=
let (same_type, other_type) := partition (λc' : derived_clause, c'.c.type = c.c.type) cs in
{ c with sc := foldl score.min c.sc (same_type.map $ λc, c.sc) } :: remove_duplicates other_type
meta def remove_duplicates_pre : prover unit :=
preprocessing_rule $ λnew,
return $ remove_duplicates new
meta def clause_normalize_pre : prover unit :=
preprocessing_rule $ λnew, new.mmap $ λdc,
do c' ← dc.c.normalize, return { dc with c := c' }
end super
|
4115b4f2573bd945a9c5eb7d8d6b1e803d6a015a | bb31430994044506fa42fd667e2d556327e18dfe | /archive/imo/imo1988_q6.lean | 5db7f6694d4fbe6bd0e3d27a8d8a17b70a441380 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 13,845 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.nat.prime
import data.rat.defs
import order.well_founded
import tactic.linarith
import tactic.wlog
/-!
# IMO 1988 Q6 and constant descent Vieta jumping
Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers
could not tackle the question within the given time limit.
The problem lead to the introduction of a new proof technique,
so called “Vieta jumping”.
In this file we formalise constant descent Vieta jumping,
and apply this to prove Q6 of IMO1988.
To illustrate the technique, we also prove a similar result.
-/
-- open_locale classical
local attribute [instance] classical.prop_decidable
local attribute [simp] sq
/-- Constant descent Vieta jumping.
This proof technique allows one to prove an arbitrary proposition `claim`,
by running a descent argument on a hyperbola `H` in the first quadrant of the plane,
under the following conditions:
* `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`.
* `H_symm` : The hyperbola has a symmetry along the diagonal in the plane.
* `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true.
* `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true.
* `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`,
with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`.
For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate.
(In question 6 of IMO1988, where this proof technique was first developped,
the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`,
and the predicate `H` would be `λ a b, a * a + b * b = (a * b + 1) * k`.)
To ensure that the predicate `H` actually describes a hyperbola,
the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation.
Finally, `H_quad` is the proof obligation that the quadratic equation
`(y:ℤ) * y - B x * y + C x = 0`
describes the same hyperbola as the predicate `H`.
For extra flexibility, one must provide a predicate `base` on the integral points in the plane.
In the descent step `H_desc` this will give the user the additional assumption that
the point `(x,y)` does not lie in this base locus.
The user must provide a proof that the proposition `claim` is true
if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus.
If such a base locus is not necessary, once can simply let it be `λ x y, false`.
-/
lemma constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop}
(h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop)
(H_quad : ∀ {x y}, H x y ↔ (y:ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x)
(H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim)
(H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y →
∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x)
(H_base : ∀ {x y}, H x y → base x y → claim) :
claim :=
begin
-- First of all, we may assume that x ≤ y.
-- We justify this using H_symm.
wlog hxy : x ≤ y, swap, { rw H_symm at h₀, solve_by_elim },
-- In fact, we can easily deal with the case x = y.
by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag h₀},
-- Hence we may assume that x < y.
replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y,
-- Consider the upper branch of the hyperbola defined by H.
let upper_branch : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2},
-- Note that the point p = (x,y) lies on the upper branch.
let p : ℕ × ℕ := ⟨x,y⟩,
have hp : p ∈ upper_branch := ⟨h₀, hxy⟩,
-- We also consider the exceptional set of solutions (a,b) that satisfy
-- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus.
let exceptional : set (ℕ × ℕ) :=
{p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) },
-- Let S be the projection of the upper branch on to the y-axis
-- after removing the exceptional locus.
let S : set ℕ := prod.snd '' (upper_branch \ exceptional),
-- The strategy is to show that the exceptional locus in nonempty
-- by running a descent argument that starts with the given point p = (x,y).
-- Our assumptions ensure that we can then prove the claim.
suffices exc : exceptional.nonempty,
{ -- Suppose that there exists an element in the exceptional locus.
simp [exceptional, -add_comm, set.nonempty] at exc,
-- Let (a,b) be such an element, and consider all the possible cases.
rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB,
-- The first three cases are rather easy to solve.
{ solve_by_elim },
{ rw H_symm at hH, solve_by_elim },
{ solve_by_elim },
-- The final two cases are very similar.
all_goals
{ -- Consider the quadratic equation that (a,b) satisfies.
rw H_quad at hH,
-- We find the other root of the equation, and Vieta's formulas.
rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩,
-- By substitutions we find that b = 0 or b = a.
simp [hB] at hV₁, subst hV₁,
rw [← int.coe_nat_zero] at *,
rw ← H_quad at h_root,
-- And hence we are done by H_zero and H_diag.
solve_by_elim } },
-- To finish the main proof, we need to show that the exceptional locus is nonempty.
-- So we assume that the exceptional locus is empty, and work towards deriving a contradiction.
rw set.nonempty_iff_ne_empty,
assume exceptional_empty,
-- Observe that S is nonempty.
have S_nonempty : S.nonempty,
{ -- It contains the image of p.
use p.2,
apply set.mem_image_of_mem,
-- After all, we assumed that the exceptional locus is empty.
rwa [exceptional_empty, set.diff_empty], },
-- We are now set for an infinite descent argument.
-- Let m be the smallest element of the nonempty set S.
let m : ℕ := well_founded.min nat.lt_wf S S_nonempty,
have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty,
have m_min : ∀ k ∈ S, ¬ k < m := λ k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk,
-- It suffices to show that there is point (a,b) with b ∈ S and b < m.
rsuffices ⟨p', p'_mem, p'_small⟩ : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m,
{ solve_by_elim },
-- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S
-- and that does not lie in the exceptional locus.
rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩,
-- This means that m_y = m,
-- and the conditions H(m_x, m_y) and m_x < m_y are satisfied.
simp [exceptional, hHm] at mx_lt_my h_base m_eq,
push_neg at h_base,
-- Finally, it also means that (m_x, m_y) does not lie in the base locus,
-- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y.
rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩,
replace hmx : 0 < mx := pos_iff_ne_zero.mpr hmx,
-- Consider the quadratic equation that (m_x, m_y) satisfies.
have h_quad := hHm, rw H_quad at h_quad,
-- We find the other root of the equation, and Vieta's formulas.
rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩,
-- No we rewrite Vietas formulas a bit, and apply the descent step.
replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁,
rw mul_comm at hV₂,
have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂,
-- This means that we may assume that c ≥ 0 and c ≤ m_x.
cases Hc with c_nonneg c_lt,
-- In other words, c is a natural number.
lift c to ℕ using c_nonneg,
-- Recall that we are trying find a point (a,b) such that b ∈ S and b < m.
-- We claim that p' = (c, m_x) does the job.
let p' : ℕ × ℕ := ⟨c, mx⟩,
use p',
-- The second condition is rather easy to check, so we do that first.
split, swap,
{ rwa m_eq at mx_lt_my },
-- Now we need to show that p' projects onto S. In other words, that c ∈ S.
-- We do that, by showing that it lies in the upper branch
-- (which is sufficient, because we assumed that the exceptional locus is empty).
apply set.mem_image_of_mem,
rw [exceptional_empty, set.diff_empty],
-- Now we are ready to prove that p' = (c, m_x) lies on the upper branch.
-- We need to check two conditions: H(c, m_x) and c < m_x.
split; dsimp only,
{ -- The first condition is not so hard. After all, c is the other root of the quadratic equation.
rw [H_symm, H_quad],
simpa using h_root, },
{ -- For the second condition, we note that it suffices to check that c ≠ m_x.
suffices hc : c ≠ mx,
{ refine lt_of_le_of_ne _ hc,
exact_mod_cast c_lt, },
-- However, recall that B(m_x) ≠ m_x + m_y.
-- If c = m_x, we can prove B(m_x) = m_x + m_y.
contrapose! hm_B₂, subst c,
simp [hV₁], }
-- Hence p' = (c, m_x) lies on the upper branch, and we are done.
end
/--Question 6 of IMO1988. If a and b are two natural numbers
such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/
lemma imo1988_q6 {a b : ℕ} (h : (a*b+1) ∣ a^2 + b^2) :
∃ d, d^2 = (a^2 + b^2)/(a*b + 1) :=
begin
rcases h with ⟨k, hk⟩,
rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))],
simp only [sq] at hk,
apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x - k) (λ x y, false);
clear hk a b,
{ -- We will now show that the fibers of the solution set are described by a quadratic equation.
intros x y, dsimp only,
rw [← int.coe_nat_inj', ← sub_eq_zero],
apply eq_iff_eq_cancel_right.2,
norm_cast,
simp, ring, },
{ -- Show that the solution set is symmetric in a and b.
intros x y, simp [add_comm (x*x), mul_comm x], },
{ -- Show that the claim is true if b = 0.
suffices : ∀ a, a * a = k → ∃ d, d * d = k, by simpa,
rintros x rfl, use x },
{ -- Show that the claim is true if a = b.
intros x hx,
suffices : k ≤ 1,
{ rw [nat.le_add_one_iff, le_zero_iff] at this,
rcases this with rfl|rfl,
{ use 0, simp },
{ use 1, simp } },
contrapose! hx with k_lt_one,
apply ne_of_lt,
calc x*x + x*x = x*x * 2 : by rw mul_two
... ≤ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one
... < (x*x + 1) * k : by linarith },
{ -- Show the descent step.
intros x y hx x_lt_y hxky h z h_root hV₁ hV₀,
split,
{ dsimp [-sub_eq_add_neg] at *,
have hpos : z*z + x*x > 0,
{ apply add_pos_of_nonneg_of_pos,
{ apply mul_self_nonneg },
{ apply mul_pos; exact_mod_cast hx }, },
have hzx : z*z + x*x = (z * x + 1) * k,
{ rw [← sub_eq_zero, ← h_root],
ring, },
rw hzx at hpos,
replace hpos : z * x + 1 > 0 := pos_of_mul_pos_left hpos (int.coe_zero_le k),
replace hpos : z * x ≥ 0 := int.le_of_lt_add_one hpos,
apply nonneg_of_mul_nonneg_left hpos (by exact_mod_cast hx), },
{ contrapose! hV₀ with x_lt_z,
apply ne_of_gt,
calc z * y > x*x : by apply mul_lt_mul'; linarith
... ≥ x*x - k : sub_le_self _ (int.coe_zero_le k) }, },
{ -- There is no base case in this application of Vieta jumping.
simp },
end
/-
The following example illustrates the use of constant descent Vieta jumping
in the presence of a non-trivial base case.
-/
example {a b : ℕ} (h : a*b ∣ a^2 + b^2 + 1) :
3*a*b = a^2 + b^2 + 1 :=
begin
rcases h with ⟨k, hk⟩,
suffices : k = 3, { simp * at *, ring, },
simp only [sq] at hk,
apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x + 1) (λ x y, x ≤ 1);
clear hk a b,
{ -- We will now show that the fibers of the solution set are described by a quadratic equation.
intros x y, dsimp only,
rw [← int.coe_nat_inj', ← sub_eq_zero],
apply eq_iff_eq_cancel_right.2,
simp, ring, },
{ -- Show that the solution set is symmetric in a and b.
cc },
{ -- Show that the claim is true if b = 0.
simp },
{ -- Show that the claim is true if a = b.
intros x hx,
have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k,
rw ← hx at x_sq_dvd,
obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd,
obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm,
simpa using hx.symm, },
{ -- Show the descent step.
intros x y x_lt_y hx h_base h z h_root hV₁ hV₀,
split,
{ have zy_pos : z * y ≥ 0,
{ rw hV₀, exact_mod_cast (nat.zero_le _) },
apply nonneg_of_mul_nonneg_left zy_pos,
linarith },
{ contrapose! hV₀ with x_lt_z,
apply ne_of_gt,
push_neg at h_base,
calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith
... ≥ x * (x + 1) : by apply mul_le_mul; linarith
... > x * x + 1 :
begin
rw [mul_add, mul_one],
apply add_lt_add_left,
assumption_mod_cast
end, } },
{ -- Show the base case.
intros x y h h_base,
obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, le_zero_iff] at h_base,
{ simpa using h, },
{ simp only [mul_one, one_mul, add_comm, zero_add] at h,
have y_dvd : y ∣ y * k := dvd_mul_right y k,
rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd,
obtain rfl|rfl := (nat.dvd_prime nat.prime_two).mp y_dvd; apply mul_left_cancel₀,
exacts [one_ne_zero, h.symm, two_ne_zero, h.symm] } }
end
|
b8d99e6c8c82792d1b3f608e25a4477fd041d799 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/tensor_algebra.lean | ace28c6dfe0f46116d82706c35bbe65b8333856e | [] | 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 | 7,272 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Adam Topaz.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.free_algebra
import Mathlib.algebra.ring_quot
import Mathlib.algebra.triv_sq_zero_ext
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Tensor Algebras
Given a commutative semiring `R`, and an `R`-module `M`, we construct the tensor algebra of `M`.
This is the free `R`-algebra generated (`R`-linearly) by the module `M`.
## Notation
1. `tensor_algebra R M` is the tensor algebra itself. It is endowed with an R-algebra structure.
2. `tensor_algebra.ι R` is the canonical R-linear map `M → tensor_algebra R M`.
3. Given a linear map `f : M → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an
`R`-algebra morphism `tensor_algebra R M → A`.
## Theorems
1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`.
2. `lift_unique` states that whenever an R-algebra morphism `g : tensor_algebra R M → A` is
given whose composition with `ι R` is `f`, then one has `g = lift R f`.
3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem.
4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift
of the composition of an algebra morphism with `ι` is the algebra morphism itself.
## Implementation details
As noted above, the tensor algebra of `M` is constructed as the free `R`-algebra generated by `M`,
modulo the additional relations making the inclusion of `M` into an `R`-linear map.
-/
namespace tensor_algebra
/--
An inductively defined relation on `pre R M` used to force the initial algebra structure on
the associated quotient.
-/
-- force `ι` to be linear
inductive rel (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] : free_algebra R M → free_algebra R M → Prop
where
| add : ∀ {a b : M}, rel R M (free_algebra.ι R (a + b)) (free_algebra.ι R a + free_algebra.ι R b)
| smul : ∀ {r : R} {a : M}, rel R M (free_algebra.ι R (r • a)) (coe_fn (algebra_map R (free_algebra R M)) r * free_algebra.ι R a)
end tensor_algebra
/--
The tensor algebra of the module `M` over the commutative semiring `R`.
-/
def tensor_algebra (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] :=
ring_quot sorry
namespace tensor_algebra
protected instance ring (M : Type u_2) [add_comm_monoid M] {S : Type u_1} [comm_ring S] [semimodule S M] : ring (tensor_algebra S M) :=
ring_quot.ring (rel S M)
/--
The canonical linear map `M →ₗ[R] tensor_algebra R M`.
-/
def ι (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : linear_map R M (tensor_algebra R M) :=
linear_map.mk (fun (m : M) => coe_fn (ring_quot.mk_alg_hom R (rel R M)) (free_algebra.ι R m)) sorry sorry
theorem ring_quot_mk_alg_hom_free_algebra_ι_eq_ι (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn (ring_quot.mk_alg_hom R (rel R M)) (free_algebra.ι R m) = coe_fn (ι R) m :=
rfl
/--
Given a linear map `f : M → A` where `A` is an `R`-algebra, `lift R f` is the unique lift
of `f` to a morphism of `R`-algebras `tensor_algebra R M → A`.
-/
def lift (R : Type u_1) [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] : linear_map R M A ≃ alg_hom R (tensor_algebra R M) A :=
equiv.mk
(⇑(ring_quot.lift_alg_hom R) ∘
fun (f : linear_map R M A) => { val := coe_fn (free_algebra.lift R) ⇑f, property := sorry })
(fun (F : alg_hom R (tensor_algebra R M) A) => linear_map.comp (alg_hom.to_linear_map F) (ι R)) sorry sorry
@[simp] theorem ι_comp_lift {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) : linear_map.comp (alg_hom.to_linear_map (coe_fn (lift R) f)) (ι R) = f :=
equiv.symm_apply_apply (lift R) f
@[simp] theorem lift_ι_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) (x : M) : coe_fn (coe_fn (lift R) f) (coe_fn (ι R) x) = coe_fn f x :=
id (Eq.refl (coe_fn f x))
@[simp] theorem lift_unique {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (f : linear_map R M A) (g : alg_hom R (tensor_algebra R M) A) : linear_map.comp (alg_hom.to_linear_map g) (ι R) = f ↔ g = coe_fn (lift R) f :=
equiv.symm_apply_eq (lift R)
-- Marking `tensor_algebra` irreducible makes `ring` instances inaccessible on quotients.
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241
-- For now, we avoid this by not marking it irreducible.
@[simp] theorem lift_comp_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] (g : alg_hom R (tensor_algebra R M) A) : coe_fn (lift R) (linear_map.comp (alg_hom.to_linear_map g) (ι R)) = g := sorry
/-- See note [partially-applied ext lemmas]. -/
theorem hom_ext {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] {A : Type u_3} [semiring A] [algebra R A] {f : alg_hom R (tensor_algebra R M) A} {g : alg_hom R (tensor_algebra R M) A} (w : linear_map.comp (alg_hom.to_linear_map f) (ι R) = linear_map.comp (alg_hom.to_linear_map g) (ι R)) : f = g := sorry
/-- The left-inverse of `algebra_map`. -/
def algebra_map_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : alg_hom R (tensor_algebra R M) R :=
coe_fn (lift R) 0
theorem algebra_map_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : function.left_inverse ⇑algebra_map_inv ⇑(algebra_map R (tensor_algebra R M)) := sorry
/-- The left-inverse of `ι`.
As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable
algebra structure. -/
def ι_inv {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : linear_map R (tensor_algebra R M) M :=
linear_map.comp (triv_sq_zero_ext.snd_hom R M) (alg_hom.to_linear_map (coe_fn (lift R) (triv_sq_zero_ext.inr_hom R M)))
theorem ι_left_inverse {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : function.left_inverse ⇑ι_inv ⇑(ι R) := sorry
end tensor_algebra
namespace free_algebra
/-- The canonical image of the `free_algebra` in the `tensor_algebra`, which maps
`free_algebra.ι R x` to `tensor_algebra.ι R x`. -/
def to_tensor {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] : alg_hom R (free_algebra R M) (tensor_algebra R M) :=
coe_fn (lift R) ⇑(tensor_algebra.ι R)
@[simp] theorem to_tensor_ι {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn to_tensor (ι R m) = coe_fn (tensor_algebra.ι R) m := sorry
|
060c3c6584ddf8cbaec08d7e4324dcc0fe5f74e7 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /08_Building_Theories_and_Proofs.org.1.lean | ec00c946038ef26de655aa752a9f347d3651b6ea | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 213 | lean | import standard
structure Semigroup : Type :=
(carrier : Type)
(mul : carrier → carrier → carrier)
(mul_assoc : ∀ a b c : carrier, mul (mul a b) c = mul a (mul b c))
notation a `*` b := Semigroup.mul _ a b
|
db40bee5e58b8e1b9606f150b1e8761cc88b6ad1 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/over.lean | 01c0fdc49e5cf85e77c500c85f4775ad34aa1fc6 | [
"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 | 9,779 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Bhavik Mehta
-/
import category_theory.comma
import category_theory.punit
import category_theory.reflects_isomorphisms
/-!
# Over and under categories
Over (and under) categories are special cases of comma categories.
* If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or
"over" category over the object `R` maps to.
* Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the
"coslice" or "under" category under the object `L` maps to.
## Tags
comma, slice, coslice, over, under
-/
namespace category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {T : Type u₁} [category.{v₁} T]
/--
The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative
triangles.
See https://stacks.math.columbia.edu/tag/001G.
-/
@[derive category]
def over (X : T) := comma.{v₁ v₁ v₁} (𝟭 T) (functor.from_punit X)
-- Satisfying the inhabited linter
instance over.inhabited [inhabited T] : inhabited (over (default T)) :=
{ default :=
{ left := default T,
hom := 𝟙 _ } }
namespace over
variables {X : T}
@[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V}
(h : f.left = g.left) : f = g :=
by tidy
@[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy
@[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl
@[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).left = f.left ≫ g.left := rfl
@[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom :=
by have := f.w; tidy
/-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/
@[simps]
def mk {X Y : T} (f : Y ⟶ X) : over X :=
{ left := Y, hom := f }
/-- We can set up a coercion from arrows with codomain `X` to `over X`. This most likely should not
be a global instance, but it is sometimes useful. -/
def coe_from_hom {X Y : T} : has_coe (Y ⟶ X) (over X) :=
{ coe := mk }
section
local attribute [instance] coe_from_hom
@[simp] lemma coe_hom {X Y : T} (f : Y ⟶ X) : (f : over X).hom = f := rfl
end
/-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative
triangle. -/
@[simps]
def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) :
U ⟶ V :=
{ left := f }
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
@[simps {rhs_md:=semireducible}]
def iso_mk {f g : over X} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom . obviously) : f ≅ g :=
comma.iso_mk hl (eq_to_iso (subsingleton.elim _ _)) (by simp [hw])
section
variable (X)
/--
The forgetful functor mapping an arrow to its domain.
See https://stacks.math.columbia.edu/tag/001G.
-/
def forget : over X ⥤ T := comma.fst _ _
end
@[simp] lemma forget_obj {U : over X} : (forget X).obj U = U.left := rfl
@[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : (forget X).map f = f.left := rfl
/--
A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way.
See https://stacks.math.columbia.edu/tag/001G.
-/
def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V}
@[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl
@[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
instance forget_reflects_iso : reflects_isomorphisms (forget X) :=
{ reflects := λ Y Z f t, by exactI
{ inv := over.hom_mk t.inv ((as_iso ((forget X).map f)).inv_comp_eq.2 (over.w f).symm) } }
section iterated_slice
variables (f : over X)
/-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/
@[simps]
def iterated_slice_forward : over f ⥤ over f.left :=
{ obj := λ α, over.mk α.hom.left,
map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) }
/-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/
@[simps]
def iterated_slice_backward : over f.left ⥤ over f :=
{ obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f),
map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) }
/-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/
@[simps]
def iterated_slice_equiv : over f ≌ over f.left :=
{ functor := iterated_slice_forward f,
inverse := iterated_slice_backward f,
unit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (over.iso_mk (iso.refl _) (by tidy)) (by tidy))
(λ X Y g, by { ext, dsimp, simp }),
counit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (iso.refl _) (by tidy))
(λ X Y g, by { ext, dsimp, simp }) }
lemma iterated_slice_forward_forget :
iterated_slice_forward f ⋙ forget f.left = forget f ⋙ forget X :=
rfl
lemma iterated_slice_backward_forget_forget :
iterated_slice_backward f ⋙ forget f ⋙ forget X = forget f.left :=
rfl
end iterated_slice
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/
@[simps]
def post (F : T ⥤ D) : over X ⥤ over (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ left := F.map f.left,
w' := by tidy; erw [← F.map_comp, w] } }
end
end over
/-- The under category has as objects arrows with domain `X` and as morphisms commutative
triangles. -/
@[derive category]
def under (X : T) := comma.{v₁ v₁ v₁} (functor.from_punit X) (𝟭 T)
-- Satisfying the inhabited linter
instance under.inhabited [inhabited T] : inhabited (under (default T)) :=
{ default :=
{ right := default T,
hom := 𝟙 _ } }
namespace under
variables {X : T}
@[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V}
(h : f.right = g.right) : f = g :=
by tidy
@[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy
@[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl
@[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).right = f.right ≫ g.right := rfl
@[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom :=
by have := f.w; tidy
/-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/
@[simps]
def mk {X Y : T} (f : X ⟶ Y) : under X :=
{ right := Y, hom := f }
/-- To give a morphism in the under category, it suffices to give a morphism fitting in a
commutative triangle. -/
@[simps]
def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) :
U ⟶ V :=
{ right := f }
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
def iso_mk {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : f ≅ g :=
comma.iso_mk (eq_to_iso (subsingleton.elim _ _)) hr (by simp [hw])
@[simp]
lemma iso_mk_hom_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).hom.right = hr.hom := rfl
@[simp]
lemma iso_mk_inv_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).inv.right = hr.inv := rfl
section
variables (X)
/-- The forgetful functor mapping an arrow to its domain. -/
def forget : under X ⥤ T := comma.snd _ _
end
@[simp] lemma forget_obj {U : under X} : (forget X).obj U = U.right := rfl
@[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : (forget X).map f = f.right := rfl
/-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/
def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V}
@[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl
@[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/
@[simps]
def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ right := F.map f.right,
w' := by tidy; erw [← F.map_comp, w] } }
end
end under
end category_theory
|
14f92733137988f6471c8222fa7356a7cf9d7aa2 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/opposite.lean | 9a6beca88e6deb2987eadfba797783d8020cae02 | [
"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,789 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton, Simon Hudon, Kenny Lau
-/
import logic.equiv.defs
/-!
# Opposites
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/650
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define a type synonym `opposite α := α`, denoted by `αᵒᵖ` and two synonyms for the
identity map, `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. If `α` is a category, then `αᵒᵖ` is the opposite
category, with all arrows reversed.
-/
universes v u -- morphism levels before object levels. See note [category_theory universes].
variable (α : Sort u)
/-- The type of objects of the opposite of `α`; used to define the opposite category.
In order to avoid confusion between `α` and its opposite type, we
set up the type of objects `opposite α` using the following pattern,
which will be repeated later for the morphisms.
1. Define `opposite α := α`.
2. Define the isomorphisms `op : α → opposite α`, `unop : opposite α → α`.
3. Make the definition `opposite` irreducible.
This has the following consequences.
* `opposite α` and `α` are distinct types in the elaborator, so you
must use `op` and `unop` explicitly to convert between them.
* Both `unop (op X) = X` and `op (unop X) = X` are definitional
equalities. Notably, every object of the opposite category is
definitionally of the form `op X`, which greatly simplifies the
definition of the structure of the opposite category, for example.
(If Lean supported definitional eta equality for records, we could
achieve the same goals using a structure with one field.)
-/
def opposite : Sort u := α
-- Use a high right binding power (like that of postfix ⁻¹) so that, for example,
-- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`.
notation α `ᵒᵖ`:std.prec.max_plus := opposite α
namespace opposite
variables {α}
/-- The canonical map `α → αᵒᵖ`. -/
@[pp_nodot]
def op : α → αᵒᵖ := id
/-- The canonical map `αᵒᵖ → α`. -/
@[pp_nodot]
def unop : αᵒᵖ → α := id
lemma op_injective : function.injective (op : α → αᵒᵖ) := λ _ _, id
lemma unop_injective : function.injective (unop : αᵒᵖ → α) := λ _ _, id
@[simp] lemma op_unop (x : αᵒᵖ) : op (unop x) = x := rfl
@[simp] lemma unop_op (x : α) : unop (op x) = x := rfl
attribute [irreducible] opposite
-- We could prove these by `iff.rfl`, but that would make these eligible for `dsimp`. That would be
-- a bad idea because `opposite` is irreducible.
@[simp] lemma op_inj_iff (x y : α) : op x = op y ↔ x = y := op_injective.eq_iff
@[simp] lemma unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y := unop_injective.eq_iff
/-- The type-level equivalence between a type and its opposite. -/
def equiv_to_opposite : α ≃ αᵒᵖ :=
{ to_fun := op,
inv_fun := unop,
left_inv := unop_op,
right_inv := op_unop }
@[simp]
lemma equiv_to_opposite_coe : (equiv_to_opposite : α → αᵒᵖ) = op := rfl
@[simp]
lemma equiv_to_opposite_symm_coe : (equiv_to_opposite.symm : αᵒᵖ → α) = unop := rfl
lemma op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y :=
equiv_to_opposite.apply_eq_iff_eq_symm_apply
lemma unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y :=
equiv_to_opposite.symm.apply_eq_iff_eq_symm_apply
instance [inhabited α] : inhabited αᵒᵖ := ⟨op default⟩
/-- A recursor for `opposite`. Use as `induction x using opposite.rec`. -/
@[simp]
protected def rec {F : Π (X : αᵒᵖ), Sort v} (h : Π X, F (op X)) : Π X, F X :=
λ X, h (unop X)
end opposite
namespace tactic
open opposite
namespace op_induction
/-- Test if `e : expr` is of type `opposite α` for some `α`. -/
meta def is_opposite (e : expr) : tactic bool :=
do t ← infer_type e,
`(opposite _) ← whnf t | return ff,
return tt
/-- Find the first hypothesis of type `opposite _`. Fail if no such hypothesis exist in the local
context. -/
meta def find_opposite_hyp : tactic name :=
do lc ← local_context,
h :: _ ← lc.mfilter $ is_opposite | fail "No hypotheses of the form Xᵒᵖ",
return h.local_pp_name
end op_induction
open op_induction
/-- A version of `induction x using opposite.rec` which finds the appropriate hypothesis
automatically, for use with `local attribute [tidy] op_induction'`. This is necessary because
`induction x` is not able to deduce that `opposite.rec` should be used. -/
meta def op_induction' : tactic unit :=
do h ← find_opposite_hyp,
h' ← tactic.get_local h,
tactic.induction' h' [] `opposite.rec
end tactic
|
95614129d19c3d81effb076e229dfb3ccf75dce2 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/control/traversable/equiv.lean | 02b8ff3d878f827d384334f0ff8663eddf63804b | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 6,229 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.lemmas
import data.equiv.basic
/-!
# Transferring `traversable` instances along isomorphisms
This file allows to transfer `traversable` instances along isomorphisms.
## Main declarations
* `equiv.map`: Turns functorially a function `α → β` into a function `t' α → t' β` using the functor
`t` and the equivalence `Π α, t α ≃ t' α`.
* `equiv.functor`: `equiv.map` as a functor.
* `equiv.traverse`: Turns traversably a function `α → m β` into a function `t' α → m (t' β)` using
the traversable functor `t` and the equivalence `Π α, t α ≃ t' α`.
* `equiv.traversable`: `equiv.traverse` as a traversable functor.
* `equiv.is_lawful_traversable`: `equiv.traverse` as a lawful traversable functor.
-/
universes u
namespace equiv
section functor
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [functor t]
open functor
/-- Given a functor `t`, a function `t' : Type u → Type u`, and
equivalences `t α ≃ t' α` for all `α`, then every function `α → β` can
be mapped to a function `t' α → t' β` functorially (see
`equiv.functor`). -/
protected def map {α β : Type u} (f : α → β) (x : t' α) : t' β :=
eqv β $ map f ((eqv α).symm x)
/-- The function `equiv.map` transfers the functoriality of `t` to
`t'` using the equivalences `eqv`. -/
protected def functor : functor t' :=
{ map := @equiv.map _ }
variables [is_lawful_functor t]
protected lemma id_map {α : Type u} (x : t' α) : equiv.map id x = x :=
by simp [equiv.map, id_map]
protected lemma comp_map {α β γ : Type u} (g : α → β) (h : β → γ) (x : t' α) :
equiv.map (h ∘ g) x = equiv.map h (equiv.map g x) :=
by simp [equiv.map]; apply comp_map
protected lemma is_lawful_functor : @is_lawful_functor _ equiv.functor :=
{ id_map := @equiv.id_map _ _,
comp_map := @equiv.comp_map _ _ }
protected lemma is_lawful_functor' [F : _root_.functor t']
(h₀ : ∀ {α β} (f : α → β), _root_.functor.map f = equiv.map f)
(h₁ : ∀ {α β} (f : β), _root_.functor.map_const f = (equiv.map ∘ function.const α) f) :
_root_.is_lawful_functor t' :=
begin
have : F = equiv.functor,
{ casesI F, dsimp [equiv.functor],
congr; ext; [rw ← h₀, rw ← h₁] },
substI this,
exact equiv.is_lawful_functor
end
end functor
section traversable
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [traversable t]
variables {m : Type u → Type u} [applicative m]
variables {α β : Type u}
/-- Like `equiv.map`, a function `t' : Type u → Type u` can be given
the structure of a traversable functor using a traversable functor
`t'` and equivalences `t α ≃ t' α` for all α. See `equiv.traversable`. -/
protected def traverse (f : α → m β) (x : t' α) : m (t' β) :=
eqv β <$> traverse f ((eqv α).symm x)
/-- The function `equiv.traverse` transfers a traversable functor
instance across the equivalences `eqv`. -/
protected def traversable : traversable t' :=
{ to_functor := equiv.functor eqv,
traverse := @equiv.traverse _ }
end traversable
section equiv
parameters {t t' : Type u → Type u}
parameters (eqv : Π α, t α ≃ t' α)
variables [traversable t] [is_lawful_traversable t]
variables {F G : Type u → Type u} [applicative F] [applicative G]
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables (η : applicative_transformation F G)
variables {α β γ : Type u}
open is_lawful_traversable functor
protected lemma id_traverse (x : t' α) :
equiv.traverse eqv id.mk x = x :=
by simp! [equiv.traverse,id_bind,id_traverse,functor.map] with functor_norm
protected lemma traverse_eq_map_id (f : α → β) (x : t' α) :
equiv.traverse eqv (id.mk ∘ f) x = id.mk (equiv.map eqv f x) :=
by simp [equiv.traverse, traverse_eq_map_id] with functor_norm; refl
protected lemma comp_traverse (f : β → F γ) (g : α → G β) (x : t' α) :
equiv.traverse eqv (comp.mk ∘ functor.map f ∘ g) x =
comp.mk (equiv.traverse eqv f <$> equiv.traverse eqv g x) :=
by simp [equiv.traverse,comp_traverse] with functor_norm; congr; ext; simp
protected lemma naturality (f : α → F β) (x : t' α) :
η (equiv.traverse eqv f x) = equiv.traverse eqv (@η _ ∘ f) x :=
by simp only [equiv.traverse] with functor_norm
/-- The fact that `t` is a lawful traversable functor carries over the
equivalences to `t'`, with the traversable functor structure given by
`equiv.traversable`. -/
protected def is_lawful_traversable : @is_lawful_traversable t' (equiv.traversable eqv) :=
{ to_is_lawful_functor := @equiv.is_lawful_functor _ _ eqv _ _,
id_traverse := @equiv.id_traverse _ _,
comp_traverse := @equiv.comp_traverse _ _,
traverse_eq_map_id := @equiv.traverse_eq_map_id _ _,
naturality := @equiv.naturality _ _ }
/-- If the `traversable t'` instance has the properties that `map`,
`map_const`, and `traverse` are equal to the ones that come from
carrying the traversable functor structure from `t` over the
equivalences, then the fact that `t` is a lawful traversable functor
carries over as well. -/
protected def is_lawful_traversable' [_i : traversable t']
(h₀ : ∀ {α β} (f : α → β),
map f = equiv.map eqv f)
(h₁ : ∀ {α β} (f : β),
map_const f = (equiv.map eqv ∘ function.const α) f)
(h₂ : ∀ {F : Type u → Type u} [applicative F],
by exactI ∀ [is_lawful_applicative F]
{α β} (f : α → F β),
traverse f = equiv.traverse eqv f) :
_root_.is_lawful_traversable t' :=
begin
-- we can't use the same approach as for `is_lawful_functor'` because
-- h₂ needs a `is_lawful_applicative` assumption
refine {to_is_lawful_functor :=
equiv.is_lawful_functor' eqv @h₀ @h₁, ..}; introsI,
{ rw [h₂, equiv.id_traverse], apply_instance },
{ rw [h₂, equiv.comp_traverse f g x, h₂], congr,
rw [h₂], all_goals { apply_instance } },
{ rw [h₂, equiv.traverse_eq_map_id, h₀]; apply_instance },
{ rw [h₂, equiv.naturality, h₂]; apply_instance }
end
end equiv
end equiv
|
0a4a8c56a856bd68575a2159eb6516de1875ee9e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Util/Log.lean | 58f4178d946bda942ca60db4819c968e3dae5171 | [
"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 | 3,507 | lean | /-
Copyright (c) 2021 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Util.Error
import Lake.Util.OptionIO
namespace Lake
inductive LogLevel
| info
| warning
| error
inductive Verbosity : Type u
| quiet
| normal
| verbose
deriving BEq
instance : Inhabited Verbosity := ⟨.normal⟩
/-! # Class -/
class MonadLog (m : Type u → Type v) where
getVerbosity : m Verbosity
log (message : String) (level : LogLevel) : m PUnit
export MonadLog (log getVerbosity)
def getIsVerbose [Functor m] [MonadLog m] : m Bool :=
getVerbosity <&> (· == .verbose)
def getIsQuiet [Functor m] [MonadLog m] : m Bool :=
getVerbosity <&> (· == .quiet)
@[inline] def logVerbose [Monad m] [MonadLog m] (message : String) : m PUnit := do
if (← getIsVerbose) then log message .info
@[inline] def logInfo [Monad m] [MonadLog m] (message : String) : m PUnit := do
if !(← getIsQuiet) then log message .info
abbrev logWarning [MonadLog m] (message : String) : m PUnit :=
log message .warning
abbrev logError [MonadLog m] (message : String) : m PUnit :=
log message .error
namespace MonadLog
def nop [Pure m] : MonadLog m :=
⟨pure .normal, fun _ _ => pure ()⟩
instance [Pure m] : Inhabited (MonadLog m) := ⟨MonadLog.nop⟩
def io [MonadLiftT BaseIO m] (verbosity := Verbosity.normal) : MonadLog m where
getVerbosity := (pure verbosity : BaseIO _)
log msg
| .info => IO.println msg.trim |>.catchExceptions fun _ => pure ()
| .warning => IO.eprintln s!"warning: {msg.trim}" |>.catchExceptions fun _ => pure ()
| .error => IO.eprintln s!"error: {msg.trim}" |>.catchExceptions fun _ => pure ()
def eio [MonadLiftT BaseIO m] (verbosity := Verbosity.normal) : MonadLog m where
getVerbosity := (pure verbosity : BaseIO _)
log msg
| .info => IO.eprintln s!"info: {msg.trim}" |>.catchExceptions fun _ => pure ()
| .warning => IO.eprintln s!"warning: {msg.trim}" |>.catchExceptions fun _ => pure ()
| .error => IO.eprintln s!"error: {msg.trim}" |>.catchExceptions fun _ => pure ()
def lift [MonadLiftT m n] (self : MonadLog m) : MonadLog n where
getVerbosity := liftM <| self.getVerbosity
log msg lv := liftM <| self.log msg lv
instance [MonadLift m n] [methods : MonadLog m] : MonadLog n := lift methods
/-- Log the given error message and then fail. -/
protected def error [Alternative m] [MonadLog m] (msg : String) : m α :=
logError msg *> failure
end MonadLog
/-! # Transformers -/
abbrev MonadLogT (m : Type u → Type v) (n : Type v → Type w) :=
ReaderT (MonadLog m) n
instance [Pure n] [Inhabited α] : Inhabited (MonadLogT m n α) :=
⟨fun _ => pure Inhabited.default⟩
instance [Monad n] [MonadLiftT m n] : MonadLog (MonadLogT m n) where
getVerbosity := do (← read).getVerbosity
log msg lv := do (← read).log msg lv
abbrev MonadLogT.adaptMethods [Monad n]
(f : MonadLog m → MonadLog m') (self : MonadLogT m' n α) : MonadLogT m n α :=
ReaderT.adapt f self
abbrev MonadLogT.ignoreLog [Pure m] (self : MonadLogT m n α) : n α :=
self MonadLog.nop
abbrev LogIO :=
MonadLogT BaseIO OptionIO
instance : MonadError LogIO := ⟨MonadLog.error⟩
instance : MonadLift IO LogIO := ⟨MonadError.runIO⟩
def LogIO.captureLog (self : LogIO α) (verbosity := Verbosity.normal) : BaseIO (String × Option α) :=
IO.FS.withIsolatedStreams <| self (MonadLog.eio verbosity) |>.toBaseIO
abbrev LogT (m : Type → Type) :=
MonadLogT m m
|
10a3070a8a886e24110e7a95638cb3d6dc5f596d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/convex/combination.lean | 9d77210e94389bb4e0e5399a47dbe03d0d096229 | [
"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 | 20,191 | lean | /-
Copyright (c) 2019 Yury Kudriashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudriashov
-/
import algebra.big_operators.order
import analysis.convex.hull
import linear_algebra.affine_space.basis
/-!
# Convex combinations
This file defines convex combinations of points in a vector space.
## Main declarations
* `finset.center_mass`: Center of mass of a finite family of points.
## Implementation notes
We divide by the sum of the weights in the definition of `finset.center_mass` because of the way
mathematical arguments go: one doesn't change weights, but merely adds some. This also makes a few
lemmas unconditional on the sum of the weights being `1`.
-/
open set
open_locale big_operators classical pointwise
universes u u'
variables {R E F ι ι' : Type*} [linear_ordered_field R] [add_comm_group E] [add_comm_group F]
[module R E] [module R F] {s : set E}
/-- Center of mass of a finite collection of points with prescribed weights.
Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/
def finset.center_mass (t : finset ι) (w : ι → R) (z : ι → E) : E :=
(∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i)
variables (i j : ι) (c : R) (t : finset ι) (w : ι → R) (z : ι → E)
open finset
lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 :=
by simp only [center_mass, sum_empty, smul_zero]
lemma finset.center_mass_pair (hne : i ≠ j) :
({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j :=
by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul]
variable {w}
lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) :
(insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i +
((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z :=
begin
simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul],
congr' 2,
rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div]
end
lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i :=
by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul]
lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) :
t.center_mass w z = ∑ i in t, w i • z i :=
by simp only [finset.center_mass, hw, inv_one, one_smul]
lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z :=
by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc]
/-- A convex combination of two centers of mass is a center of mass as well. This version
deals with two different index types. -/
lemma finset.center_mass_segment'
(s : finset ι) (t : finset ι') (ws : ι → R) (zs : ι → E) (wt : ι' → R) (zt : ι' → E)
(hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : R) (hab : a + b = 1) :
a • s.center_mass ws zs + b • t.center_mass wt zt =
(s.map function.embedding.inl ∪ t.map function.embedding.inr).center_mass
(sum.elim (λ i, a * ws i) (λ j, b * wt j))
(sum.elim zs zt) :=
begin
rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt,
smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1],
{ congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] },
{ rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] }
end
/-- A convex combination of two centers of mass is a center of mass as well. This version
works if two centers of mass share the set of original points. -/
lemma finset.center_mass_segment
(s : finset ι) (w₁ w₂ : ι → R) (z : ι → E)
(hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : R) (hab : a + b = 1) :
a • s.center_mass w₁ z + b • s.center_mass w₂ z =
s.center_mass (λ i, a * w₁ i + b * w₂ i) z :=
have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1,
by simp only [mul_sum.symm, sum_add_distrib, mul_one, *],
by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *]
lemma finset.center_mass_ite_eq (hi : i ∈ t) :
t.center_mass (λ j, if (i = j) then (1 : R) else 0) z = z i :=
begin
rw [finset.center_mass_eq_of_sum_1],
transitivity ∑ j in t, if (i = j) then z i else 0,
{ congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] },
{ rw [sum_ite_eq, if_pos hi] },
{ rw [sum_ite_eq, if_pos hi] }
end
variables {t w}
lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t')
(h : ∀ i ∈ t', i ∉ t → w i = 0) :
t.center_mass w z = t'.center_mass w z :=
begin
rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum],
apply sum_subset ht,
assume i hit' hit,
rw [h i hit' hit, zero_smul, smul_zero]
end
lemma finset.center_mass_filter_ne_zero :
(t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z :=
finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit',
by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit'
variable {z}
/-- The center of mass of a finite subset of a convex set belongs to the set
provided that all weights are non-negative, and the total weight is positive. -/
lemma convex.center_mass_mem (hs : convex R s) :
(∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s :=
begin
induction t using finset.induction with i t hi ht, { simp [lt_irrefl] },
intros h₀ hpos hmem,
have zi : z i ∈ s, from hmem _ (mem_insert_self _ _),
have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj,
rw [sum_insert hi] at hpos,
by_cases hsum_t : ∑ j in t, w j = 0,
{ have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t,
have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]),
simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero],
simp only [hsum_t, add_zero] at hpos,
rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul],
exact zi },
{ rw [finset.center_mass_insert _ _ _ hi hsum_t],
refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos,
{ exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) },
{ intros j hj, exact hmem j (mem_insert_of_mem hj) },
{ exact h₀ _ (mem_insert_self _ _) } }
end
lemma convex.sum_mem (hs : convex R s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1)
(hz : ∀ i ∈ t, z i ∈ s) :
∑ i in t, w i • z i ∈ s :=
by simpa only [h₁, center_mass, inv_one, one_smul] using
hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz
lemma convex_iff_sum_mem :
convex R s ↔
(∀ (t : finset E) (w : E → R),
(∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) :=
begin
refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩,
intros h x y hx hy a b ha hb hab,
by_cases h_cases: x = y,
{ rw [h_cases, ←add_smul, hab, one_smul], exact hy },
{ convert h {x, y} (λ z, if z = y then b else a) _ _ _,
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] },
{ simp_intros i hi,
cases hi; subst i; simp [ha, hb, if_neg h_cases] },
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] },
{ simp_intros i hi,
cases hi; subst i; simp [hx, hy, if_neg h_cases] } }
end
lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i)
(hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) :
t.center_mass w z ∈ convex_hull R s :=
(convex_convex_hull R s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull R s $ hz i hi)
/-- A refinement of `finset.center_mass_mem_convex_hull` when the indexed family is a `finset` of
the space. -/
lemma finset.center_mass_id_mem_convex_hull (t : finset E) {w : E → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i)
(hws : 0 < ∑ i in t, w i) :
t.center_mass w id ∈ convex_hull R (t : set E) :=
t.center_mass_mem_convex_hull hw₀ hws (λ i, mem_coe.2)
lemma affine_combination_eq_center_mass {ι : Type*} {t : finset ι} {p : ι → E} {w : ι → R}
(hw₂ : ∑ i in t, w i = 1) :
affine_combination t p w = center_mass t w p :=
begin
rw [affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ w _ hw₂ (0 : E),
finset.weighted_vsub_of_point_apply, vadd_eq_add, add_zero, t.center_mass_eq_of_sum_1 _ hw₂],
simp_rw [vsub_eq_sub, sub_zero],
end
lemma affine_combination_mem_convex_hull
{s : finset ι} {v : ι → E} {w : ι → R} (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1) :
s.affine_combination v w ∈ convex_hull R (range v) :=
begin
rw affine_combination_eq_center_mass hw₁,
apply s.center_mass_mem_convex_hull hw₀,
{ simp [hw₁], },
{ simp, },
end
/-- The centroid can be regarded as a center of mass. -/
@[simp] lemma finset.centroid_eq_center_mass (s : finset ι) (hs : s.nonempty) (p : ι → E) :
s.centroid R p = s.center_mass (s.centroid_weights R) p :=
affine_combination_eq_center_mass (s.sum_centroid_weights_eq_one_of_nonempty R hs)
lemma finset.centroid_mem_convex_hull (s : finset E) (hs : s.nonempty) :
s.centroid R id ∈ convex_hull R (s : set E) :=
begin
rw s.centroid_eq_center_mass hs,
apply s.center_mass_id_mem_convex_hull,
{ simp only [inv_nonneg, implies_true_iff, nat.cast_nonneg, finset.centroid_weights_apply], },
{ have hs_card : (s.card : R) ≠ 0, { simp [finset.nonempty_iff_ne_empty.mp hs] },
simp only [hs_card, finset.sum_const, nsmul_eq_mul, mul_inv_cancel, ne.def, not_false_iff,
finset.centroid_weights_apply, zero_lt_one] }
end
lemma convex_hull_range_eq_exists_affine_combination (v : ι → E) :
convex_hull R (range v) = { x | ∃ (s : finset ι) (w : ι → R)
(hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1), s.affine_combination v w = x } :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
obtain ⟨i, hi⟩ := set.mem_range.mp hx,
refine ⟨{i}, function.const ι (1 : R), by simp, by simp, by simp [hi]⟩, },
{ rw convex,
rintros x y ⟨s, w, hw₀, hw₁, rfl⟩ ⟨s', w', hw₀', hw₁', rfl⟩ a b ha hb hab,
let W : ι → R := λ i, (if i ∈ s then a * w i else 0) + (if i ∈ s' then b * w' i else 0),
have hW₁ : (s ∪ s').sum W = 1,
{ rw [sum_add_distrib, ← sum_subset (subset_union_left s s'),
← sum_subset (subset_union_right s s'), sum_ite_of_true _ _ (λ i hi, hi),
sum_ite_of_true _ _ (λ i hi, hi), ← mul_sum, ← mul_sum, hw₁, hw₁', ← add_mul, hab, mul_one];
intros i hi hi';
simp [hi'], },
refine ⟨s ∪ s', W, _, hW₁, _⟩,
{ rintros i -,
by_cases hi : i ∈ s;
by_cases hi' : i ∈ s';
simp [hi, hi', add_nonneg, mul_nonneg ha (hw₀ i _), mul_nonneg hb (hw₀' i _)], },
{ simp_rw [affine_combination_eq_linear_combination (s ∪ s') v _ hW₁,
affine_combination_eq_linear_combination s v w hw₁,
affine_combination_eq_linear_combination s' v w' hw₁', add_smul, sum_add_distrib],
rw [← sum_subset (subset_union_left s s'), ← sum_subset (subset_union_right s s')],
{ simp only [ite_smul, sum_ite_of_true _ _ (λ i hi, hi), mul_smul, ← smul_sum], },
{ intros i hi hi', simp [hi'], },
{ intros i hi hi', simp [hi'], }, }, },
{ rintros x ⟨s, w, hw₀, hw₁, rfl⟩,
exact affine_combination_mem_convex_hull hw₀ hw₁, },
end
/-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`.
This version allows finsets in any type in any universe. -/
lemma convex_hull_eq (s : set E) :
convex_hull R s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → R) (z : ι → E)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s),
t.center_mass w z = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one,
finset.sum_singleton, λ _ _, hx],
simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] },
{ rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩
a b ha hb hab,
rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, _, _, _, _, rfl⟩,
{ rintros i hi,
rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩;
simp only [sum.elim_inl, sum.elim_inr];
apply_rules [mul_nonneg, hwx₀, hwy₀] },
{ simp [finset.sum_sum_elim, finset.mul_sum.symm, *] },
{ intros i hi,
rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } },
{ rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz }
end
lemma finset.convex_hull_eq (s : finset E) :
convex_hull R ↑s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1),
s.center_mass w id = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
rw [finset.mem_coe] at hx,
refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩,
{ intros, split_ifs, exacts [zero_le_one, le_refl 0] },
{ rw [finset.sum_ite_eq, if_pos hx] } },
{ rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩
a b ha hb hab,
rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, rfl⟩,
{ rintros i hi,
apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], },
{ simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } },
{ rintros _ ⟨w, hw₀, hw₁, rfl⟩,
exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx)
(hw₁.symm ▸ zero_lt_one) (λ x hx, hx) }
end
lemma set.finite.convex_hull_eq {s : set E} (hs : s.finite) :
convex_hull R s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y)
(hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} :=
by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop]
using hs.to_finset.convex_hull_eq
/-- A weak version of Carathéodory's theorem. -/
lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) :
convex_hull R s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull R ↑t :=
begin
refine subset.antisymm _ _,
{ rw convex_hull_eq,
rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
simp only [mem_Union],
refine ⟨t.image z, _, _⟩,
{ rw [coe_image, set.image_subset_iff],
exact hz },
{ apply t.center_mass_mem_convex_hull hw₀,
{ simp only [hw₁, zero_lt_one] },
{ exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } },
{ exact Union_subset (λ i, Union_subset convex_hull_mono), },
end
lemma mk_mem_convex_hull_prod {t : set F} {x : E} {y : F} (hx : x ∈ convex_hull R s)
(hy : y ∈ convex_hull R t) :
(x, y) ∈ convex_hull R (s ×ˢ t) :=
begin
rw convex_hull_eq at ⊢ hx hy,
obtain ⟨ι, a, w, S, hw, hw', hS, hSp⟩ := hx,
obtain ⟨κ, b, v, T, hv, hv', hT, hTp⟩ := hy,
have h_sum : ∑ (i : ι × κ) in a.product b, w i.fst * v i.snd = 1,
{ rw [finset.sum_product, ← hw'],
congr,
ext i,
have : ∑ (y : κ) in b, w i * v y = ∑ (y : κ) in b, v y * w i,
{ congr, ext, simp [mul_comm] },
rw [this, ← finset.sum_mul, hv'],
simp },
refine ⟨ι × κ, a.product b, λ p, (w p.1) * (v p.2), λ p, (S p.1, T p.2),
λ p hp, _, h_sum, λ p hp, _, _⟩,
{ rw mem_product at hp,
exact mul_nonneg (hw p.1 hp.1) (hv p.2 hp.2) },
{ rw mem_product at hp,
exact ⟨hS p.1 hp.1, hT p.2 hp.2⟩ },
ext,
{ rw [←hSp, finset.center_mass_eq_of_sum_1 _ _ hw', finset.center_mass_eq_of_sum_1 _ _ h_sum],
simp_rw [prod.fst_sum, prod.smul_mk],
rw finset.sum_product,
congr,
ext i,
have : ∑ (j : κ) in b, (w i * v j) • S i = ∑ (j : κ) in b, v j • w i • S i,
{ congr, ext, rw [mul_smul, smul_comm] },
rw [this, ←finset.sum_smul, hv', one_smul] },
{ rw [←hTp, finset.center_mass_eq_of_sum_1 _ _ hv', finset.center_mass_eq_of_sum_1 _ _ h_sum],
simp_rw [prod.snd_sum, prod.smul_mk],
rw [finset.sum_product, finset.sum_comm],
congr,
ext j,
simp_rw mul_smul,
rw [←finset.sum_smul, hw', one_smul] }
end
@[simp] lemma convex_hull_prod (s : set E) (t : set F) :
convex_hull R (s ×ˢ t) = convex_hull R s ×ˢ convex_hull R t :=
subset.antisymm (convex_hull_min (prod_mono (subset_convex_hull _ _) $ subset_convex_hull _ _) $
(convex_convex_hull _ _).prod $ convex_convex_hull _ _) $
prod_subset_iff.2 $ λ x hx y, mk_mem_convex_hull_prod hx
lemma convex_hull_add (s t : set E) : convex_hull R (s + t) = convex_hull R s + convex_hull R t :=
by simp_rw [←image2_add, ←image_prod, is_linear_map.is_linear_map_add.convex_hull_image,
convex_hull_prod]
lemma convex_hull_sub (s t : set E) : convex_hull R (s - t) = convex_hull R s - convex_hull R t :=
by simp_rw [sub_eq_add_neg, convex_hull_add, convex_hull_neg]
/-! ### `std_simplex` -/
variables (ι) [fintype ι] {f : ι → R}
/-- `std_simplex 𝕜 ι` is the convex hull of the canonical basis in `ι → 𝕜`. -/
lemma convex_hull_basis_eq_std_simplex :
convex_hull R (range $ λ(i j:ι), if i = j then (1:R) else 0) = std_simplex R ι :=
begin
refine subset.antisymm (convex_hull_min _ (convex_std_simplex R ι)) _,
{ rintros _ ⟨i, rfl⟩,
exact ite_eq_mem_std_simplex R i },
{ rintros w ⟨hw₀, hw₁⟩,
rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁],
exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i)
(hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) }
end
variable {ι}
/-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ`
under the linear map sending each function `w` to `∑ x in s, w x • x`.
Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`.
The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need
to prove that this map is linear. -/
lemma set.finite.convex_hull_eq_image {s : set E} (hs : s.finite) :
convex_hull R s = by haveI := hs.fintype; exact
(⇑(∑ x : s, (@linear_map.proj R s _ (λ i, R) _ _ x).smul_right x.1)) '' (std_simplex R s) :=
begin
rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)],
apply congr_arg,
convert subtype.range_coe.symm,
ext x,
simp [linear_map.sum_apply, ite_smul, finset.filter_eq]
end
/-- All values of a function `f ∈ std_simplex 𝕜 ι` belong to `[0, 1]`. -/
lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex R ι) (x) :
f x ∈ Icc (0 : R) 1 :=
⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩
/-- The convex hull of an affine basis is the intersection of the half-spaces defined by the
corresponding barycentric coordinates. -/
lemma convex_hull_affine_basis_eq_nonneg_barycentric {ι : Type*} (b : affine_basis ι R E) :
convex_hull R (range b.points) = { x | ∀ i, 0 ≤ b.coord i x } :=
begin
rw convex_hull_range_eq_exists_affine_combination,
ext x,
split,
{ rintros ⟨s, w, hw₀, hw₁, rfl⟩ i,
by_cases hi : i ∈ s,
{ rw b.coord_apply_combination_of_mem hi hw₁,
exact hw₀ i hi, },
{ rw b.coord_apply_combination_of_not_mem hi hw₁, }, },
{ intros hx,
have hx' : x ∈ affine_span R (range b.points),
{ rw b.tot, exact affine_subspace.mem_top R E x, },
obtain ⟨s, w, hw₁, rfl⟩ := (mem_affine_span_iff_eq_affine_combination R E).mp hx',
refine ⟨s, w, _, hw₁, rfl⟩,
intros i hi,
specialize hx i,
rw b.coord_apply_combination_of_mem hi hw₁ at hx,
exact hx, },
end
|
c9eb85ab45114ae5173f2abad825cd34ddca3c3e | 952248371e69ccae722eb20bfe6815d8641554a8 | /src/rat_additions.lean | c9d64f915de339849ac75a3c4c9c638c7c06d4d5 | [] | no_license | robertylewis/lean_polya | 5fd079031bf7114449d58d68ccd8c3bed9bcbc97 | 1da14d60a55ad6cd8af8017b1b64990fccb66ab7 | refs/heads/master | 1,647,212,226,179 | 1,558,108,354,000 | 1,558,108,354,000 | 89,933,264 | 1 | 2 | null | 1,560,964,118,000 | 1,493,650,551,000 | Lean | UTF-8 | Lean | false | false | 8,596 | lean | import data.rat data.nat.gcd tactic.finish algebra.group_power
--meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-"++↑(k+1)++"")⟩
meta instance int.reflect : has_reflect int
| (int.of_nat n) :=
if n = 0 then unchecked_cast `(0 : int)
else if n = 1 then unchecked_cast `(1 : int)
else if n % 2 = 0 then unchecked_cast $ `(λ n : int, bit0 n).subst (int.reflect ↑(n / 2))
else unchecked_cast $ `(λ n : int, bit1 n).subst (int.reflect ↑(n / 2))
| (int.neg_succ_of_nat n) := let rv := int.reflect (int.of_nat (n+1)) in unchecked_cast `(-%%rv : ℤ)
/-meta def f (z : ℤ) : expr := `(z)
set_option pp.all true
run_cmd tactic.trace $ f (-10)-/
--def rat_of_int (i : ℤ) : ℚ := --⟦⟨i, 1, zero_lt_one⟩⟧
--{ num := i, denom := 1,
/-meta def num_denum.to_expr : rat.num_denum → expr
| (num, ⟨denum, _⟩) := `((rat.of_int %%(int.reflect num)) / (rat.of_int (%%(int.reflect denum)) : ℚ))
meta def num_denum_to_expr_wf : Π a b : rat.num_denum, rat.rel a b → num_denum.to_expr a = num_denum.to_expr b := sorry
meta def rat.to_expr :=
quot.lift num_denum.to_expr num_denum_to_expr_wf
meta instance rat.reflect : has_reflect rat :=
λ q, unchecked_cast $ q.to_expr
-/
private meta def nat_to_rat_expr : nat → expr | n :=
if n = 0 then `(0 : ℚ)
else if n = 1 then `(1 : ℚ)
else if n % 2 = 0 then `(@bit0 ℚ _ %%(nat_to_rat_expr (n/2)))
else `(@bit1 ℚ _ _ %%(nat_to_rat_expr (n/2)))
private meta def int_to_rat_expr : int → expr | n :=
if n = 0 then `(0 : ℚ)
else if n < 0 then `(-%%(int_to_rat_expr (-n)) : ℚ)
else if n = 1 then `(1 : ℚ)
else if n % 2 = 0 then `(@bit0 ℚ _ %%(int_to_rat_expr (n/2)))
else `(@bit1 ℚ _ _ %%(int_to_rat_expr (n/2)))
meta def rat.to_expr (q : ℚ) : expr :=
if q.denom = 1 then
`(%%(int_to_rat_expr q.num) : ℚ)
else
`(%%(int_to_rat_expr q.num) / %%(nat_to_rat_expr q.denom) : ℚ)
--`(rat.mk_nat %%(int.reflect q.num) %%(nat.reflect q.denom))
meta instance rat.reflect : has_reflect rat :=
λ q, unchecked_cast $ q.to_expr
section
open nat
theorem gcd_ne_zero_right (a : ℕ) {b : ℕ} (hb : b ≠ 0) : gcd a b ≠ 0 :=
assume : gcd a b = 0,
have gcd a b ∣ b, from gcd_dvd_right _ _,
have 0 ∣ b, by cc,
have b = 0, from eq_zero_of_zero_dvd this,
by contradiction
end
def sign {α} [decidable_linear_ordered_comm_ring α] (a : α) : α :=
if a < 0 then (-1) else if a = 0 then 0 else 1
/-
section
open int
def int.gcd : ℤ → ℤ → ℤ
| (of_nat k1) (of_nat k2) := of_nat (nat.gcd k1 k2)
| (of_nat k1) (neg_succ_of_nat k2) := of_nat (nat.gcd k1 (k2+1))
| (neg_succ_of_nat k1) (of_nat k2) := of_nat (nat.gcd (k1+1) k2)
| (neg_succ_of_nat k1) (neg_succ_of_nat k2) := of_nat (nat.gcd (k1+1) (k2+1))
/-def int.sign : ℤ → ℤ
--| (of_nat 0) := 0
| (of_nat k) := if k = 0 then 0 else 1
| (neg_succ_of_nat _) := -1-/
/-def int.div : ℤ → ℤ → ℤ
| (of_nat k1) (of_nat k2) := of_nat (k1 / k2)
| (of_nat k1) (neg_succ_of_nat k2) := neg_succ_of_nat (k1 / (k2+1))
| (neg_succ_of_nat k1) (of_nat k2) := neg_succ_of_nat ((k1) / k2)
| (neg_succ_of_nat k1) (neg_succ_of_nat k2) := of_nat ((k1+1) / (k2+1))-/
def int.div (a b : ℤ) : ℤ :=
sign b *
(match a with
| of_nat m := of_nat (m / (nat_abs b))
| -[1+m] := -[1+ ((m:nat) / (nat_abs b))]
end)
instance : has_div int := ⟨int.div⟩
theorem int.of_nat_ne_zero_of_ne_zero {n : ℕ} (h : n ≠ 0) : of_nat n ≠ 0 :=
suppose of_nat n = of_nat 0,
by cc
@[ematch]
theorem int_gcd_ne_zero_right : Π (a : ℤ) {b : ℤ} (h : b ≠ 0), int.gcd a b ≠ 0 :=
begin
intros,
induction a,
all_goals {induction b; apply int.of_nat_ne_zero_of_ne_zero; apply gcd_ne_zero_right; finish}
end
theorem int.gcd_pos_of_ne_right (a : ℤ) {b : ℤ} (h : b ≠ 0) : int.gcd a b > 0 :=
begin
induction a,
all_goals {induction b; unfold int.gcd; apply of_nat_p},
end
/-
variable P : ℕ → Prop
theorem f : Π (h : P 0) (h2 : ∀ n, P n → P (n+1)), Π (n : ℕ), P n
| h h2 0 := sorry --begin try {do n ← decl_name, interactive.clear [n]}; finish end
| h h2 (k+1) := begin apply h2, apply f, apply h, apply h2 end
theorem int_gcd_ne_zero_right' : Π (a : ℤ) {b : ℤ} (h : b ≠ 0), int.gcd a b ≠ 0 :=
begin
intros,
cases a; cases b,
safe [int_gcd_ne_zero_right],
-/
/-| (of_nat k1) (of_nat k2) h := begin safe end
| (of_nat k1) (neg_succ_of_nat k2) h := sorry
| (neg_succ_of_nat k1) (of_nat k2) h := sorry
| (neg_succ_of_nat k1) (neg_succ_of_nat k2) h := sorry
-/
def num_denum.reduce : rat.num_denum → rat.num_denum | (num, ⟨denum, _⟩) :=
let g := int.gcd num denum in
(num/g, ⟨denum/g, begin end⟩)-/
/-set_option pp.all true
run_cmd tactic.trace $ (↑`(-5 : ℤ) : expr)
meta example (z : ℤ) : reflected z := by apply_instance
-/
/-
| n := if n = 0 then unchecked_cast `(0 : nat)
else if n % 2 = 0 then unchecked_cast $ `(λ n : nat, bit0 n).subst (nat.reflect (n / 2))
else unchecked_cast $ `(λ n : nat, bit1 n).subst (nat.reflect (n / 2))
-/
-- make this more efficient. Why did it disappear?
--meta instance : has_to_pexpr ℕ := ⟨λ n, nat.rec_on n ``(0) (λ _ k, ``(%%k + 1))⟩
--meta instance : has_to_pexpr ℤ :=
--⟨λ z, int.rec_on z (λ k, ``(%%k)) (λ k, ``(-(%%(k)+1)))⟩
/-meta def num_denum_format : rat.num_denum → format
| (num, ⟨denum, _⟩) :=
if num = 0 then "0"
--else if denum = 1 then to_fmt num
else to_fmt num ++ "/" ++ to_fmt denum
-/
/-meta def num_denum_quote : rat.num_denum → pexpr
| (num, ⟨denum, _⟩) := ``(%%(to_pexpr num)/%%(to_pexpr denum))-/
--meta def num_denum_format_wf : Π a b : rat.num_denum, rat.rel a b → num_denum_format a = num_denum_format b := sorry
--meta def num_denum_quote_wf : Π a b : rat.num_denum, rat.rel a b → num_denum_quote a = num_denum_quote b := sorry
meta def rat.to_string (q : ℚ) : string :=
if q.denom = 1 then
to_string q.num
else
to_string q.num ++ " / " ++ to_string q.denom
meta def rat.to_format (q : ℚ) : format :=
/-if q.denom = 1 then
to_fmt q.num
else
to_fmt q.num ++ " / " ++ to_fmt q.denom-/
rat.to_string q
/-meta instance : has_to_pexpr ℚ :=
⟨quot.lift num_denum_quote num_denum_quote_wf⟩
-/
def rat.pow (q : ℚ) : ℤ → ℚ
| (int.of_nat n) := q^n
| -[1+n] := 1/(q^(n+1))
--def rat.pow (q : ℚ) (z : ℤ) : ℚ :=
--if q = 1 then q else if z = 1 then q else rat.pow_aux q z
lemma rat.mul_pow_neg_one {q : ℚ} (h : q ≠ 0) : q * (rat.pow q (-1)) = 1 :=
begin
change (-1 : ℤ) with -[1+0],
simp [rat.pow, mul_inv_cancel h]
end
lemma rat.pow_neg_one {q : ℚ} : rat.pow q (-1) = 1 / q :=
begin
change (-1 : ℤ) with -[1+0],
simp [rat.pow]
end
lemma rat.pow_one {q : ℚ} : rat.pow q 1 = q :=
begin
change (1 : ℤ) with int.of_nat 1,
simp [rat.pow]
end
lemma rat.pow_pow (a : ℚ) (z1 z2 : ℤ) : rat.pow (rat.pow a z1) z2 = rat.pow a (z1*z2) := sorry
lemma rat.one_div_pow (q : ℚ) (z : ℤ) : rat.pow (1/q) z = rat.pow q (-z) := sorry
namespace int
open nat
/-protected def div : ℤ → ℤ → ℤ
| (m : ℕ) (n : ℕ) := of_nat (m / n)
| (m : ℕ) -[1+ n] := -of_nat (m / succ n)
| -[1+ m] 0 := 0
| -[1+ m] (n+1:ℕ) := -[1+ m / succ n]
| -[1+ m] -[1+ n] := of_nat (succ (m / succ n))
instance : has_div int := ⟨int.div⟩
-/
theorem exists_eq_of_nat {z : ℤ} (h : z ≥ 0) : ∃ n : ℕ, z = n :=
match int.le.dest h with
| ⟨n, pr⟩ := ⟨n, by clear _match; finish⟩
end
end int
theorem nat.one_lt_pow_of_one_lt {x n : ℕ} (h : 1 < x) (hn : n > 0) : 1 < nat.pow x n :=
have h : nat.pow 1 n = 1, from nat.one_pow _,
begin
rw ←h, apply nat.pow_lt_pow_of_lt_left,
repeat {assumption}
end
theorem rat.one_pow : Π (n : ℤ), rat.pow 1 n = 1
| (int.of_nat n) := by simp [rat.pow]
| -[1+n] := by simp [rat.pow, one_inv_eq]
theorem rat.mul_pow (q r : ℚ) : Π (z : ℤ), rat.pow (q*r) z = rat.pow q z * rat.pow r z
| (int.of_nat n) := mul_pow _ _ _
| -[1+n] := begin unfold rat.pow, rw [mul_pow, div_mul_eq_div_mul_one_div] end
theorem rat.mul_pow_rev (q r : ℚ) (z : ℤ) : rat.pow q z * rat.pow r z = rat.pow (q*r) z := by simp [rat.mul_pow]
def rat.order : ℚ → ℚ → ordering :=
λ a b, if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt
def int.order : ℤ → ℤ → ordering :=
λ a b, if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt
|
3aaf8e048798bbeaf51f92d5d53fac078b9addd9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/affine_space/finite_dimensional_auto.lean | d5c4a74c528aa523012e9b5944d3b29d58f2ee10 | [] | 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 | 14,574 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Joseph Myers.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.affine_space.independent
import Mathlib.linear_algebra.finite_dimensional
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# Finite-dimensional subspaces of affine spaces.
This file provides a few results relating to finite-dimensional
subspaces of affine spaces.
## Main definitions
* `collinear` defines collinear sets of points as those that span a
subspace of dimension at most 1.
-/
/-- The `vector_span` of a finite set is finite-dimensional. -/
theorem finite_dimensional_vector_span_of_finite (k : Type u_1) {V : Type u_2} {P : Type u_3}
[field k] [add_comm_group V] [module k V] [add_torsor V P] {s : set P} (h : set.finite s) :
finite_dimensional k ↥(vector_span k s) :=
finite_dimensional.span_of_finite k (set.finite.vsub h h)
/-- The `vector_span` of a family indexed by a `fintype` is
finite-dimensional. -/
protected instance finite_dimensional_vector_span_of_fintype (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
[fintype ι] (p : ι → P) : finite_dimensional k ↥(vector_span k (set.range p)) :=
finite_dimensional_vector_span_of_finite k (set.finite_range p)
/-- The `vector_span` of a subset of a family indexed by a `fintype`
is finite-dimensional. -/
protected instance finite_dimensional_vector_span_image_of_fintype (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
[fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k ↥(vector_span k (p '' s)) :=
finite_dimensional_vector_span_of_finite k (set.finite.image p (set.finite.of_fintype s))
/-- The direction of the affine span of a finite set is
finite-dimensional. -/
theorem finite_dimensional_direction_affine_span_of_finite (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {s : set P}
(h : set.finite s) : finite_dimensional k ↥(affine_subspace.direction (affine_span k s)) :=
Eq.symm (direction_affine_span k s) ▸ finite_dimensional_vector_span_of_finite k h
/-- The direction of the affine span of a family indexed by a
`fintype` is finite-dimensional. -/
protected instance finite_dimensional_direction_affine_span_of_fintype (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
[fintype ι] (p : ι → P) :
finite_dimensional k ↥(affine_subspace.direction (affine_span k (set.range p))) :=
finite_dimensional_direction_affine_span_of_finite k (set.finite_range p)
/-- The direction of the affine span of a subset of a family indexed
by a `fintype` is finite-dimensional. -/
protected instance finite_dimensional_direction_affine_span_image_of_fintype (k : Type u_1)
{V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P]
{ι : Type u_4} [fintype ι] (p : ι → P) (s : set ι) :
finite_dimensional k ↥(affine_subspace.direction (affine_span k (p '' s))) :=
finite_dimensional_direction_affine_span_of_finite k
(set.finite.image p (set.finite.of_fintype s))
/-- The `vector_span` of a finite subset of an affinely independent
family has dimension one less than its cardinality. -/
theorem findim_vector_span_image_finset_of_affine_independent {k : Type u_1} {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
{p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) :
finite_dimensional.findim k ↥(vector_span k (p '' ↑s)) = n :=
sorry
/-- The `vector_span` of a finite affinely independent family has
dimension one less than its cardinality. -/
theorem findim_vector_span_of_affine_independent {k : Type u_1} {V : Type u_2} {P : Type u_3}
[field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4} [fintype ι]
{p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) :
finite_dimensional.findim k ↥(vector_span k (set.range p)) = n :=
sorry
/-- If the `vector_span` of a finite subset of an affinely independent
family lies in a submodule with dimension one less than its
cardinality, it equals that submodule. -/
theorem vector_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one
{k : Type u_1} {V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V]
[add_torsor V P] {ι : Type u_4} {p : ι → P} (hi : affine_independent k p) {s : finset ι}
{sm : submodule k V} [finite_dimensional k ↥sm] (hle : vector_span k (p '' ↑s) ≤ sm)
(hc : finset.card s = finite_dimensional.findim k ↥sm + 1) : vector_span k (p '' ↑s) = sm :=
finite_dimensional.eq_of_le_of_findim_eq hle
(findim_vector_span_image_finset_of_affine_independent hi hc)
/-- If the `vector_span` of a finite affinely independent
family lies in a submodule with dimension one less than its
cardinality, it equals that submodule. -/
theorem vector_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one {k : Type u_1}
{V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P]
{ι : Type u_4} [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V}
[finite_dimensional k ↥sm] (hle : vector_span k (set.range p) ≤ sm)
(hc : fintype.card ι = finite_dimensional.findim k ↥sm + 1) :
vector_span k (set.range p) = sm :=
finite_dimensional.eq_of_le_of_findim_eq hle (findim_vector_span_of_affine_independent hi hc)
/-- If the `affine_span` of a finite subset of an affinely independent
family lies in an affine subspace whose direction has dimension one
less than its cardinality, it equals that subspace. -/
theorem affine_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one
{k : Type u_1} {V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V]
[add_torsor V P] {ι : Type u_4} {p : ι → P} (hi : affine_independent k p) {s : finset ι}
{sp : affine_subspace k P} [finite_dimensional k ↥(affine_subspace.direction sp)]
(hle : affine_span k (p '' ↑s) ≤ sp)
(hc : finset.card s = finite_dimensional.findim k ↥(affine_subspace.direction sp) + 1) :
affine_span k (p '' ↑s) = sp :=
sorry
/-- If the `affine_span` of a finite affinely independent family lies
in an affine subspace whose direction has dimension one less than its
cardinality, it equals that subspace. -/
theorem affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one {k : Type u_1}
{V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P]
{ι : Type u_4} [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P}
[finite_dimensional k ↥(affine_subspace.direction sp)] (hle : affine_span k (set.range p) ≤ sp)
(hc : fintype.card ι = finite_dimensional.findim k ↥(affine_subspace.direction sp) + 1) :
affine_span k (set.range p) = sp :=
sorry
/-- The `vector_span` of a finite affinely independent family whose
cardinality is one more than that of the finite-dimensional space is
`⊤`. -/
theorem vector_span_eq_top_of_affine_independent_of_card_eq_findim_add_one {k : Type u_1}
{V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P]
{ι : Type u_4} [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p)
(hc : fintype.card ι = finite_dimensional.findim k V + 1) : vector_span k (set.range p) = ⊤ :=
finite_dimensional.eq_top_of_findim_eq (findim_vector_span_of_affine_independent hi hc)
/-- The `affine_span` of a finite affinely independent family whose
cardinality is one more than that of the finite-dimensional space is
`⊤`. -/
theorem affine_span_eq_top_of_affine_independent_of_card_eq_findim_add_one {k : Type u_1}
{V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P]
{ι : Type u_4} [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p)
(hc : fintype.card ι = finite_dimensional.findim k V + 1) : affine_span k (set.range p) = ⊤ :=
sorry
/-- The `vector_span` of `n + 1` points in an indexed family has
dimension at most `n`. -/
theorem findim_vector_span_image_finset_le (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4} (p : ι → P) (s : finset ι)
{n : ℕ} (hc : finset.card s = n + 1) :
finite_dimensional.findim k ↥(vector_span k (p '' ↑s)) ≤ n :=
sorry
/-- The `vector_span` of an indexed family of `n + 1` points has
dimension at most `n`. -/
theorem findim_vector_span_range_le (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4} [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 1) :
finite_dimensional.findim k ↥(vector_span k (set.range p)) ≤ n :=
sorry
/-- `n + 1` points are affinely independent if and only if their
`vector_span` has dimension `n`. -/
theorem affine_independent_iff_findim_vector_span_eq (k : Type u_1) {V : Type u_2} {P : Type u_3}
[field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4} [fintype ι]
(p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) :
affine_independent k p ↔ finite_dimensional.findim k ↥(vector_span k (set.range p)) = n :=
sorry
/-- `n + 1` points are affinely independent if and only if their
`vector_span` has dimension at least `n`. -/
theorem affine_independent_iff_le_findim_vector_span (k : Type u_1) {V : Type u_2} {P : Type u_3}
[field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4} [fintype ι]
(p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) :
affine_independent k p ↔ n ≤ finite_dimensional.findim k ↥(vector_span k (set.range p)) :=
sorry
/-- `n + 2` points are affinely independent if and only if their
`vector_span` does not have dimension at most `n`. -/
theorem affine_independent_iff_not_findim_vector_span_le (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
[fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + bit0 1) :
affine_independent k p ↔ ¬finite_dimensional.findim k ↥(vector_span k (set.range p)) ≤ n :=
sorry
/-- `n + 2` points have a `vector_span` with dimension at most `n` if
and only if they are not affinely independent. -/
theorem findim_vector_span_le_iff_not_affine_independent (k : Type u_1) {V : Type u_2}
{P : Type u_3} [field k] [add_comm_group V] [module k V] [add_torsor V P] {ι : Type u_4}
[fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + bit0 1) :
finite_dimensional.findim k ↥(vector_span k (set.range p)) ≤ n ↔ ¬affine_independent k p :=
iff.symm
(iff.mp not_iff_comm (iff.symm (affine_independent_iff_not_findim_vector_span_le k p hc)))
/-- A set of points is collinear if their `vector_span` has dimension
at most `1`. -/
def collinear (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k] [add_comm_group V] [module k V]
[add_torsor V P] (s : set P) :=
vector_space.dim k ↥(vector_span k s) ≤ 1
/-- The definition of `collinear`. -/
theorem collinear_iff_dim_le_one (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (s : set P) :
collinear k s ↔ vector_space.dim k ↥(vector_span k s) ≤ 1 :=
iff.rfl
/-- A set of points, whose `vector_span` is finite-dimensional, is
collinear if and only if their `vector_span` has dimension at most
`1`. -/
theorem collinear_iff_findim_le_one (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (s : set P)
[finite_dimensional k ↥(vector_span k s)] :
collinear k s ↔ finite_dimensional.findim k ↥(vector_span k s) ≤ 1 :=
sorry
/-- The empty set is collinear. -/
theorem collinear_empty (k : Type u_1) {V : Type u_2} (P : Type u_3) [field k] [add_comm_group V]
[module k V] [add_torsor V P] : collinear k ∅ :=
sorry
/-- A single point is collinear. -/
theorem collinear_singleton (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (p : P) : collinear k (singleton p) :=
sorry
/-- Given a point `p₀` in a set of points, that set is collinear if and
only if the points can all be expressed as multiples of the same
vector, added to `p₀`. -/
theorem collinear_iff_of_mem (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] {s : set P} {p₀ : P} (h : p₀ ∈ s) :
collinear k s ↔ ∃ (v : V), ∀ (p : P), p ∈ s → ∃ (r : k), p = r • v +ᵥ p₀ :=
sorry
/-- A set of points is collinear if and only if they can all be
expressed as multiples of the same vector, added to the same base
point. -/
theorem collinear_iff_exists_forall_eq_smul_vadd (k : Type u_1) {V : Type u_2} {P : Type u_3}
[field k] [add_comm_group V] [module k V] [add_torsor V P] (s : set P) :
collinear k s ↔ ∃ (p₀ : P), ∃ (v : V), ∀ (p : P), p ∈ s → ∃ (r : k), p = r • v +ᵥ p₀ :=
sorry
/-- Two points are collinear. -/
theorem collinear_insert_singleton (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (p₁ : P) (p₂ : P) :
collinear k (insert p₁ (singleton p₂)) :=
sorry
/-- Three points are affinely independent if and only if they are not
collinear. -/
theorem affine_independent_iff_not_collinear (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (p : fin (bit1 1) → P) :
affine_independent k p ↔ ¬collinear k (set.range p) :=
sorry
/-- Three points are collinear if and only if they are not affinely
independent. -/
theorem collinear_iff_not_affine_independent (k : Type u_1) {V : Type u_2} {P : Type u_3} [field k]
[add_comm_group V] [module k V] [add_torsor V P] (p : fin (bit1 1) → P) :
collinear k (set.range p) ↔ ¬affine_independent k p :=
sorry
end Mathlib |
304158195d9a770476c4f4c7457573a51f627c37 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Elab/Tactic/Match.lean | e93cecbae9556e5978ae5afd852327c66c602dd4 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,169 | 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.Match
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Induction
namespace Lean.Elab.Tactic
structure AuxMatchTermState :=
(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[1].getArgs
let newAlts ← alts.mapSepElemsM fun alt => do
let alt := alt.setKind `Lean.Parser.Term.matchAlt
let holeOrTacticSeq := alt[2]
if holeOrTacticSeq.isOfKind `Lean.Parser.Term.syntheticHole then
pure alt
else if holeOrTacticSeq.isOfKind `Lean.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 2 newHole
else withFreshMacroScope do
let newHole ← `(?rhs)
let newHoleId := newHole[1]
let newCase ← `(tactic| case $newHoleId => $holeOrTacticSeq:tacticSeq )
modify fun s => { s with cases := s.cases.push newCase }
pure $ alt.setArg 2 newHole
let result := matchTac.setKind `Lean.Parser.Term.«match»
let result := result.setArg 4 (matchAlts.setArg 1 (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
|
3c7bf4ee8751236b9190a7e2e283c0e0eff398c7 | e953c38599905267210b87fb5d82dcc3e52a4214 | /library/data/rat/basic.lean | b584aaa01f72b2acd0f0ab7d332fc98d0c47382d | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 22,694 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
The rational numbers as a field generated by the integers, defined as the usual quotient.
-/
import data.int algebra.field
open int quot eq.ops
record prerat : Type :=
(num : ℤ) (denom : ℤ) (denom_pos : denom > 0)
/-
prerat: the representations of the rationals as integers num, denom, with denom > 0.
note: names are not protected, because it is not expected that users will open prerat.
-/
namespace prerat
/- the equivalence relation -/
definition equiv (a b : prerat) : Prop := num a * denom b = num b * denom a
infix `≡` := equiv
theorem equiv.refl [refl] (a : prerat) : a ≡ a := rfl
theorem equiv.symm [symm] {a b : prerat} (H : a ≡ b) : b ≡ a := !eq.symm H
theorem num_eq_zero_of_equiv {a b : prerat} (H : a ≡ b) (na_zero : num a = 0) : num b = 0 :=
have num a * denom b = 0, from !zero_mul ▸ na_zero ▸ rfl,
have num b * denom a = 0, from H ▸ this,
show num b = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) (ne_of_gt (denom_pos a))
theorem num_pos_of_equiv {a b : prerat} (H : a ≡ b) (na_pos : num a > 0) : num b > 0 :=
have num a * denom b > 0, from mul_pos na_pos (denom_pos b),
have num b * denom a > 0, from H ▸ this,
show num b > 0, from pos_of_mul_pos_right this (le_of_lt (denom_pos a))
theorem num_neg_of_equiv {a b : prerat} (H : a ≡ b) (na_neg : num a < 0) : num b < 0 :=
have num a * denom b < 0, from mul_neg_of_neg_of_pos na_neg (denom_pos b),
have -(-num b * denom a) < 0, from !neg_mul_eq_neg_mul⁻¹ ▸ !neg_neg⁻¹ ▸ H ▸ this,
have -num b > 0, from pos_of_mul_pos_right (pos_of_neg_neg this) (le_of_lt (denom_pos a)),
neg_of_neg_pos this
theorem equiv_of_num_eq_zero {a b : prerat} (H1 : num a = 0) (H2 : num b = 0) : a ≡ b :=
by rewrite [↑equiv, H1, H2, *zero_mul]
theorem equiv.trans [trans] {a b c : prerat} (H1 : a ≡ b) (H2 : b ≡ c) : a ≡ c :=
decidable.by_cases
(suppose num b = 0,
have num a = 0, from num_eq_zero_of_equiv (equiv.symm H1) `num b = 0`,
have num c = 0, from num_eq_zero_of_equiv H2 `num b = 0`,
equiv_of_num_eq_zero `num a = 0` `num c = 0`)
(suppose num b ≠ 0,
have H3 : num b * denom b ≠ 0, from mul_ne_zero this (ne_of_gt (denom_pos b)),
have H4 : (num b * denom b) * (num a * denom c) = (num b * denom b) * (num c * denom a),
from calc
(num b * denom b) * (num a * denom c) = (num a * denom b) * (num b * denom c) :
by rewrite [*mul.assoc, *mul.left_comm (num a), *mul.left_comm (num b)]
... = (num b * denom a) * (num b * denom c) : {H1}
... = (num b * denom a) * (num c * denom b) : {H2}
... = (num b * denom b) * (num c * denom a) :
by rewrite [*mul.assoc, *mul.left_comm (denom a),
*mul.left_comm (denom b), mul.comm (denom a)],
eq_of_mul_eq_mul_left H3 H4)
theorem equiv.is_equivalence : equivalence equiv :=
mk_equivalence equiv equiv.refl @equiv.symm @equiv.trans
definition setoid : setoid prerat :=
setoid.mk equiv equiv.is_equivalence
/- field operations -/
definition of_int (i : int) : prerat := prerat.mk i 1 !of_nat_succ_pos
definition zero : prerat := of_int 0
definition one : prerat := of_int 1
private theorem mul_denom_pos (a b : prerat) : denom a * denom b > 0 :=
mul_pos (denom_pos a) (denom_pos b)
definition add (a b : prerat) : prerat :=
prerat.mk (num a * denom b + num b * denom a) (denom a * denom b) (mul_denom_pos a b)
definition mul (a b : prerat) : prerat :=
prerat.mk (num a * num b) (denom a * denom b) (mul_denom_pos a b)
definition neg (a : prerat) : prerat :=
prerat.mk (- num a) (denom a) (denom_pos a)
definition smul (a : ℤ) (b : prerat) (H : a > 0) : prerat :=
prerat.mk (a * num b) (a * denom b) (mul_pos H (denom_pos b))
theorem of_int_add (a b : ℤ) : of_int (#int a + b) ≡ add (of_int a) (of_int b) :=
by esimp [equiv, num, denom, one, add, of_int]; rewrite [*int.mul_one]
theorem of_int_mul (a b : ℤ) : of_int (#int a * b) ≡ mul (of_int a) (of_int b) :=
!equiv.refl
theorem of_int_neg (a : ℤ) : of_int (#int -a) ≡ neg (of_int a) :=
!equiv.refl
theorem of_int.inj {a b : ℤ} : of_int a ≡ of_int b → a = b :=
by rewrite [↑of_int, ↑equiv, *mul_one]; intros; assumption
definition inv : prerat → prerat
| inv (prerat.mk nat.zero d dp) := zero
| inv (prerat.mk (nat.succ n) d dp) := prerat.mk d (nat.succ n) !of_nat_succ_pos
| inv (prerat.mk -[1+n] d dp) := prerat.mk (-d) (nat.succ n) !of_nat_succ_pos
theorem equiv_zero_of_num_eq_zero {a : prerat} (H : num a = 0) : a ≡ zero :=
by rewrite [↑equiv, H, ↑zero, ↑num, ↑of_int, *zero_mul]
theorem num_eq_zero_of_equiv_zero {a : prerat} : a ≡ zero → num a = 0 :=
by rewrite [↑equiv, ↑zero, ↑of_int, mul_one, zero_mul]; intro H; exact H
theorem inv_zero {d : int} (dp : d > 0) : inv (mk nat.zero d dp) = zero :=
begin rewrite [↑inv, ▸*] end
theorem inv_zero' : inv zero = zero := inv_zero (of_nat_succ_pos nat.zero)
theorem inv_of_pos {n d : int} (np : n > 0) (dp : d > 0) : inv (mk n d dp) ≡ mk d n np :=
obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np),
have (#nat n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np),
obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this,
have d * n = d * nat.succ k, by rewrite [Hn', Hk],
Hn'⁻¹ ▸ (Hk⁻¹ ▸ this)
theorem inv_neg {n d : int} (np : n > 0) (dp : d > 0) : inv (mk (-n) d dp) ≡ mk (-d) n np :=
obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np),
have (#nat n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np),
obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this,
have -d * n = -d * nat.succ k, by rewrite [Hn', Hk],
have H3 : inv (mk -[1+k] d dp) ≡ mk (-d) n np, from this,
have H4 : -[1+k] = -n, from calc
-[1+k] = -(nat.succ k) : rfl
... = -n : by rewrite [Hk⁻¹, Hn'],
H4 ▸ H3
theorem inv_of_neg {n d : int} (nn : n < 0) (dp : d > 0) :
inv (mk n d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn) :=
have inv (mk (-(-n)) d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn),
from inv_neg (neg_pos_of_neg nn) dp,
!neg_neg ▸ this
/- operations respect equiv -/
theorem add_equiv_add {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) :
add a1 b1 ≡ add a2 b2 :=
calc
(num a1 * denom b1 + num b1 * denom a1) * (denom a2 * denom b2)
= num a1 * denom a2 * denom b1 * denom b2 + num b1 * denom b2 * denom a1 * denom a2 :
by rewrite [mul.right_distrib, *mul.assoc, mul.left_comm (denom b1),
mul.comm (denom b2), *mul.assoc]
... = num a2 * denom a1 * denom b1 * denom b2 + num b2 * denom b1 * denom a1 * denom a2 :
by rewrite [↑equiv at *, eqv1, eqv2]
... = (num a2 * denom b2 + num b2 * denom a2) * (denom a1 * denom b1) :
by rewrite [mul.right_distrib, *mul.assoc, *mul.left_comm (denom b2),
*mul.comm (denom b1), *mul.assoc, mul.left_comm (denom a2)]
theorem mul_equiv_mul {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) :
mul a1 b1 ≡ mul a2 b2 :=
calc
(num a1 * num b1) * (denom a2 * denom b2)
= (num a1 * denom a2) * (num b1 * denom b2) : by rewrite [*mul.assoc, mul.left_comm (num b1)]
... = (num a2 * denom a1) * (num b2 * denom b1) : by rewrite [↑equiv at *, eqv1, eqv2]
... = (num a2 * num b2) * (denom a1 * denom b1) : by rewrite [*mul.assoc, mul.left_comm (num b2)]
theorem neg_equiv_neg {a b : prerat} (eqv : a ≡ b) : neg a ≡ neg b :=
calc
-num a * denom b = -(num a * denom b) : neg_mul_eq_neg_mul
... = -(num b * denom a) : {eqv}
... = -num b * denom a : neg_mul_eq_neg_mul
theorem inv_equiv_inv : ∀{a b : prerat}, a ≡ b → inv a ≡ inv b
| (mk an ad adp) (mk bn bd bdp) :=
assume H,
lt.by_cases
(assume an_neg : an < 0,
have bn_neg : bn < 0, from num_neg_of_equiv H an_neg,
calc
inv (mk an ad adp) ≡ mk (-ad) (-an) (neg_pos_of_neg an_neg) : inv_of_neg an_neg adp
... ≡ mk (-bd) (-bn) (neg_pos_of_neg bn_neg) :
by rewrite [↑equiv at *, ▸*, *neg_mul_neg, mul.comm ad, mul.comm bd, H]
... ≡ inv (mk bn bd bdp) : (inv_of_neg bn_neg bdp)⁻¹)
(assume an_zero : an = 0,
have bn_zero : bn = 0, from num_eq_zero_of_equiv H an_zero,
eq.subst (calc
inv (mk an ad adp) = inv (mk 0 ad adp) : {an_zero}
... = zero : inv_zero
... = inv (mk 0 bd bdp) : inv_zero
... = inv (mk bn bd bdp) : bn_zero) !equiv.refl)
(assume an_pos : an > 0,
have bn_pos : bn > 0, from num_pos_of_equiv H an_pos,
calc
inv (mk an ad adp) ≡ mk ad an an_pos : inv_of_pos an_pos adp
... ≡ mk bd bn bn_pos :
by rewrite [↑equiv at *, ▸*, mul.comm ad, mul.comm bd, H]
... ≡ inv (mk bn bd bdp) : (inv_of_pos bn_pos bdp)⁻¹)
theorem smul_equiv {a : ℤ} {b : prerat} (H : a > 0) : smul a b H ≡ b :=
by esimp[equiv, smul]; rewrite[mul.assoc, mul.left_comm]
/- properties -/
theorem add.comm (a b : prerat) : add a b ≡ add b a :=
by rewrite [↑add, ↑equiv, ▸*, add.comm, mul.comm (denom a)]
theorem add.assoc (a b c : prerat) : add (add a b) c ≡ add a (add b c) :=
by rewrite [↑add, ↑equiv, ▸*, *(mul.comm (num c)), *(λy, mul.comm y (denom a)), *mul.left_distrib,
*mul.right_distrib, *mul.assoc, *add.assoc]
theorem add_zero (a : prerat) : add a zero ≡ a :=
by rewrite [↑add, ↑equiv, ↑zero, ↑of_int, ▸*, *mul_one, zero_mul, add_zero]
theorem add.left_inv (a : prerat) : add (neg a) a ≡ zero :=
by rewrite [↑add, ↑equiv, ↑neg, ↑zero, ↑of_int, ▸*, -neg_mul_eq_neg_mul, add.left_inv, *zero_mul]
theorem mul.comm (a b : prerat) : mul a b ≡ mul b a :=
by rewrite [↑mul, ↑equiv, mul.comm (num a), mul.comm (denom a)]
theorem mul.assoc (a b c : prerat) : mul (mul a b) c ≡ mul a (mul b c) :=
by rewrite [↑mul, ↑equiv, *mul.assoc]
theorem mul_one (a : prerat) : mul a one ≡ a :=
by rewrite [↑mul, ↑one, ↑of_int, ↑equiv, ▸*, *mul_one]
theorem mul.left_distrib (a b c : prerat) : mul a (add b c) ≡ add (mul a b) (mul a c) :=
have H : smul (denom a) (mul a (add b c)) (denom_pos a) =
add (mul a b) (mul a c), from begin
rewrite[↑smul, ↑mul, ↑add],
congruence,
rewrite[*mul.left_distrib, *mul.right_distrib, -*int.mul.assoc],
have T : ∀ {x y z w : ℤ}, x*y*z*w=y*z*x*w, from
λx y z w, (!int.mul.assoc ⬝ !int.mul.comm) ▸ rfl,
exact !congr_arg2 T T,
exact !mul.left_comm ▸ !int.mul.assoc⁻¹
end,
equiv.symm (H ▸ smul_equiv (denom_pos a))
theorem mul_inv_cancel : ∀{a : prerat}, ¬ a ≡ zero → mul a (inv a) ≡ one
| (mk an ad adp) :=
assume H,
let a := mk an ad adp in
lt.by_cases
(assume an_neg : an < 0,
let ia := mk (-ad) (-an) (neg_pos_of_neg an_neg) in
calc
mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_neg an_neg adp)
... ≡ one : begin
esimp [equiv, num, denom, one, mul, of_int],
rewrite [*int.mul_one, *int.one_mul, int.mul.comm,
neg_mul_comm]
end)
(assume an_zero : an = 0, absurd (equiv_zero_of_num_eq_zero an_zero) H)
(assume an_pos : an > 0,
let ia := mk ad an an_pos in
calc
mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_pos an_pos adp)
... ≡ one : begin
esimp [equiv, num, denom, one, mul, of_int],
rewrite [*int.mul_one, *int.one_mul, int.mul.comm]
end)
theorem zero_not_equiv_one : ¬ zero ≡ one :=
begin
esimp [equiv, zero, one, of_int],
rewrite [zero_mul, int.mul_one],
exact zero_ne_one
end
theorem mul_denom_equiv (a : prerat) : mul a (of_int (denom a)) ≡ of_int (num a) :=
by esimp [mul, of_int, equiv]; rewrite [*int.mul_one]
/- Reducing a fraction to lowest terms. Needed to choose a canonical representative of rat, and
define numerator and denominator. -/
definition reduce : prerat → prerat
| (mk an ad adpos) :=
have pos : ad div gcd an ad > 0, from div_pos_of_pos_of_dvd adpos !gcd_nonneg !gcd_dvd_right,
if an = 0 then prerat.zero
else mk (an div gcd an ad) (ad div gcd an ad) pos
protected theorem eq {a b : prerat} (Hn : num a = num b) (Hd : denom a = denom b) : a = b :=
begin
cases a with [an, ad, adpos],
cases b with [bn, bd, bdpos],
generalize adpos, generalize bdpos,
esimp at *,
rewrite [Hn, Hd],
intros, apply rfl
end
theorem reduce_equiv : ∀ a : prerat, reduce a ≡ a
| (mk an ad adpos) :=
decidable.by_cases
(assume anz : an = 0,
by krewrite [↑reduce, if_pos anz, ↑equiv, anz, *zero_mul])
(assume annz : an ≠ 0,
by rewrite [↑reduce, if_neg annz, ↑equiv, int.mul.comm, -!mul_div_assoc !gcd_dvd_left,
-!mul_div_assoc !gcd_dvd_right, int.mul.comm])
theorem reduce_eq_reduce : ∀{a b : prerat}, a ≡ b → reduce a = reduce b
| (mk an ad adpos) (mk bn bd bdpos) :=
assume H : an * bd = bn * ad,
decidable.by_cases
(assume anz : an = 0,
have H' : bn * ad = 0, by rewrite [-H, anz, zero_mul],
assert bnz : bn = 0,
from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt adpos),
by rewrite [↑reduce, if_pos anz, if_pos bnz])
(assume annz : an ≠ 0,
assert bnnz : bn ≠ 0, from
assume bnz,
have H' : an * bd = 0, by rewrite [H, bnz, zero_mul],
have anz : an = 0,
from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt bdpos),
show false, from annz anz,
begin
rewrite [↑reduce, if_neg annz, if_neg bnnz],
apply prerat.eq,
{apply div_gcd_eq_div_gcd H adpos bdpos},
{esimp, rewrite [gcd.comm, gcd.comm bn],
apply div_gcd_eq_div_gcd_of_nonneg,
rewrite [int.mul.comm, -H, int.mul.comm],
apply annz,
apply bnnz,
apply le_of_lt adpos,
apply le_of_lt bdpos},
end)
end prerat
/-
the rationals
-/
definition rat : Type.{1} := quot prerat.setoid
notation `ℚ` := rat
local attribute prerat.setoid [instance]
namespace rat
/- operations -/
definition of_int [coercion] (i : ℤ) : ℚ := ⟦prerat.of_int i⟧
definition of_nat [coercion] (n : ℕ) : ℚ := ⟦prerat.of_int n⟧
definition of_num [coercion] [reducible] (n : num) : ℚ := of_int (int.of_num n)
definition add : ℚ → ℚ → ℚ :=
quot.lift₂
(λ a b : prerat, ⟦prerat.add a b⟧)
(take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.add_equiv_add H1 H2))
definition mul : ℚ → ℚ → ℚ :=
quot.lift₂
(λ a b : prerat, ⟦prerat.mul a b⟧)
(take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.mul_equiv_mul H1 H2))
definition neg : ℚ → ℚ :=
quot.lift
(λ a : prerat, ⟦prerat.neg a⟧)
(take a1 a2, assume H, quot.sound (prerat.neg_equiv_neg H))
definition inv : ℚ → ℚ :=
quot.lift
(λ a : prerat, ⟦prerat.inv a⟧)
(take a1 a2, assume H, quot.sound (prerat.inv_equiv_inv H))
definition reduce : ℚ → prerat :=
quot.lift
(λ a : prerat, prerat.reduce a)
@prerat.reduce_eq_reduce
definition num (a : ℚ) : ℤ := prerat.num (reduce a)
definition denom (a : ℚ) : ℤ := prerat.denom (reduce a)
theorem denom_pos (a : ℚ): denom a > 0 :=
prerat.denom_pos (reduce a)
protected definition prio := num.pred int.prio
infix [priority rat.prio] + := rat.add
infix [priority rat.prio] * := rat.mul
prefix [priority rat.prio] - := rat.neg
definition sub [reducible] (a b : rat) : rat := a + (-b)
postfix [priority rat.prio] ⁻¹ := rat.inv
infix [priority rat.prio] - := rat.sub
/- properties -/
theorem of_int_add (a b : ℤ) : of_int (#int a + b) = of_int a + of_int b :=
quot.sound (prerat.of_int_add a b)
theorem of_int_mul (a b : ℤ) : of_int (#int a * b) = of_int a * of_int b :=
quot.sound (prerat.of_int_mul a b)
theorem of_int_neg (a : ℤ) : of_int (#int -a) = -(of_int a) :=
quot.sound (prerat.of_int_neg a)
theorem of_int_sub (a b : ℤ) : of_int (#int a - b) = of_int a - of_int b :=
calc
of_int (#int a - b) = of_int a + of_int (#int -b) : of_int_add
... = of_int a - of_int b : {of_int_neg b}
theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b :=
prerat.of_int.inj (quot.exact H)
theorem of_nat_eq (a : ℕ) : of_nat a = of_int (int.of_nat a) := rfl
theorem of_nat_add (a b : ℕ) : of_nat (#nat a + b) = of_nat a + of_nat b :=
by rewrite [*of_nat_eq, int.of_nat_add, rat.of_int_add]
theorem of_nat_mul (a b : ℕ) : of_nat (#nat a * b) = of_nat a * of_nat b :=
by rewrite [*of_nat_eq, int.of_nat_mul, rat.of_int_mul]
theorem of_nat_sub {a b : ℕ} (H : #nat a ≥ b) : of_nat (#nat a - b) = of_nat a - of_nat b :=
by rewrite [*of_nat_eq, int.of_nat_sub H, rat.of_int_sub]
theorem add.comm (a b : ℚ) : a + b = b + a :=
quot.induction_on₂ a b (take u v, quot.sound !prerat.add.comm)
theorem add.assoc (a b c : ℚ) : a + b + c = a + (b + c) :=
quot.induction_on₃ a b c (take u v w, quot.sound !prerat.add.assoc)
theorem add_zero (a : ℚ) : a + 0 = a :=
quot.induction_on a (take u, quot.sound !prerat.add_zero)
theorem zero_add (a : ℚ) : 0 + a = a := !add.comm ▸ !add_zero
theorem add.left_inv (a : ℚ) : -a + a = 0 :=
quot.induction_on a (take u, quot.sound !prerat.add.left_inv)
theorem mul.comm (a b : ℚ) : a * b = b * a :=
quot.induction_on₂ a b (take u v, quot.sound !prerat.mul.comm)
theorem mul.assoc (a b c : ℚ) : a * b * c = a * (b * c) :=
quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.assoc)
theorem mul_one (a : ℚ) : a * 1 = a :=
quot.induction_on a (take u, quot.sound !prerat.mul_one)
theorem one_mul (a : ℚ) : 1 * a = a := !mul.comm ▸ !mul_one
theorem mul.left_distrib (a b c : ℚ) : a * (b + c) = a * b + a * c :=
quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.left_distrib)
theorem mul.right_distrib (a b c : ℚ) : (a + b) * c = a * c + b * c :=
by rewrite [mul.comm, mul.left_distrib, *mul.comm c]
theorem mul_inv_cancel {a : ℚ} : a ≠ 0 → a * a⁻¹ = 1 :=
quot.induction_on a
(take u,
assume H,
quot.sound (!prerat.mul_inv_cancel (assume H1, H (quot.sound H1))))
theorem inv_mul_cancel {a : ℚ} (H : a ≠ 0) : a⁻¹ * a = 1 :=
!mul.comm ▸ mul_inv_cancel H
theorem zero_ne_one : (0 : ℚ) ≠ 1 :=
assume H, prerat.zero_not_equiv_one (quot.exact H)
definition has_decidable_eq [instance] : decidable_eq ℚ :=
take a b, quot.rec_on_subsingleton₂ a b
(take u v,
if H : prerat.num u * prerat.denom v = prerat.num v * prerat.denom u
then decidable.inl (quot.sound H)
else decidable.inr (assume H1, H (quot.exact H1)))
theorem inv_zero : inv 0 = 0 :=
quot.sound (prerat.inv_zero' ▸ !prerat.equiv.refl)
theorem quot_reduce (a : ℚ) : ⟦reduce a⟧ = a :=
quot.induction_on a (take u, quot.sound !prerat.reduce_equiv)
theorem mul_denom (a : ℚ) : a * denom a = num a :=
have H : ⟦reduce a⟧ * of_int (denom a) = of_int (num a), from quot.sound (!prerat.mul_denom_equiv),
quot_reduce a ▸ H
theorem coprime_num_denom (a : ℚ) : coprime (num a) (denom a) :=
decidable.by_cases
(suppose a = 0, by substvars)
(quot.induction_on a
(take u H,
assert H' : prerat.num u ≠ 0, from take H'', H (quot.sound (prerat.equiv_zero_of_num_eq_zero H'')),
begin
cases u with un ud udpos,
rewrite [▸*, ↑num, ↑denom, ↑reduce, ↑prerat.reduce, if_neg H', ▸*],
have gcd un ud ≠ 0, from ne_of_gt (!gcd_pos_of_ne_zero_left H'),
apply coprime_div_gcd_div_gcd this
end))
section migrate_algebra
open [classes] algebra
protected definition discrete_field [reducible] : algebra.discrete_field rat :=
⦃algebra.discrete_field,
add := add,
add_assoc := add.assoc,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
neg := neg,
add_left_inv := add.left_inv,
add_comm := add.comm,
mul := mul,
mul_assoc := mul.assoc,
one := (of_num 1),
one_mul := one_mul,
mul_one := mul_one,
left_distrib := mul.left_distrib,
right_distrib := mul.right_distrib,
mul_comm := mul.comm,
mul_inv_cancel := @mul_inv_cancel,
inv_mul_cancel := @inv_mul_cancel,
zero_ne_one := zero_ne_one,
inv_zero := inv_zero,
has_decidable_eq := has_decidable_eq⦄
local attribute rat.discrete_field [instance]
definition divide (a b : rat) := algebra.divide a b
infix [priority rat.prio] `/` := divide
definition dvd (a b : rat) := algebra.dvd a b
definition pow (a : ℚ) (n : ℕ) : ℚ := algebra.pow a n
infix [priority rat.prio] ^ := pow
definition nmul (n : ℕ) (a : ℚ) : ℚ := algebra.nmul n a
infix [priority rat.prio] `⬝` := nmul
definition imul (i : ℤ) (a : ℚ) : ℚ := algebra.imul i a
migrate from algebra with rat
replacing sub → rat.sub, divide → divide, dvd → dvd, pow → pow, nmul → nmul, imul → imul
end migrate_algebra
theorem eq_num_div_denom (a : ℚ) : a = num a / denom a :=
have H : of_int (denom a) ≠ 0, from assume H', ne_of_gt (denom_pos a) (of_int.inj H'),
iff.mpr (eq_div_iff_mul_eq H) (mul_denom a)
theorem of_int_div {a b : ℤ} (H : b ∣ a) : of_int (a div b) = of_int a / of_int b :=
decidable.by_cases
(assume bz : b = 0,
by rewrite [bz, div_zero, int.div_zero])
(assume bnz : b ≠ 0,
have bnz' : of_int b ≠ 0, from assume oibz, bnz (of_int.inj oibz),
have H' : of_int (a div b) * of_int b = of_int a, from
int.dvd.elim H
(take c, assume Hc : a = b * c,
by rewrite [Hc, !int.mul_div_cancel_left bnz, mul.comm]),
iff.mpr (eq_div_iff_mul_eq bnz') H')
theorem of_int_pow (a : ℤ) (n : ℕ) : of_int (a^n) = (of_int a)^n :=
begin
induction n with n ih,
apply eq.refl,
rewrite [pow_succ, int.pow_succ, of_int_mul, ih]
end
end rat
|
5a83ac9ea222926de987e5bbe2c4128051dd526a | 8f209eb34c0c4b9b6be5e518ebfc767a38bed79c | /code/src/internal/Ant/map.lean | eb1778020ffd676af46d4d0c7161772ac63db52b | [] | 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 | 955 | lean | import tactic
import ...definitions
import ..internal_definitions
import ..utils
variable [GuardModule]
open GuardModule
lemma Ant.map_associative { α β γ: Type } (f: β → γ) (g: α → β) (ant: Ant α):
(ant.map g).map f = ant.map (f ∘ g) :=
by induction ant; simp [*, Ant.map]
@[simp]
lemma Ant.map_const { α β γ: Type } (c: γ) (g: α → β) (ant: Ant α):
(ant.map g).map (λ x, c) = ant.map (λ x, c) :=
by rw Ant.map_associative
@[simp]
lemma Ant.map_id { α: Type } (ant: Ant α): ant.map id = ant :=
by induction ant; simp [Ant.map, *]
@[simp]
lemma Ant.map_rhss { α β: Type } (ant: Ant α) (f: α → β): (ant.map f).rhss = ant.rhss :=
by induction ant; finish [Ant.rhss, Ant.rhss_list, Ant.map]
@[simp]
lemma Ant.map_disjoint_rhss_iff { α β: Type } { f: α → β } { ant: Ant α }: (ant.map f).disjoint_rhss ↔ ant.disjoint_rhss :=
by induction ant; { simp only [Ant.map, Ant.disjoint_rhss, *, Ant.map_rhss], }
|
b20e766223ac797ed3e901cf9eb9429f449f12ee | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/Group/biproducts.lean | 10730e722a3dcaee4297e75788836a151f960460 | [
"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,651 | 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.Group.limits
import algebra.category.Group.preadditive
import category_theory.limits.shapes.biproducts
import category_theory.limits.shapes.types
import algebra.group.pi
/-!
# The category of abelian groups has finite biproducts
-/
open category_theory
open category_theory.limits
open_locale big_operators
universe u
namespace AddCommGroup
/--
Construct limit data for a binary product in `AddCommGroup`, using `AddCommGroup.of (G × H)`.
-/
def binary_product_limit_cone (G H : AddCommGroup.{u}) : limits.limit_cone (pair G H) :=
{ cone :=
{ X := AddCommGroup.of (G × H),
π := { app := λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H) }},
is_limit :=
{ lift := λ s, add_monoid_hom.prod (s.π.app walking_pair.left) (s.π.app walking_pair.right),
fac' := begin rintros s (⟨⟩|⟨⟩); { ext x, simp, }, end,
uniq' := λ s m w,
begin
ext; [rw ← w walking_pair.left, rw ← w walking_pair.right]; refl,
end, } }
instance has_binary_product (G H : AddCommGroup.{u}) : has_binary_product G H :=
has_limit.mk (binary_product_limit_cone G H)
instance (G H : AddCommGroup.{u}) : has_binary_biproduct G H :=
has_binary_biproduct.of_has_binary_product _ _
/--
We verify that the biproduct in AddCommGroup is isomorphic to
the cartesian product of the underlying types:
-/
noncomputable
def biprod_iso_prod (G H : AddCommGroup.{u}) : (G ⊞ H : AddCommGroup) ≅ AddCommGroup.of (G × H) :=
is_limit.cone_point_unique_up_to_iso
(binary_biproduct.is_limit G H)
(binary_product_limit_cone G H).is_limit
-- Furthermore, our biproduct will automatically function as a coproduct.
example (G H : AddCommGroup.{u}) : has_colimit (pair G H) := by apply_instance
variables {J : Type u} (F : (discrete J) ⥤ AddCommGroup.{u})
namespace has_limit
/--
The map from an arbitrary cone over a indexed family of abelian groups
to the cartesian product of those groups.
-/
def lift (s : cone F) :
s.X ⟶ AddCommGroup.of (Π j, F.obj j) :=
{ to_fun := λ x j, s.π.app j x,
map_zero' := by { ext, simp },
map_add' := λ x y, by { ext, simp }, }
@[simp] lemma lift_apply (s : cone F) (x : s.X) (j : J) : (lift F s) x j = s.π.app j x := rfl
/--
Construct limit data for a product in `AddCommGroup`, using `AddCommGroup.of (Π j, F.obj j)`.
-/
def product_limit_cone : limits.limit_cone F :=
{ cone :=
{ X := AddCommGroup.of (Π j, F.obj j),
π := discrete.nat_trans (λ j, pi.eval_add_monoid_hom (λ j, F.obj j) j), },
is_limit :=
{ lift := lift F,
fac' := λ s j, by { ext, simp, },
uniq' := λ s m w,
begin
ext x j,
dsimp only [has_limit.lift],
simp only [add_monoid_hom.coe_mk],
exact congr_arg (λ f : s.X ⟶ F.obj j, (f : s.X → F.obj j) x) (w j),
end, }, }
end has_limit
section
open has_limit
variables [decidable_eq J] [fintype J]
instance (f : J → AddCommGroup.{u}) : has_biproduct f :=
has_biproduct.of_has_product _
/--
We verify that the biproduct we've just defined is isomorphic to the AddCommGroup structure
on the dependent function type
-/
noncomputable
def biproduct_iso_pi (f : J → AddCommGroup.{u}) :
(⨁ f : AddCommGroup) ≅ AddCommGroup.of (Π j, f j) :=
is_limit.cone_point_unique_up_to_iso
(biproduct.is_limit f)
(product_limit_cone (discrete.functor f)).is_limit
end
instance : has_finite_biproducts AddCommGroup :=
⟨λ J _ _, by exactI { has_biproduct := λ f, by apply_instance }⟩
end AddCommGroup
|
945b43cbfb6449748366ff91705030fb15cbee4a | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /src/01_Equality/01_equality.lean | 32b487722953d70808a67feb6df095a2a0f8cdab | [] | no_license | kevinsullivan/cs-dm-lean | b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124 | a06a94e98be77170ca1df486c8189338b16cf6c6 | refs/heads/master | 1,585,948,743,595 | 1,544,339,346,000 | 1,544,339,346,000 | 155,570,767 | 1 | 3 | null | 1,541,540,372,000 | 1,540,995,993,000 | Lean | UTF-8 | Lean | false | false | 1,894 | lean | /- ** An inference rule for equality in general ** -/
/-
Intuitively you would suppose that the proposition,
0 = 0, should be true in any reasonable logical system.
There are two ways a logic could make this happen.
The first is that the logic could provide 0 = 0 as
an axiom, as we just discussed.
That'd be ok, but then we'd need similar axioms for
every other number. We'd also need similar axioms
for every object of every other type: person, car,
plant, atom, book, idea, etc. We end up with a pretty
unwieldy (and infinite) set of axioms.
Moreover, if we were ever to define a new type of
objects (e.g., digital pets), we'd have to extend
the axioms of the logic with similar rules for
every value of the new type. (e.g., Fido = Fido,
Spot = Spot, Kitty = Kitty, etc).
What would be much better would be to have just one
inference rule that basically allow us to conclude
that *any* object, or value, of any type whatsoever
is always equal to itself (and that nothing else
is ever equal to that object).
It'd go something like this: if T is any "type"
(such as natural number, car, person), and t is any
object or value of that type, T (e.g., t could be
the value, 0, which is a value of type "natural
number", or "nat" for short), then you can derive
that t = t is true.
We could write this inference rule something like
this:
T: Type, t : T
-------------- (eq.refl)
pf: t = t
In English you could pronounce this rule as
saying, "if you can give any type, T, and any
value, t, of that type, T, then the eq.refl
rule will derive a proof of the proposition
that t = t. In mathematical logic, this notion
of equality is called Leibniz equality.
EXERCISE: Give an expression in which eq.refl
is applied to two arguments to derive a proof
of 0 = 0.
EXERCISE: Why exactly can this rule never be used
to derive a proof of the proposition that 0 = 1?
-/ |
d5c7da483fd9408e0a7302334d0014c295ffbc1e | cabd1ea95170493667c024ef2045eb86d981b133 | /src/super/clausifier.lean | 9b0022e0b32a8b6d8ae0c44e68085d4c18d5946d | [] | no_license | semorrison/super | 31db4b5aa5ef4c2313dc5803b8c79a95f809815b | 0c6c03ba9c7470f801eb4d055294f424ff090308 | refs/heads/master | 1,630,272,140,541 | 1,511,054,739,000 | 1,511,054,756,000 | 114,317,807 | 0 | 0 | null | 1,513,304,776,000 | 1,513,304,775,000 | null | UTF-8 | Lean | false | false | 10,788 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .clause_ops
import .prover_state .misc_preprocessing
open expr list tactic monad decidable
universe u
namespace super
meta def try_option {a : Type u} (tac : tactic a) : tactic (option a) :=
lift some tac <|> return none
private meta def normalize : expr → tactic expr | e := do
e' ← whnf e reducible,
args' ← e'.get_app_args.mmap normalize,
return $ app_of_list e'.get_app_fn args'
meta def inf_normalize_l (c : clause) : tactic (list clause) :=
on_first_left c $ λtype, do
type' ← normalize type,
guard $ type' ≠ type,
h ← mk_local_def `h type',
return [([h], h)]
meta def inf_normalize_r (c : clause) : tactic (list clause) :=
on_first_right c $ λha, do
a' ← normalize ha.local_type,
guard $ a' ≠ ha.local_type,
hna ← mk_local_def `hna (imp a' c.local_false),
return [([hna], app hna ha)]
meta def inf_false_l (c : clause) : tactic (list clause) :=
first $ do i ← list.range c.num_lits,
if c.get_lit i = clause.literal.left `(false)
then [return []]
else []
meta def inf_false_r (c : clause) : tactic (list clause) :=
on_first_right c $ λhf,
if hf.local_type = c.local_false
then return [([], hf)]
else match hf.local_type with
| const ``false [] := do
pr ← mk_app ``false.rec [c.local_false, hf],
return [([], pr)]
| _ := failed
end
meta def inf_true_l (c : clause) : tactic (list clause) :=
on_first_left c $ λt,
match t with
| (const ``true []) := return [([], const ``true.intro [])]
| _ := failed
end
meta def inf_true_r (c : clause) : tactic (list clause) :=
first $ do i ← list.range c.num_lits,
if c.get_lit i = clause.literal.right (const ``true [])
then [return []]
else []
meta def inf_not_l (c : clause) : tactic (list clause) :=
on_first_left c $ λtype,
match type with
| app (const ``not []) a := do
hna ← mk_local_def `h (a.imp `(false)),
return [([hna], hna)]
| _ := failed
end
meta def inf_not_r (c : clause) : tactic (list clause) :=
on_first_right c $ λhna,
match hna.local_type with
| app (const ``not []) a := do
hnna ← mk_local_def `h ((a.imp `(false)).imp c.local_false),
return [([hnna], app hnna hna)]
| _ := failed
end
meta def inf_and_l (c : clause) : tactic (list clause) :=
on_first_left c $ λab,
match ab with
| (app (app (const ``and []) a) b) := do
ha ← mk_local_def `l a,
hb ← mk_local_def `r b,
pab ← mk_mapp ``and.intro [some a, some b, some ha, some hb],
return [([ha, hb], pab)]
| _ := failed
end
meta def inf_and_r (c : clause) : tactic (list clause) :=
on_first_right' c $ λhyp, do
pa ← mk_mapp ``and.left [none, none, some hyp],
pb ← mk_mapp ``and.right [none, none, some hyp],
return [([], pa), ([], pb)]
meta def inf_iff_l (c : clause) : tactic (list clause) :=
on_first_left c $ λab,
match ab with
| (app (app (const ``iff []) a) b) := do
hab ← mk_local_def `l (imp a b),
hba ← mk_local_def `r (imp b a),
pab ← mk_mapp ``iff.intro [some a, some b, some hab, some hba],
return [([hab, hba], pab)]
| _ := failed
end
meta def inf_iff_r (c : clause) : tactic (list clause) :=
on_first_right' c $ λhyp, do
pa ← mk_mapp ``iff.mp [none, none, some hyp],
pb ← mk_mapp ``iff.mpr [none, none, some hyp],
return [([], pa), ([], pb)]
meta def inf_or_r (c : clause) : tactic (list clause) :=
on_first_right c $ λhab,
match hab.local_type with
| (app (app (const ``or []) a) b) := do
hna ← mk_local_def `l (imp a c.local_false),
hnb ← mk_local_def `r (imp b c.local_false),
proof ← mk_app ``or.elim [a, b, c.local_false, hab, hna, hnb],
return [([hna, hnb], proof)]
| _ := failed
end
meta def inf_or_l (c : clause) : tactic (list clause) :=
on_first_left c $ λab,
match ab with
| (app (app (const ``or []) a) b) := do
ha ← mk_local_def `l a,
hb ← mk_local_def `l b,
pa ← mk_mapp ``or.inl [some a, some b, some ha],
pb ← mk_mapp ``or.inr [some a, some b, some hb],
return [([ha], pa), ([hb], pb)]
| _ := failed
end
meta def inf_all_r (c : clause) : tactic (list clause) :=
on_first_right' c $ λhallb,
match hallb.local_type with
| (pi n bi a b) := do
ha ← mk_local_def `x a,
return [([ha], app hallb ha)]
| _ := failed
end
lemma imp_l {F a b} [decidable a] : ((a → b) → F) → ((a → F) → F) :=
λhabf haf, decidable.by_cases
(assume ha : a, haf ha)
(assume hna : ¬a, habf (assume ha, absurd ha hna))
lemma imp_l' {F a b} [decidable F] : ((a → b) → F) → ((a → F) → F) :=
λhabf haf, decidable.by_cases
(assume hf : F, hf)
(assume hnf : ¬F, habf (assume ha, absurd (haf ha) hnf))
lemma imp_l_c {F : Prop} {a b} : ((a → b) → F) → ((a → F) → F) :=
λhabf haf, classical.by_cases
(assume hf : F, hf)
(assume hnf : ¬F, habf (assume ha, absurd (haf ha) hnf))
meta def inf_imp_l (c : clause) : tactic (list clause) :=
on_first_left_dn c $ λhnab,
match hnab.local_type with
| (pi _ _ (pi _ _ a b) _) :=
if b.has_var then failed else do
hna ← mk_local_def `na (imp a c.local_false),
pf ← first (do r ← [``super.imp_l, ``super.imp_l', ``super.imp_l_c],
[mk_app r [hnab, hna]]),
hb ← mk_local_def `b b,
return [([hna], pf), ([hb], app hnab (lam `a binder_info.default a hb))]
| _ := failed
end
meta def inf_ex_l (c : clause) : tactic (list clause) :=
on_first_left c $ λexp,
match exp with
| (app (app (const ``Exists [u]) dom) pred) := do
hx ← mk_local_def `x dom,
predx ← whnf $ app pred hx,
hpx ← mk_local_def `hpx predx,
return [([hx,hpx], app_of_list (const ``exists.intro [u])
[dom, pred, hx, hpx])]
| _ := failed
end
lemma demorgan' {F a} {b : a → Prop} : ((∀x, b x) → F) → (((∃x, b x → F) → F) → F) :=
assume hab hnenb,
classical.by_cases
(assume h : ∃x, ¬b x, begin cases h with x, apply hnenb, existsi x, intros, contradiction end)
(assume h : ¬∃x, ¬b x, hab (assume x,
classical.by_cases
(assume bx : b x, bx)
(assume nbx : ¬b x, have hf : false, { apply h, existsi x, assumption }, by contradiction)))
meta def inf_all_l (c : clause) : tactic (list clause) :=
on_first_left_dn c $ λhnallb,
match hnallb.local_type with
| pi _ _ (pi n bi a b) _ := do
enb ← mk_mapp ``Exists [none, some $ lam n binder_info.default a (imp b c.local_false)],
hnenb ← mk_local_def `h (imp enb c.local_false),
pr ← mk_app ``super.demorgan' [hnallb, hnenb],
return [([hnenb], pr)]
| _ := failed
end
meta def inf_ex_r (c : clause) : tactic (list clause) := do
(qf, ctx) ← c.open_constn c.num_quants,
skolemized ← on_first_right' qf $ λhexp,
match hexp.local_type with
| (app (app (const ``Exists [_]) d) p) := do
sk_sym_name_pp ← get_unused_name `sk (some 1),
inh_lc ← mk_local' `w binder_info.implicit d,
sk_sym ← mk_local_def sk_sym_name_pp (pis (ctx ++ [inh_lc]) d),
sk_p ← whnf_no_delta $ app p (app_of_list sk_sym (ctx ++ [inh_lc])),
sk_ax ← mk_mapp ``Exists [some (local_type sk_sym),
some (lambdas [sk_sym] (pis (ctx ++ [inh_lc]) (imp hexp.local_type sk_p)))],
sk_ax_name ← get_unused_name `sk_axiom (some 1), assert sk_ax_name sk_ax,
nonempt_of_inh ← mk_mapp ``nonempty.intro [some d, some inh_lc],
eps ← mk_mapp ``classical.epsilon [some d, some nonempt_of_inh, some p],
existsi (lambdas (ctx ++ [inh_lc]) eps),
eps_spec ← mk_mapp ``classical.epsilon_spec [some d, some p],
exact (lambdas (ctx ++ [inh_lc]) eps_spec),
sk_ax_local ← get_local sk_ax_name, cases sk_ax_local [sk_sym_name_pp, sk_ax_name],
sk_ax' ← get_local sk_ax_name,
return [([inh_lc], app_of_list sk_ax' (ctx ++ [inh_lc, hexp]))]
| _ := failed
end,
return $ skolemized.map (λs, s.close_constn ctx)
meta def first_some {a : Type} : list (tactic (option a)) → tactic (option a)
| [] := return none
| (x::xs) := do xres ← x, match xres with some y := return (some y) | none := first_some xs end
private meta def get_clauses_core' (rules : list (clause → tactic (list clause)))
: list clause → tactic (list clause) | cs :=
lift list.join $ do
cs.mmap $ λc, do first $
rules.map (λr, r c >>= get_clauses_core') ++ [return [c]]
meta def get_clauses_core (rules : list (clause → tactic (list clause))) (initial : list clause)
: tactic (list clause) := do
clauses ← get_clauses_core' rules initial,
filter (λc, lift bnot $ is_taut c) $ list.nub_on clause.type clauses
meta def clausification_rules_intuit : list (clause → tactic (list clause)) :=
[ inf_false_l, inf_false_r, inf_true_l, inf_true_r,
inf_not_l, inf_not_r,
inf_and_l, inf_and_r,
inf_iff_l, inf_iff_r,
inf_or_l, inf_or_r,
inf_ex_l,
inf_normalize_l, inf_normalize_r ]
meta def clausification_rules_classical : list (clause → tactic (list clause)) :=
[ inf_false_l, inf_false_r, inf_true_l, inf_true_r,
inf_not_l, inf_not_r,
inf_and_l, inf_and_r,
inf_iff_l, inf_iff_r,
inf_or_l, inf_or_r,
inf_imp_l, inf_all_r,
inf_ex_l,
inf_all_l, inf_ex_r,
inf_normalize_l, inf_normalize_r ]
meta def get_clauses_classical : list clause → tactic (list clause) :=
get_clauses_core clausification_rules_classical
meta def get_clauses_intuit : list clause → tactic (list clause) :=
get_clauses_core clausification_rules_intuit
meta def as_refutation : tactic unit := do
repeat (do intro1, skip),
tgt ← target,
if tgt.is_constant || tgt.is_local_constant then skip else do
local_false_name ← get_unused_name `F none, tgt_type ← infer_type tgt,
definev local_false_name tgt_type tgt, local_false ← get_local local_false_name,
target_name ← get_unused_name `target none,
assertv target_name (imp tgt local_false) (lam `hf binder_info.default tgt $ mk_var 0),
change local_false
meta def clauses_of_context : tactic (list clause) := do
local_false ← target,
l ← local_context,
l.mmap (clause.of_proof local_false)
meta def clausify_pre := preprocessing_rule $ assume new, lift list.join $ new.mmap $ λ dc, do
cs ← get_clauses_classical [dc.c],
if cs.length ≤ 1 then
return (cs.map $ λ c, { dc with c := c })
else
cs.mmap (λc, mk_derived c dc.sc)
-- @[super.inf]
meta def clausification_inf : inf_decl := inf_decl.mk 0 $
λ given, list.foldr (<|>) (return ()) $
do r ← clausification_rules_classical,
[do cs ← r given.c,
cs' ← get_clauses_classical cs,
cs'.mmap' (λc, mk_derived c given.sc.sched_now >>= add_inferred),
remove_redundant given.id []]
end super
|
93da4ba4011714ee3d563c55059e1fb6d785d555 | 6b45072eb2b3db3ecaace2a7a0241ce81f815787 | /algebra/group_power.lean | e8d1ffb285faa79c91925bffae35549ac7252a8a | [] | no_license | avigad/library_dev | 27b47257382667b5eb7e6476c4f5b0d685dd3ddc | 9d8ac7c7798ca550874e90fed585caad030bbfac | refs/heads/master | 1,610,452,468,791 | 1,500,712,839,000 | 1,500,713,478,000 | 69,311,142 | 1 | 0 | null | 1,474,942,903,000 | 1,474,942,902,000 | null | UTF-8 | Lean | false | false | 5,719 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
The power operation on monoids and groups. We separate this from group, because it depends on
nat, which in turn depends on other parts of algebra.
We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation
a^n is used for the first, but users can locally redefine it to gpow when needed.
Note: power adopts the convention that 0^0=1.
-/
import data.nat.basic data.int.basic ..tools.auto.finish
universe u
variable {α : Type u}
class has_pow_nat (α : Type u) :=
(pow_nat : α → nat → α)
definition pow_nat {α : Type u} [s : has_pow_nat α] : α → nat → α :=
has_pow_nat.pow_nat
infix ` ^ ` := pow_nat
class has_pow_int (α : Type u) :=
(pow_int : α → int → α)
definition pow_int {α : Type u} [s : has_pow_int α] : α → int → α :=
has_pow_int.pow_int
/- monoid -/
section monoid
open nat
variable [s : monoid α]
include s
definition monoid.pow (a : α) : ℕ → α
| 0 := 1
| (n+1) := a * monoid.pow n
instance monoid.has_pow_nat : has_pow_nat α :=
has_pow_nat.mk monoid.pow
@[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl
@[simp] theorem pow_succ (a : α) (n : ℕ) : a^(succ n) = a * a^n := rfl
@[simp] theorem pow_one (a : α) : a^1 = a := mul_one _
theorem pow_succ' (a : α) : ∀ (n : ℕ), a^(succ n) = (a^n) * a
| 0 := by simp
| (succ n) :=
suffices a * (a ^ n * a) = a * a ^ succ n, by simp [this],
by rw <-pow_succ'
@[simp] theorem one_pow : ∀ n : ℕ, (1 : α)^n = (1:α)
| 0 := rfl
| (succ n) := by simp; rw one_pow
theorem pow_add (a : α) : ∀ m n : ℕ, a^(m + n) = a^m * a^n
| m 0 := by simp
| m (n+1) := by rw [add_succ, pow_succ', pow_succ', pow_add, mul_assoc]
theorem pow_mul (a : α) (m : ℕ) : ∀ n, a^(m * n) = (a^m)^n
| 0 := by simp
| (succ n) := by rw [nat.mul_succ, pow_add, pow_succ', pow_mul]
theorem pow_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m :=
by rw [←pow_add, ←pow_add, add_comm]
end monoid
/- commutative monoid -/
section comm_monoid
open nat
variable [s : comm_monoid α]
include s
theorem mul_pow (a b : α) : ∀ n, (a * b)^n = a^n * b^n
| 0 := by simp
| (succ n) := by simp; rw mul_pow
end comm_monoid
section group
variable [s : group α]
include s
section nat
open nat
theorem inv_pow (a : α) : ∀n, (a⁻¹)^n = (a^n)⁻¹
| 0 := by simp
| (succ n) := by rw [pow_succ', _root_.pow_succ, mul_inv_rev, inv_pow]
theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : 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],
eq_mul_inv_of_mul_eq h2
theorem pow_inv_comm (a : α) : ∀m n, (a⁻¹)^m * a^n = a^n * (a⁻¹)^m
| 0 n := by simp
| m 0 := by simp
| (succ m) (succ n) := calc
a⁻¹ ^ succ m * a ^ succ n = (a⁻¹ ^ m * a⁻¹) * (a * a^n) : by rw [pow_succ', _root_.pow_succ]
... = a⁻¹ ^ m * (a⁻¹ * a) * a^n : by simp
... = a⁻¹ ^ m * a^n : by simp
... = a ^ n * (a⁻¹)^m : by rw pow_inv_comm
... = a ^ n * (a * a⁻¹) * (a⁻¹)^m : by simp
... = (a^n * a) * (a⁻¹ * (a⁻¹)^m) : by simp only [mul_assoc]
... = a ^ succ n * a⁻¹ ^ succ m : by rw [pow_succ', _root_.pow_succ]; simp
end nat
open int
definition gpow (a : α) : ℤ → α
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
local attribute [ematch] le_of_lt
open nat
private lemma gpow_add_aux (a : α) (m n : nat) :
gpow a ((of_nat m) + -[1+n]) = gpow a (of_nat m) * gpow a (-[1+n]) :=
or.elim (nat.lt_or_ge m (nat.succ n))
(assume : m < succ n,
have m ≤ n, from le_of_lt_succ this,
suffices gpow a -[1+ n-m] = (gpow a (of_nat m)) * (gpow a -[1+n]), by simp [*, of_nat_add_neg_succ_of_nat_of_lt],
suffices (a^(nat.succ (n - m)))⁻¹ = (gpow a (of_nat m)) * (gpow a -[1+n]), from this,
suffices (a^(nat.succ n - m))⁻¹ = (gpow a (of_nat m)) * (gpow a -[1+n]), by rw ←succ_sub; assumption,
by rw pow_sub; finish [gpow])
(assume : m ≥ succ n,
suffices gpow a (of_nat (m - succ n)) = (gpow a (of_nat m)) * (gpow a -[1+ n]),
by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption,
suffices a ^ (m - succ n) = a^m * (a^succ n)⁻¹, from this,
by rw pow_sub; assumption)
theorem gpow_add (a : α) : ∀i j : int, gpow a (i + j) = gpow a i * gpow a j
| (of_nat m) (of_nat n) := pow_add _ _ _
| (of_nat m) -[1+n] := gpow_add_aux _ _ _
| -[1+m] (of_nat n) := begin rw [add_comm, gpow_add_aux], unfold gpow, rw [←inv_pow, pow_inv_comm] end
| -[1+m] -[1+n] :=
suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ succ m)⁻¹ * (a ^ succ n)⁻¹, from this,
by rw [←succ_add_eq_succ_add, add_comm, pow_add, mul_inv_rev]
theorem gpow_comm (a : α) (i j : ℤ) : gpow a i * gpow a j = gpow a j * gpow a i :=
by rw [←gpow_add, ←gpow_add, add_comm]
end group
section ordered_ring
open nat
variable [s : linear_ordered_ring α]
include s
theorem pow_pos {a : α} (H : a > 0) : ∀ (n : ℕ), a ^ n > 0
| 0 := by simp; apply zero_lt_one
| (succ n) := begin simp, apply mul_pos, assumption, apply pow_pos end
theorem pow_ge_one_of_ge_one {a : α} (H : a ≥ 1) : ∀ (n : ℕ), a ^ n ≥ 1
| 0 := by simp; apply le_refl
| (succ n) :=
begin
simp, rw ←(one_mul (1 : α)),
apply mul_le_mul,
assumption,
apply pow_ge_one_of_ge_one,
apply zero_le_one,
transitivity, apply zero_le_one, assumption
end
end ordered_ring
|
38776aa480fdbe37297028acdfa4ebe4fe90eeb0 | 3984ab8555ab1e1084e22ef652544acdfc231f27 | /src/v0.1/dump/variance.lean | 6f4ec549eaa223f3194bf84495c29046dca28136 | [] | no_license | mrakgr/CFR-in-Lean | a35c7a478795cc794cc0caff3199cf28c8ee5448 | 720a3260297bcc158e08833d38964450dcaad2eb | refs/heads/master | 1,598,515,917,940 | 1,572,612,355,000 | 1,572,612,355,000 | 217,296,108 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,461 | lean | -- Not related to the CFR project.
-- The variance proof here was just a little thing I did in order to get familiar with Lean.
import data.rat
variable (α : Type)
theorem list.eq.identity : ∀ (l : list α), list.map id l = l
| [] := rfl
| (x :: l) := by simp [list.eq.identity l]
def mean (l : list rat) : rat := list.sum l / l.length
@[simp] def sqr (x : rat) := x ^ 2
theorem sqr.eq.a_minus_b (a b : rat) : sqr (a - b) = sqr a - 2 * a * b + sqr b := by {unfold sqr, ring}
def E (f : rat -> rat) (l : list rat) := mean $ list.map f l
def var (l : list rat) (m : rat) := E (fun x, (x - m) ^ 2) l
def var' (l : list rat) (m : rat) := mean (list.map sqr l) - sqr m
theorem list.eq.sum_add (f g : rat → rat) :
∀ (l : list rat), list.sum (list.map (λ x, f x + g x) l) = list.sum (list.map f l) + list.sum (list.map g l)
| [] := rfl
| (x :: l) := by simp [list.eq.sum_add]
theorem list.eq.sum_sub (f g : rat → rat) :
∀ (l : list rat), list.sum (list.map (λ x, f x - g x) l) = list.sum (list.map f l) - list.sum (list.map g l)
| [] := rfl
| (x :: l) := by {
have := list.eq.sum_sub l,
simp [list.eq.sum_add] at ⊢ this,
assumption
}
theorem list.eq.sum_mul (c : rat) (f : rat → rat) :
∀ (l : list rat), list.sum (list.map (λ x, c * f x) l) = c * list.sum (list.map f l)
| [] := by simp
| (x :: l) := by { simp, rw list.eq.sum_mul, ring }
theorem E.add {f g : rat -> rat} (l : list rat) : E (fun x, f x + g x) l = E f l + E g l :=
by { unfold E mean, simp only [list.length_map, list.eq.sum_add], ring }
theorem E.sub {f g : rat -> rat} (l : list rat) : E (fun x, f x - g x) l = E f l - E g l :=
by { unfold E mean, simp only [list.length_map, list.eq.sum_sub], ring }
theorem E.const_left {f : rat -> rat} (c : rat) (l : list rat) : E (fun x, c * f x) l = c * E f l :=
by { simp [E, mean], rw [list.eq.sum_mul], ring }
theorem rat.eq.mult_elim (n : rat) : n / n = 1 ∨ n = 0 :=
if h : n = 0 then or.inr h
else or.inl $ div_self h
theorem list.eq.repeat (c : rat) (l : list rat) : list.sum (list.map (fun _, c) l) = c * list.length l :=
by { simp, rw add_monoid.smul_eq_mul _ c, ring }
theorem E.const_none (c : rat) : ∀ (x : rat) (l : list rat), E (fun x, c) (x :: l) = c
| x l :=
by {
simp only [E, mean],
rw list.eq.repeat,
rw list.length_map,
simp,
from match rat.eq.mult_elim (1 + ↑(list.length l)) with
| or.inl is_one := by {
have := congr_arg (fun x, c * x) is_one,
simp at this,
ring at ⊢ this,
assumption
}
| or.inr is_zero := by {
ring at is_zero,
norm_cast at is_zero
}
end
}
theorem E.const_right (c : rat) (l : list rat) : E (fun x, x * c) l = E id l * c :=
calc
E (fun x, x * c) l = E (fun x, c * x) l : by simp [mul_comm]
... = c * E id l : by rw ← E.const_left; refl
... = E id l * c : by rw mul_comm
theorem E.const_both (c c' : rat) (l : list rat) : E (fun x, c * x * c') l = c * E id l * c' :=
calc
E (fun x, c * x * c') l = E (fun x, c * (x * c')) l : by simp [mul_assoc]
... = c * E (fun x, x * c') l : by rw E.const_left
... = c * (E id l * c') : by rw E.const_right
... = c * E id l * c' : by rw ← mul_assoc
theorem E.identity_is_mean (l : list rat) : E id l = mean l :=
calc
E id l = mean (list.map id l) : by unfold E
... = mean l : by rw list.eq.identity
theorem E.sqr_split (m : rat) (x : rat) (xs : list rat) : E (fun x, (x - m) ^ 2) (x :: xs) = E (fun x, x ^ 2) (x :: xs) - 2 * mean (x :: xs) * m + m ^ 2 :=
let l := x :: xs in
calc
E (fun x, (x - m) ^ 2) l = E (fun x, x ^ 2 - 2 * x * m + m ^ 2) l : by ring
... = E (fun x, x ^ 2) l - E (fun x, 2 * x * m) l + E (fun _, m ^ 2) l : by rw [E.add, E.sub]
... = E (fun x, x ^ 2) l - 2 * E id l * m + m ^ 2 : by rw [E.const_both, E.const_none]
... = E (fun x, x ^ 2) l - 2 * mean l * m + m ^ 2 : by rw [E.identity_is_mean]
theorem var_equals_var' : ∀ (l : list rat), var l (mean l) = var' l (mean l)
| [] := rfl
| l@(x :: xs) :=
let m := mean l in
calc
var l m = E (fun x, (x - m) ^ 2) l : by unfold var
... = E (fun x, x ^ 2) l - 2 * m * m + m ^ 2 : by rw E.sqr_split
... = E (fun x, x ^ 2) l - 2 * (m * m) + m ^ 2 : by rw [mul_assoc]
... = E (fun x, x ^ 2) l - 2 * m ^ 2 + m ^ 2 : by ring
... = E (fun x, x ^ 2) l - m ^ 2 : by ring
... = var' l m : by refl
-- Is also known as MSE = variance + bias ^ 2 proof
theorem mean_is_global_minima_of_variance (m' : rat) : ∀ (l : list rat), var l (mean l) <= var l m'
| [] := by simp [var]
| l@(x :: xs) :=
let m := mean l in
calc
var l m = E (fun x, (x - m) ^ 2) l : rfl
... = E (fun x, x ^ 2) l - 2 * m * m + m ^ 2 : by rw E.sqr_split
... <= E (fun x, x ^ 2) l - 2 * m * m' + m' ^ 2 : by { repeat {rw [sub_eq_add_neg, add_assoc]}, apply add_le_add_left, apply @le_of_add_le_add_right _ _ _ (m ^ 2), convert (pow_two_nonneg (m - m')); ring }
... = E (fun x, (x - m') ^ 2) l : by rw ← E.sqr_split
... = var l m' : rfl |
029e6eb471076e59484b760ae3363d351af28b89 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/category_theory/preadditive.lean | 5df0fefcffb004c4b07e494a07431b4319174d65 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 7,187 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.group.hom
import category_theory.limits.shapes.kernels
/-!
# Preadditive categories
A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that
composition of morphisms is linear in both variables.
This file contains a definition of preadditive category that directly encodes the definition given
above. The definition could also be phrased as follows: A preadditive category is a category
enriched over the category of Abelian groups. Once the general framework to state this in Lean is
available, the contents of this file should become obsolete.
## Main results
* Definition of preadditive categories and basic properties
* In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all
composable `g`.
* A preadditive category with kernels has equalizers.
## Implementation notes
The simp normal form for negation and composition is to push negations as far as possible to
the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)`
is simplified to `f ≫ g`.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
## Tags
additive, preadditive, Hom group, Ab-category, Ab-enriched
-/
universes v u
open category_theory.limits
open add_monoid_hom
namespace category_theory
variables (C : Type u) [category.{v} C]
/-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is
linear in both variables. -/
class preadditive :=
(hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance)
(add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R),
(f + f') ≫ g = f ≫ g + f' ≫ g . obviously)
(comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R),
f ≫ (g + g') = f ≫ g + f ≫ g' . obviously)
attribute [instance] preadditive.hom_group
restate_axiom preadditive.add_comp'
restate_axiom preadditive.comp_add'
attribute [simp] preadditive.add_comp preadditive.comp_add
end category_theory
open category_theory
namespace category_theory.preadditive
section preadditive
variables {C : Type u} [category.{v} C] [preadditive.{v} C]
/-- Composition by a fixed left argument as a group homomorphism -/
def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) :=
mk' (λ g, f ≫ g) $ λ g g', by simp
/-- Composition by a fixed right argument as a group homomorphism -/
def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) :=
mk' (λ f, f ≫ g) $ λ f f', by simp
@[simp, reassoc] lemma sub_comp {P Q R : C} (f f' : P ⟶ Q) (g : Q ⟶ R) :
(f - f') ≫ g = f ≫ g - f' ≫ g :=
map_sub (right_comp P g) f f'
-- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma.
@[reassoc, simp] lemma comp_sub {P Q R : C} (f : P ⟶ Q) (g g' : Q ⟶ R) :
f ≫ (g - g') = f ≫ g - f ≫ g' :=
map_sub (left_comp R f) g g'
@[simp, reassoc] lemma neg_comp {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ g = -(f ≫ g) :=
map_neg (right_comp _ _) _
/- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/
@[reassoc, simp] lemma comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : f ≫ (-g) = -(f ≫ g) :=
map_neg (left_comp _ _) _
@[reassoc] lemma neg_comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ (-g) = f ≫ g :=
by simp
instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) :=
⟨λ R g g', by { rw [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi], exact neg_inj }⟩
instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) :=
⟨λ R g g', by { rw [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono], exact neg_inj }⟩
@[priority 100]
instance preadditive_has_zero_morphisms : has_zero_morphisms.{v} C :=
{ has_zero := infer_instance,
comp_zero' := λ P Q f R, map_zero $ left_comp R f,
zero_comp' := λ P Q R f, map_zero $ right_comp P f }
lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) :
mono f :=
⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩
lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) :
mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 :=
⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩
lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)]
(w : kernel.ι f = 0) : mono f :=
mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, has_zero_morphisms.comp_zero])
lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) :
epi f :=
⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩
lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) :
epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 :=
⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩
lemma epi_of_cokernel_zero {X Y : C} (f : X ⟶ Y) [has_colimit (parallel_pair f 0 )]
(w : cokernel.π f = 0) : epi f :=
epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, has_zero_morphisms.zero_comp])
end preadditive
section equalizers
variables {C : Type u} [category.{v} C] [preadditive.{v} C]
section
variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y)
/-- A kernel of `f - g` is an equalizer of `f` and `g`. -/
def has_limit_parallel_pair [has_kernel (f - g)] :
has_limit (parallel_pair f g) :=
{ cone := fork.of_ι (kernel.ι (f - g)) (sub_eq_zero.1 $
by { rw ←comp_sub, exact kernel.condition _ }),
is_limit := fork.is_limit.mk _
(λ s, kernel.lift (f - g) (fork.ι s) $
by { rw comp_sub, apply sub_eq_zero.2, exact fork.condition _ })
(λ s, by simp)
(λ s m h, by { ext, simpa using h walking_parallel_pair.zero }) }
end
section
/-- If a preadditive category has all kernels, then it also has all equalizers. -/
def has_equalizers_of_has_kernels [has_kernels.{v} C] : has_equalizers.{v} C :=
@has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_limit_parallel_pair f g)
end
section
variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y)
/-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/
def has_colimit_parallel_pair [has_cokernel (f - g)] :
has_colimit (parallel_pair f g) :=
{ cocone := cofork.of_π (cokernel.π (f - g)) (sub_eq_zero.1 $
by { rw ←sub_comp, exact cokernel.condition _ }),
is_colimit := cofork.is_colimit.mk _
(λ s, cokernel.desc (f - g) (cofork.π s) $
by { rw sub_comp, apply sub_eq_zero.2, exact cofork.condition _ })
(λ s, by simp)
(λ s m h, by { ext, simpa using h walking_parallel_pair.one }) }
end
section
/-- If a preadditive category has all cokernels, then it also has all coequalizers. -/
def has_coequalizers_of_has_cokernels [has_cokernels.{v} C] : has_coequalizers.{v} C :=
@has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_colimit_parallel_pair f g)
end
end equalizers
end category_theory.preadditive
|
3a84d6b1b096f9d219b0e636602f428a99656be1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/subobject/well_powered.lean | 3336ecda1e17742e8b049730084fcec94e9d4546 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,907 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.subobject.basic
import category_theory.essentially_small
/-!
# Well-powered categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A category `(C : Type u) [category.{v} C]` is `[well_powered C]` if
for every `X : C`, we have `small.{v} (subobject X)`.
(Note that in this situtation `subobject X : Type (max u v)`,
so this is a nontrivial condition for large categories,
but automatic for small categories.)
This is equivalent to the category `mono_over X` being `essentially_small.{v}` for all `X : C`.
When a category is well-powered, you can obtain nonconstructive witnesses as
`shrink (subobject X) : Type v`
and
`equiv_shrink (subobject X) : subobject X ≃ shrink (subobject X)`.
-/
universes v u₁ u₂
namespace category_theory
variables (C : Type u₁) [category.{v} C]
/--
A category (with morphisms in `Type v`) is well-powered if `subobject X` is `v`-small for every `X`.
We show in `well_powered_of_mono_over_essentially_small` and `mono_over_essentially_small`
that this is the case if and only if `mono_over X` is `v`-essentially small for every `X`.
-/
class well_powered : Prop :=
(subobject_small : ∀ X : C, small.{v} (subobject X) . tactic.apply_instance)
instance small_subobject [well_powered C] (X : C) : small.{v} (subobject X) :=
well_powered.subobject_small X
@[priority 100]
instance well_powered_of_small_category (C : Type u₁) [small_category C] : well_powered C :=
{}
variables {C}
theorem essentially_small_mono_over_iff_small_subobject (X : C) :
essentially_small.{v} (mono_over X) ↔ small.{v} (subobject X) :=
essentially_small_iff_of_thin
theorem well_powered_of_essentially_small_mono_over
(h : ∀ X : C, essentially_small.{v} (mono_over X)) :
well_powered C :=
{ subobject_small := λ X, (essentially_small_mono_over_iff_small_subobject X).mp (h X), }
section
variables [well_powered C]
instance essentially_small_mono_over (X : C) :
essentially_small.{v} (mono_over X) :=
(essentially_small_mono_over_iff_small_subobject X).mpr (well_powered.subobject_small X)
end
section equivalence
variables {D : Type u₂} [category.{v} D]
theorem well_powered_of_equiv (e : C ≌ D) [well_powered C] : well_powered D :=
well_powered_of_essentially_small_mono_over $
λ X, (essentially_small_congr (mono_over.congr X e.symm)).2 $ by apply_instance
/-- Being well-powered is preserved by equivalences, as long as the two categories involved have
their morphisms in the same universe. -/
theorem well_powered_congr (e : C ≌ D) : well_powered C ↔ well_powered D :=
⟨λ i, by exactI well_powered_of_equiv e, λ i, by exactI well_powered_of_equiv e.symm⟩
end equivalence
end category_theory
|
ef1cc57696f1efc1d5b9dc76e652dcb724963a97 | 7541ac8517945d0f903ff5397e13e2ccd7c10573 | /src/category_theory/endofunctor_comp.lean | 40903f6c1752e1a64dc54b74cabdd185c6c6b2f5 | [] | no_license | ramonfmir/lean-category-theory | 29b6bad9f62c2cdf7517a3135e5a12b340b4ed90 | be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad | refs/heads/master | 1,586,110,684,637 | 1,541,927,184,000 | 1,541,927,184,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,068 | lean | import category_theory.functor_category
import category_theory.products
import category_theory.tactics.obviously
import tactic.interactive
universes u₁ v₁
open category_theory
def functor.prod' (C : Type u₁) [category.{u₁ v₁} C] : ( (C ⥤ C) × (C ⥤ C) ) ⥤ (C ⥤ C) :=
begin
refine
{ obj := λ a, a.1 ⋙ a.2,
map := λ a b f, f.1 ◫ f.2,
map_comp' := _ },
tidy,
-- Z_fst Z_snd Y_fst Y_snd : C ⥤ C,
-- g_fst : Y_fst ⟶ Z_fst,
-- g_snd : Y_snd ⟶ Z_snd,
-- X_fst X_snd : C ⥤ C,
-- f_fst : X_fst ⟶ Y_fst,
-- f_snd : X_snd ⟶ Y_snd
-- ⊢ ⇑f_snd (⇑X_fst X_1) ≫
-- ⇑g_snd (⇑X_fst X_1) ≫ functor.map Z_snd (⇑f_fst X_1) ≫ functor.map Z_snd (⇑g_fst X_1) =
-- ⇑f_snd (⇑X_fst X_1) ≫
-- functor.map Y_snd (⇑f_fst X_1) ≫ ⇑g_snd (⇑Y_fst X_1) ≫ functor.map Z_snd (⇑g_fst X_1)
conv_lhs { congr, skip, erw [←category.assoc] },
conv_lhs { congr, skip, congr, erw [←nat_trans.naturality] },
conv_rhs { congr, skip, erw [←category.assoc] }
end |
9e25315eeabc10db12c25f1165ef3ec3b474a067 | 41ebf3cb010344adfa84907b3304db00e02db0a6 | /uexp/tactic_paper_supplemental_material/robust_simp/robust_simp.lean | 31079597367939f817debf1c64670cfbd92434d6 | [
"BSD-2-Clause"
] | permissive | ReinierKoops/Cosette | e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb | eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29 | refs/heads/master | 1,686,483,953,198 | 1,624,293,498,000 | 1,624,293,498,000 | 378,997,885 | 0 | 0 | BSD-2-Clause | 1,624,293,485,000 | 1,624,293,484,000 | null | UTF-8 | Lean | false | false | 3,481 | lean | open tactic smt_tactic list expr
/-
cc_state is the state of the congruence closure procedure.
It uses an union-find datastructure to store equivalence classes of terms.
-/
structure rsimp_cfg :=
(max_rounds := 5)
meta def collect_implied_eqs (cfg : rsimp_cfg) : tactic cc_state :=
focus1 $ using_smt $
do add_lemmas_from_facts,
/- Execute E-matching for at most max_rounds -/
repeat_at_most cfg.max_rounds (ematch >> try close),
/- 'done' succeeds if the goal has been solved -/
(done >> return cc_state.mk)
<|>
/- If the goal was not solved return the state of the congruence closure procedure. -/
to_cc_state
meta def size : expr → nat
| (app f a) := size f + size a
| _ := 1
/- Fold over the equivalence class containing 'e'. -/
meta def choose (ccs : cc_state) (e : expr) : expr :=
ccs.fold_eqc e e $ λ (best_so_far : expr) (curr : expr),
if size curr < size best_so_far then curr else best_so_far
/- We use the rsimp' name here, since rsimp is already defined by the standard library. -/
meta def rsimp' (cfg : rsimp_cfg := {}) : tactic unit :=
do ccs ← collect_implied_eqs cfg,
/- If the goal has not been solved, use top down simplifier and ccs to simplify the goal. -/
try $ simp_top_down $ λ t,
/- Rewrite goal using a top-down simplifier, and the equalities stored at 'ccs'. -/
do root ← return $ ccs.root t, /- Retrieve the root of the equivalence class containing subterm 't'. -/
let t' := choose ccs root, /- Traverse the equivalence class and select the smallest element. -/
p ← ccs.eqv_proof t t', /- Construct a proof that 't' = 'repr' -/
return (t', p)
/- Examples -/
namespace example_1
constant f : nat → nat → nat
axiom fax : ∀ x, f x x = x
constant g : nat → nat
constant p : nat → nat → Prop
axiom pax : ∀ x, p x x
attribute [simp] [ematch_lhs] fax
example (a b c : nat) (h₁ : a = g b) (h₂ : a = b) : p (f (g a) a) b :=
begin
rsimp',
/- the new goal is |- p b b -/
apply pax
end
attribute [ematch] pax
example (a b c : nat) (h₁ : a = g b) (h₂ : a = b) : p (f (g a) a) b :=
by rsimp'
example (a b c : nat) (h₁ : a = g b) (h₂ : a = b) : p (f (g a) a) b :=
begin
simp_using_hs,
/- the new goal is |- p (f (g b) b) b -/
apply pax -- Failed
end
end example_1
namespace example_2
axiom max_add_cancel : ∀ a b : nat, max a (a + b) = a + b
constant p : nat → nat → Prop
axiom pax : ∀ x, p x x
attribute [simp] [ematch_lhs] max_assoc max_comm max_self max_add_cancel
attribute [simp] max_left_comm
example (a b c d : nat) (h : d = max c (a + b)) : p (max a (max d (b + a))) (max d (a + b)) :=
begin
rsimp',
/- The new goal is |- p d d -/
apply pax
end
example (a b c d : nat) (h : d = max c (a + b)) : p (max a (max d (b + a))) (max d (a + b)) :=
begin
simp_using_hs,
/- The new goal is |- p (max a (max c (a + b))) (max c (a + b)) -/
apply pax -- Failed
end
end example_2
namespace example_3
constant f : nat → nat → nat
constant g : nat → nat
axiom fax : ∀ x, f (g x) x = x
axiom gax : ∀ x, g (g x) = x
constant p : nat → nat → Prop
axiom pax : ∀ x, p x x
attribute [simp] [ematch_lhs] fax gax
example (a b : nat) : p (f (g (g a)) (g a)) (g a) :=
begin
rsimp',
apply pax
end
example (a b : nat) : p (f (g (g a)) (g a)) (g a) :=
begin
simp,
/- the new goal is |- p (f a (g a)) (g a) -/
apply pax -- Failed
end
end example_3
|
1527a66998c5044dd344a54438b6b33879592668 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/notation8.lean | 53323448cdf5482eb016b1301df1186da4b2fa5c | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 121 | lean | constant f : nat → nat → nat
constant g : nat → nat
check f $ 1 + g 1 $ g 2 + 2
check f $ g 1 $ (f $ 1 + 1 $ g 2)
|
8e47e2fdc53147c336c9dd0cf77cf6fe67335bf7 | f68ef9a599ec5575db7b285d4960e63c5d464ccc | /Exercises/Lista6-LucasMoschen.lean | 1cc4eb49e83aaa12d5355544aa3118a933828646 | [] | no_license | lucasmoschen/discrete-mathematics | a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3 | 0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e | refs/heads/master | 1,677,111,757,003 | 1,611,500,097,000 | 1,611,500,097,000 | 205,903,359 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 860 | lean | -- Lucas Moschen
-- Teorema de Cantor
import data.set
variables X Y: Type
def surjective {X: Type} {Y: Type} (f : X → Y) : Prop := ∀ y, ∃ x, f x = y
theorem Cantor : ∀ (A: set X), ¬ ∃ (f: A → set A), surjective f :=
begin
intro A,
intro h,
cases h with f h1,
have h2: ∃ x, f x = {t : A | ¬ (t ∈ f t)}, from h1 {t : A | ¬ (t ∈ f t)},
cases h2 with x h3,
apply or.elim (classical.em (x ∈ {t : A | ¬ (t ∈ f t)})),
intro h4,
have h5: ¬ (x ∈ f x), from h4,
rw (eq.symm h3) at h4,
apply h5 h4,
intro h4,
rw (eq.symm h3) at h4,
have h5: x ∈ {t : A | ¬ (t ∈ f t)}, from h4,
rw (eq.symm h3) at h5,
apply h4 h5,
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.