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
584547522595dbab884fe0253548f3f7c24a4d12
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/complex/basic.lean
96f9722ffe706c0713d40e18236103a5f80d8a23
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,844
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.sqrt /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. The result that the complex numbers are algebraically closed, see `field_theory.algebraic_closure`. -/ open_locale big_operators /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex open_locale complex_conjugate noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : can_lift ℂ ℝ := { cond := λ z, z.im = 0, coe := coe, prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ } instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩ instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (of_real_mul_re _ _) (of_real_mul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity defined in `data.complex.module.lean`. -/ instance : comm_ring ℂ := by refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, sub := has_sub.sub, one := 1, mul := (*), zero_add := λ z, by { apply ext_iff.2, simp }, add_zero := λ z, by { apply ext_iff.2, simp }, nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩, npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩, gsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} /-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field` instance. -/ instance : ring ℂ := by apply_instance /-- The "real part" map, considered as an additive group homomorphism. -/ def re_add_group_hom : ℂ →+ ℝ := { to_fun := re, map_zero' := zero_re, map_add' := add_re } @[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def im_add_group_hom : ℂ →+ ℝ := { to_fun := im, map_zero' := zero_im, map_add' := add_im } @[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl @[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n := by rw [pow_bit0', I_mul_I] @[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [pow_bit1', I_mul_I] /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It is recommended to use the ring automorphism version `star_ring_aut`, available under the notation `conj` in the locale `complex_conjugate`. -/ instance : star_ring ℂ := { star := λ z, ⟨z.re, -z.im⟩, star_involutive := λ x, by simp only [eta, neg_neg], star_mul := λ a b, by ext; simp [add_comm]; ring, star_add := λ a b, by ext; simp [add_comm] } @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ lemma eq_conj_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 := ⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ @[simp] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq : monoid_with_zero_hom ℂ ℝ := { to_fun := λ z, z.re * z.re + z.im * z.im, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { dsimp, ring } } lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z := by { ext; simp [norm_sq, mul_comm], } @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero @[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := (norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero) @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by { rw [sub_eq_add_neg, norm_sq_add], simp only [ring_equiv.map_neg, mul_neg_eq_neg_mul_symm, neg_re, tactic.ring.add_neg_eq_sub, norm_sq_neg] } /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ by simp protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } @[simp] lemma I_fpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n := by rw [fpow_bit0', I_mul_I] @[simp] lemma I_fpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [fpow_bit1', I_mul_I] lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := of_real.map_div r s @[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := of_real.map_fpow r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := norm_sq.map_inv z @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := norm_sq.map_div z w /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := of_real.map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0, mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) := by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm, mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := has_abs.abs @[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 /-- The **triangle inequality** for complex numbers. -/ lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : |(abs z)| = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub_comm : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, |abs z - abs w| ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] @[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n := by rw [← of_real_int_cast, abs_of_real, int.cast_abs] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)] /-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative. Complex numbers with different imaginary parts are incomparable. -/ protected def partial_order : partial_order ℂ := { le := λ z w, z.re ≤ w.re ∧ z.im = w.im, lt := λ z w, z.re < w.re ∧ z.im = w.im, lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto }, le_refl := λ x, ⟨le_rfl, rfl⟩, le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩, le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 } section complex_order localized "attribute [instance] complex.partial_order" in complex_order lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl @[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def] @[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def] @[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real @[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im := by rw [le_def, not_and_distrib, not_le] lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring. -/ protected def ordered_comm_ring : ordered_comm_ring ℂ := { zero_le_one := ⟨zero_le_one, rfl⟩, add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩, mul_pos := λ z w hz hw, by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1], .. complex.partial_order, .. complex.comm_ring } localized "attribute [instance] complex.ordered_comm_ring" in complex_order /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring. (That is, an ordered ring in which every element of the form `star z * z` is nonnegative.) In fact, the nonnegative elements are precisely those of this form. This hold in any `C^*`-algebra, e.g. `ℂ`, but we don't yet have `C^*`-algebras in mathlib. -/ protected def star_ordered_ring : star_ordered_ring ℂ := { star_mul_self_nonneg := λ z, ⟨by simp [add_nonneg, mul_self_nonneg], by simp [mul_comm]⟩ } localized "attribute [instance] complex.star_ordered_ring" in complex_order end complex_order /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← ring_equiv.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) @[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ end complex
1d8443e4dd928cc6dd26a0792adc972979a7f4a7
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/local_ns_shadow.lean
47a6ee456d89f89ab1de45c3bb5fc781c49c8318
[ "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
400
lean
#check λ (a b : nat) (heq : a = b), (heq.symm : b = a) example : ∀ (a b : nat), a = b → b = a := begin exact λ (a b : nat) (heq : a = b), heq.symm end example : ∀ (a b : nat), a = b → b = a := begin intros a b heq, exact heq.symm end section parameter x : nat def foo.bla : nat × nat := (x, x+1) def g : nat := foo.bla.fst + foo.bla.snd end example : g 10 = 21 := rfl
74045a253f75939b8c61a7547aac09bf5d657d86
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/classical_lie_algebras.lean
2377feb35517c5717f372263343926fcd39376b1
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
3,025
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie_algebra import linear_algebra.matrix /-! # Classical Lie algebras This file is the place to find definitions and basic properties of the classical Lie algebras: * Aₙ sl(n+1) * Bₙ so(2n+1) * Cₙ sp(2n) * Dₙ so(2n) As of April 2020, the definition of Aₙ is in place while the others still need to be provided. ## Tags classical lie algebra, special linear -/ universes u₁ u₂ namespace lie_algebra open_locale matrix variables (n : Type u₁) (R : Type u₂) variables [fintype n] [decidable_eq n] [nonzero_comm_ring R] local attribute [instance] matrix.lie_ring local attribute [instance] matrix.lie_algebra @[simp] lemma matrix_trace_commutator_zero (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 := begin change matrix.trace n R R (X ⬝ Y - Y ⬝ X) = 0, simp only [matrix.trace_mul_comm, linear_map.map_sub, sub_self], end namespace special_linear /-- The special linear Lie algebra: square matrices of trace zero. -/ def sl : lie_subalgebra R (matrix n n R) := { lie_mem := λ X Y _ _, by { suffices : matrix.trace n R R ⁅X, Y⁆ = 0, apply (list.mem_pure _ 0).2 this, apply matrix_trace_commutator_zero, }, ..linear_map.ker (matrix.trace n R R) } lemma sl_bracket (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl section elementary_basis variables {n} (i j : n) /-- It is useful to define these matrices for explicit calculations in sl n R. -/ abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0 @[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl) @[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h @[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 := begin ext k, rw matrix.diag_apply, suffices : ¬(i = k ∧ j = k), by exact if_neg this, rintros ⟨e₁, e₂⟩, apply h, subst e₁, exact e₂, end lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h] /-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural basis of sl n R. -/ def Eb (h : j ≠ i) : sl n R := ⟨E R i j, by { change E R i j ∈ linear_map.ker (matrix.trace n R R), simp [E_trace_zero R i j h], }⟩ @[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl end elementary_basis lemma sl_non_abelian (h : 1 < fintype.card n) : ¬lie_algebra.is_abelian ↥(sl n R) := begin rcases fintype.exists_pair_of_one_lt_card h with ⟨i, j, hij⟩, let A := Eb R i j hij, let B := Eb R j i hij.symm, intros c, have c' : A.val ⬝ B.val = B.val ⬝ A.val := by { rw [←sub_eq_zero, ←sl_bracket, c.abelian], refl, }, have : 1 = 0 := by simpa [matrix.mul_val, hij] using (congr_fun (congr_fun c' i) i), exact one_ne_zero this, end end special_linear end lie_algebra
5f0c9bcd76f5280805e1260b53f183b4826f8686
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/completionDocString.lean
51b7de4e4659c4e1b872abd14acc7a590984e13d
[ "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
67
lean
#eval Array.insertAt --^ textDocument/completion
65b6c6e575332cf0b57480970cf46adbed7574f0
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/presheaves/locally_ringed.lean
4aaaa84d646e20c254bfa7e59c2f551ec4503cb3
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
975
lean
-- import category_theory.presheaves.sheaves -- import topology.Top.stalks -- import algebra.CommRing.limits -- import ring_theory.ideals -- universes v -- open category_theory.examples -- open category_theory.presheaves -- open category_theory.limits -- variables (X : Top.{v}) -- instance : has_colimits.{v+1 v} CommRing := sorry -- def structure_sheaf := sheaf.{v+1 v} X CommRing -- structure ringed_space := -- (𝒪 : structure_sheaf X) -- structure locally_ringed_space extends ringed_space X := -- (locality : ∀ x : X, is_local_ring (stalk_at.{v+1 v} 𝒪.presheaf x).1) -- coercion from sheaf to presheaf? -- def ringed_space.of_topological_space : ringed_space X := -- { 𝒪 := { presheaf := { obj := λ U, sorry /- ring of continuous functions U → ℂ -/, -- map := sorry, -- map_id' := sorry, -- map_comp' := sorry }, -- sheaf_condition := sorry, -- } }
eaba717707bce14f918055d96a32ad672fef588d
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Meta/Tactic.lean
9d200763a37d55c84efd4be861ef7647e566e014
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
247
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Tactic.Intro import Init.Lean.Meta.Tactic.Assumption
f783c7656bd894ac62828d57467e1c8480c3936b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/polynomial_galois_group.lean
7a2697257221ccd2c9be8abe808585d76121db7e
[ "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
21,716
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import analysis.complex.polynomial import field_theory.galois import group_theory.perm.cycle.type /-! # Galois Groups of Polynomials In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale classical polynomial open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : F[X]) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal instance : has_coe_to_fun p.gal (λ _, p.splitting_field → p.splitting_field) := alg_equiv.has_coe_to_fun instance apply_mul_semiring_action : mul_semiring_action p.gal p.splitting_field := alg_equiv.apply_mul_semiring_action @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : F[X]).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : F[X]).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : F[X]).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : F[X]).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) -- The `algebra p.splitting_field E` instance above behaves badly when -- `E := p.splitting_field`, since it may result in a unification problem -- `is_splitting_field.lift.to_ring_hom.to_algebra =?= algebra.id`, -- which takes an extremely long time to resolve, causing timeouts. -- Since we don't really care about this definition, marking it as irreducible -- causes that unification to error out early. attribute [irreducible] gal.algebra /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := mul_action.to_perm_hom _ _ lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw injective_iff_map_eq_one, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal, { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set, polynomial.map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : F[X]} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : F[X] → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : F[X]}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) ((minpoly.irreducible qx_int).dvd_symm hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : F[X]}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := algebra.is_integral_of_finite _ _ α, use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := (minpoly.irreducible hα).dvd_symm p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : ℚ[X]} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : ℚ[X]) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add], refine eq.symm (le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))), simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff], apply_instance }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 := λ z, by rw [set.mem_to_finset, mem_root_set hp], have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.eq_conj_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { intro z, rw [finset.inf_eq_inter, finset.mem_inter, hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
dea0c9f181e9061cd2a3906493c138c76d0d270e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/computability/turing_machine.lean
6fe07d75f83b50e8adc5beeaa4176263a57cae29
[ "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
109,895
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.option import data.fintype.prod import data.fintype.pi import data.vector.basic import data.pfun import logic.function.iterate import order.basic import tactic.apply_fun /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → part output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default : Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat default n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by { rintro ⟨i, rfl⟩ ⟨j, rfl⟩, exact ⟨i+j, by simp [list.repeat_add]⟩ } theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, add_tsub_cancel_of_le h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, tsub_add_cancel_of_le], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only, cases lt_or_le _ _ with h h, {rw list.inth_append _ _ _ h}, rw list.inth_eq_default _ h, cases le_or_lt _ _ with h₂ h₂, {rw list.inth_eq_default _ h₂}, rw [list.inth_eq_nth_le _ h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [add_tsub_cancel_of_le h, list.length_append, list.length_repeat] }, simp only [list_blank.nth_mk] at H, cases lt_or_le i l₁.length with h' h', { simp only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', ←list.inth_eq_nth_le _ h, ←list.inth_eq_nth_le _ h', H] }, { simp only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', ←list.inth_eq_default _ h', H, list.inth_eq_nth_le _ h] } end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons] } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f default = default) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨default, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') (λ _, Γ → Γ') := ⟨pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f default = default := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth_eq_iget_nth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f default = list.repeat default n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `part.none`. -/ def eval {σ} (f : σ → option σ) : σ → part σ := pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} (hab : reaches f a b) (hac : reaches f a c) : reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' e, h' _ $ part.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ part.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, _⟩; rw e at h; cases part.mem_some_iff.1 h, cases IH a' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply part.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply part.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := part.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := part.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default : Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write default⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default, default⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default, default, default⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some default, default, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M default), default)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [part.map_eq_map, part.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := TM1.stmts M S ×ˢ finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc default = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin letI := classical.dec_eq Γ, let n := fintype.card Γ, obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value default (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal default⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc default = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal default⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default, default, default⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some default, default, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [←proj_map_nth, hL, ←list.map_reverse, list_blank.nth_mk, list.inth_eq_iget_nth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on (λ l, _), simp end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal default⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | (TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.load a q) := tr_stmts₁ q | (TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.map], { rw [list.inth_eq_nth_le, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk], cases lt_or_gt_of_ne h with h h, { rw list.inth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.inth_eq_default, list.inth_eq_default]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail], { rw [list.inth_eq_default], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, e, list.map, list.reverse_cons], cases lt_or_gt_of_ne h with h h, { rw list.inth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.inth_eq_default, list.inth_eq_default]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ le_rfl, obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], rsuffices ⟨b, c, r⟩ : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, { exact ⟨b, c, trans_gen.head' rfl r⟩ }, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update default k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth_eq_iget_nth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth_eq_iget_nth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth_eq_iget_nth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂, obtain ⟨_, ⟨L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases part.mem_unique h₁ h₃, exact ⟨_, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
3f60e2b451fdbbad9fbd15112e8e8dd810cdbc21
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/natural_isomorphism.lean
deec92b254f73abb7e016002d2ef303f6f8b03bb
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,339
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, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism /-! # Natural isomorphisms For the most part, natural isomorphisms are just another sort of isomorphism. We provide some special support for extracting components: * if `α : F ≅ G`, then `a.app X : F.obj X ≅ G.obj X`, and building natural isomorphisms from components: * ``` nat_iso.of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G ``` only needing to check naturality in one direction. ## Implementation Note that `nat_iso` is a namespace without a corresponding definition; we put some declarations that are specifically about natural isomorphisms in the `iso` namespace so that they are available using dot notation. -/ open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simps] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end } section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end /-- A natural transformation is an isomorphism if all its components are isomorphisms. -/ -- Making this an instance would cause a typeclass inference loop with `is_iso_app_of_is_iso`. def is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, begin have h := congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm, simp only [is_iso.inv_hom_id_assoc, is_iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end } } /-- The components of a natural isomorphism are isomorphisms. -/ instance is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := { inv := (inv α).app X, hom_inv_id' := congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, inv_hom_id' := congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X } @[simp] lemma is_iso_inv_app (α : F ⟶ G) [is_iso α] (X) : (inv α).app X = inv (α.app X) := rfl /-- Construct a natural isomorphism between functors by giving object level isomorphisms, and checking naturality only in the forward direction. -/ def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := { hom := { app := λ X, (app X).hom }, ..is_iso_of_is_iso_app _ } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl /-- Horizontal composition of natural isomorphisms. -/ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end end nat_iso end category_theory
7b35b90461292292e074b6cbd62ea8e011b67703
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0406.lean
d80b1bea22c24a410d4b6aa85b3a498f573f3fa8
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
272
lean
example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, split, show q, from hq, show p, from hp, end example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, split, show p, from hp, show q, from hq end
9def2c37f03f2e3c90ece347eb5eba4f6d03263e
3863d2564418bccb1859e057bf5a4ef240e75fd7
/library/logic/connectives.lean
c46e9e1439140d854b41591c46349a6dd2c46718
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
5,721
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Haitao Zhang The propositional connectives. See also init.datatypes and init.logic. -/ open eq.ops variables {a b c d : Prop} /- implies -/ definition imp (a b : Prop) : Prop := a → b theorem imp.id (H : a) : a := H theorem imp.intro (H : a) (H₂ : b) : a := H theorem imp.mp (H : a) (H₂ : a → b) : b := H₂ H theorem imp.syl (H : a → b) (H₂ : c → a) (Hc : c) : b := H (H₂ Hc) theorem imp.left (H : a → b) (H₂ : b → c) (Ha : a) : c := H₂ (H Ha) theorem imp_true (a : Prop) : (a → true) ↔ true := iff_true_intro (imp.intro trivial) theorem true_imp (a : Prop) : (true → a) ↔ a := iff.intro (assume H, H trivial) imp.intro theorem imp_false (a : Prop) : (a → false) ↔ ¬ a := iff.rfl theorem false_imp (a : Prop) : (false → a) ↔ true := iff_true_intro false.elim /- not -/ theorem not.elim {A : Type} (H1 : ¬a) (H2 : a) : A := absurd H2 H1 theorem not.mto {a b : Prop} : (a → b) → ¬b → ¬a := imp.left theorem not_imp_not_of_imp {a b : Prop} : (a → b) → ¬b → ¬a := not.mto theorem not_not_of_not_implies : ¬(a → b) → ¬¬a := not.mto not.elim theorem not_of_not_implies : ¬(a → b) → ¬b := not.mto imp.intro theorem not_not_em : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), not_em (or.inr (not.mto or.inl not_em)) theorem not_iff_not (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (not.mto (iff.mpr H)) (not.mto (iff.mp H)) /- and -/ definition not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := not.mto and.left definition not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := not.mto and.right theorem and.imp_left (H : a → b) : a ∧ c → b ∧ c := and.imp H imp.id theorem and.imp_right (H : a → b) : c ∧ a → c ∧ b := and.imp imp.id H theorem and_of_and_of_imp_of_imp (H₁ : a ∧ b) (H₂ : a → c) (H₃ : b → d) : c ∧ d := and.imp H₂ H₃ H₁ theorem and_of_and_of_imp_left (H₁ : a ∧ c) (H : a → b) : b ∧ c := and.imp_left H H₁ theorem and_of_and_of_imp_right (H₁ : c ∧ a) (H : a → b) : c ∧ b := and.imp_right H H₁ theorem and_imp_iff (a b c : Prop) : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λH a b, H (and.intro a b)) and.rec theorem and_imp_eq (a b c : Prop) : (a ∧ b → c) = (a → b → c) := propext !and_imp_iff /- or -/ definition not_or : ¬a → ¬b → ¬(a ∨ b) := or.rec theorem or_of_or_of_imp_of_imp (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → d) : c ∨ d := or.imp H₂ H₃ H₁ theorem or_of_or_of_imp_left (H₁ : a ∨ c) (H : a → b) : b ∨ c := or.imp_left H H₁ theorem or_of_or_of_imp_right (H₁ : c ∨ a) (H : a → b) : c ∨ b := or.imp_right H H₁ theorem or.elim3 (H : a ∨ b ∨ c) (Ha : a → d) (Hb : b → d) (Hc : c → d) : d := or.elim H Ha (assume H₂, or.elim H₂ Hb Hc) theorem or_resolve_right (H₁ : a ∨ b) (H₂ : ¬a) : b := or.elim H₁ (not.elim H₂) imp.id theorem or_resolve_left (H₁ : a ∨ b) : ¬b → a := or_resolve_right (or.swap H₁) theorem or.imp_distrib : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := iff.intro (λH, and.intro (imp.syl H or.inl) (imp.syl H or.inr)) (and.rec or.rec) theorem or_iff_right_of_imp {a b : Prop} (Ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec Ha imp.id) or.inr theorem or_iff_left_of_imp {a b : Prop} (Hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec imp.id Hb) or.inl theorem or_iff_or (H1 : a ↔ c) (H2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp H1) (iff.mp H2)) (or.imp (iff.mpr H1) (iff.mpr H2)) /- DeMorgan -/ theorem DeMorgan_or (a b : Prop) : ¬(a ∨ b) ↔ ¬a ∧ ¬b := iff.intro (suppose ¬(a ∨ b), have ¬a, from not.intro( suppose a, have a ∨ b, from or.inl this, show false, from absurd this `¬(a ∨ b)`), have ¬b, from not.intro( suppose b, have a ∨ b, from or.inr this, show false, from absurd this `¬(a ∨ b)`), show ¬a ∧ ¬b, from and.intro `¬a` this) (suppose ¬a ∧ ¬b, not.intro( suppose a ∨ b, show false, from or.elim this (suppose a, absurd this (and.elim_left `¬a ∧ ¬b`)) (suppose b, absurd this (and.elim_right `¬a ∧ ¬b`)))) /- distributivity -/ theorem and.left_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := iff.intro (and.rec (λH, or.imp (and.intro H) (and.intro H))) (or.rec (and.imp_right or.inl) (and.imp_right or.inr)) theorem and.right_distrib (a b c : Prop) : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := iff.trans (iff.trans !and.comm !and.left_distrib) (or_iff_or !and.comm !and.comm) theorem or.left_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := iff.intro (or.rec (λH, and.intro (or.inl H) (or.inl H)) (and.imp or.inr or.inr)) (and.rec (or.rec (imp.syl imp.intro or.inl) (imp.syl or.imp_right and.intro))) theorem or.right_distrib (a b c : Prop) : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := iff.trans (iff.trans !or.comm !or.left_distrib) (and_congr !or.comm !or.comm) /- iff -/ definition iff.def : (a ↔ b) = ((a → b) ∧ (b → a)) := rfl theorem forall_imp_forall {A : Type} {P Q : A → Prop} (H : ∀a, (P a → Q a)) (p : ∀a, P a) (a : A) : Q a := (H a) (p a) theorem forall_iff_forall {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∀a, P a) ↔ (∀a, Q a) := iff.intro (λp a, iff.elim_left (H a) (p a)) (λq a, iff.elim_right (H a) (q a)) theorem imp_iff {P : Prop} (Q : Prop) (p : P) : (P → Q) ↔ Q := iff.intro (λf, f p) imp.intro
66084b57d3165045a90438417c7da61e9d398bac
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/tactic/linarith.lean
a323a353a7a93fbd92048e44ff9fbb8219dc93ea
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
29,653
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: perform slightly better on ℤ by strengthening t < 0 hyps to t + 1 ≤ 0 @TODO: alternative discharger to `ring` @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ import tactic.ring data.nat.gcd data.list.basic meta.rb_map meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, nonpos_of_neg_nonneg (by simp at this; exact this) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩ meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0, indexed by ℕ. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | _, _ := none end /-- Turns an expression into a map from ℕ to ℤ, for use in a comp object. The expr_map ℕ argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr : expr_map ℕ → expr → option (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (match m.find e with | some k := return (m, mk_rb_map.insert k 1) | none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int, m.find e with | some 0, _ := return ⟨m, mk_rb_map⟩ | some z, _ := return ⟨m, mk_rb_map.insert 0 z⟩ | none, some k := return (m, mk_rb_map.insert k 1) | none, none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (e : expr) (m : expr_map ℕ) : option (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold : expr_map ℕ → list expr → (list (option comp) × expr_map ℕ) | m [] := ([], m) | m (h::t) := match to_comp h m with | some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp) | none := let (l, mp) := to_comp_fold m t in (none::l, mp) end /-- Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, let (l', map) := to_comp_fold mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≤, =} 0. Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≤, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do extp ← match cfg.restrict_type with | none := do (_, z) ← infer_type h >>= get_rel_sides, infer_type z | some rtp := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, return m end, hz ← mk_neg_one_lt_zero_pf extp, l' ← if cfg.restrict_type.is_some then l.mfilter (λ e, succeeds (ineq_pf_tp e >>= is_def_eq extp)) else return l, l' ← add_neg_eq_pfs l', (sum.inl contr, inputs) ← elim_all_vars.run (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat inductive {u} tree (α : Type u) : Type u | nil {} : tree | node : α → tree → tree → tree def tree.repr {α} [has_repr α] : tree α → string | tree.nil := "nil" | (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")" instance {α} [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩ meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) | `(%%e1 / %%e2) := --do q ← is_numeric e2, return q.num.nat_abs match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | _ := fail "mk_coe_comp_prf failed: proof is not an inequality" end meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do (a, _) ← infer_type h >>= get_rel_sides, infer_type a >>= unify `(ℕ), ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. -/ meta def prove_false_by_linarith (cfg : linarith_config) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, ls ← l'.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none), prove_false_by_linarith1 cfg ls.reduce_option end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.interactive_aux (cfg : linarith_config) : parse ident* → (parse (tk "using" *> pexpr_list)?) → tactic unit | l (some pe) := pe.mmap (λ p, i_to_expr p >>= note_anon) >> linarith.interactive_aux l none | [] none := do t ← target, if t = `(false) then local_context >>= prove_false_by_linarith cfg else match get_contr_lemma_name t with | some nm := seq (applyc nm) (intro1 >> linarith.interactive_aux [] none) | none := if cfg.exfalso then exfalso >> linarith.interactive_aux [] none else fail "linarith failed: target type is not an inequality." end | ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith h1 h2 h3` will only use hypotheses h1, h2, h3. `linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (ids : parse (many ident)) (using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit := linarith.interactive_aux cfg ids using_hyps end
7b2d5867e157e85d8175b0596a0576f061373317
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Algebra/Group/Defs.lean
71f1fc620c86a3d010831833672788f449c878b2
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
12,770
lean
import Mathlib.Data.Nat.Basic -- *only* for notation ℕ which should be in a "prelude" import Mathlib.Data.Int.Basic -- *only* for notation ℤ which should be in a "prelude" import Mathlib.Tactic.Spread /-! # Typeclasses for monoids and groups etc -/ /- ## Stuff which was in core Lean 3 -- this should also be in a "prelude" -- it is not in mathlib3's algebra.group.defs -/ class Zero (α : Type u) where zero : α instance [Zero α] : OfNat α (nat_lit 0) where ofNat := Zero.zero class One (α : Type u) where one : α instance [One α] : OfNat α (nat_lit 1) where ofNat := One.one class Inv (α : Type u) where inv : α → α postfix:max "⁻¹" => Inv.inv /- ## The trick for adding a natural action onto monoids -/ section nat_action variable {M : Type u} -- see npow_rec comment for explanation about why not nsmul_rec n a + a /-- The fundamental scalar multiplication in an additive monoid. `nsmul_rec n a = a+a+...+a` n times. Use instead `n • a`, which has better definitional behavior. -/ def nsmul_rec [Zero M] [Add M] : ℕ → M → M | 0 , a => 0 | n+1, a => a + nsmul_rec n a -- use `x * npow_rec n x` and not `npow_rec n x * x` in the definition to make sure that -- definitional unfolding of `npow_rec` is blocked, to avoid deep recursion issues. /-- The fundamental power operation in a monoid. `npow_rec n a = a*a*...*a` n times. Use instead `a ^ n`, which has better definitional behavior. -/ def npow_rec [One M] [Mul M] : ℕ → M → M | 0 , a => 1 | n+1, a => a * npow_rec n a end nat_action section int_action /-- The fundamental scalar multiplication in an additive group. `gsmul_rec n a = a+a+...+a` n times, for integer `n`. Use instead `n • a`, which has better definitional behavior. -/ def gsmul_rec {G : Type u} [Zero G] [Add G] [Neg G]: ℤ → G → G | (Int.ofNat n) , a => nsmul_rec n a | (Int.negSucc n), a => - (nsmul_rec n.succ a) /-- The fundamental power operation in a group. `gpow_rec n a = a*a*...*a` n times, for integer `n`. Use instead `a ^ n`, which has better definitional behavior. -/ def gpow_rec {G : Type u} [One G] [Mul G] [Inv G] : ℤ → G → G | (Int.ofNat n) , a => npow_rec n a | (Int.negSucc n), a => (npow_rec n.succ a) ⁻¹ end int_action /- ## Additive semigroups, monoids and groups -/ /- ### Semigroups -/ class AddSemigroup (A : Type u) extends Add A where add_assoc (a b c : A) : (a + b) + c = a + (b + c) theorem add_assoc {G : Type u} [AddSemigroup G] : ∀ a b c : G, (a + b) + c = a + (b + c) := AddSemigroup.add_assoc class AddCommSemigroup (A : Type u) extends AddSemigroup A where add_comm (a b : A) : a + b = b + a theorem add_comm {A : Type u} [AddCommSemigroup A] (a b : A) : a + b = b + a := AddCommSemigroup.add_comm a b /- ### Cancellative semigroups -/ class IsAddLeftCancel (A : Type u) [Add A] where add_left_cancel (a b c : A) : a + b = a + c → b = c class IsAddRightCancel (A : Type u) [Add A] where add_right_cancel (a b c : A) : b + a = c + a → b = c section AddLeftCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddLeftCancel A] {a b c : A} theorem add_left_cancel : a + b = a + c → b = c := IsAddLeftCancel.add_left_cancel a b c theorem add_left_cancel_iff : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem add_right_injective (a : G) : function.injective (c * .) := --λ a b => add_left_cancel @[simp] theorem add_right_inj (a : A) {b c : A} : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ --theorem add_ne_add_right (a : A) {b c : A} : a + b ≠ a + c ↔ b ≠ c := --(add_right_injective a).ne_iff end AddLeftCancel_lemmas section AddRightCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddRightCancel A] {a b c : A} theorem add_right_cancel : b + a = c + a → b = c := IsAddRightCancel.add_right_cancel a b c theorem add_right_cancel_iff : b + a = c + a ↔ b = c := ⟨add_right_cancel, λ h => h ▸ rfl⟩ @[simp] theorem add_left_inj (a : A) {b c : A} : b + a = c + a ↔ b = c := ⟨add_right_cancel, λ h => h ▸ rfl⟩ end AddRightCancel_lemmas /- ### Additive monoids -/ class AddMonoid (A : Type u) extends AddSemigroup A, Zero A where add_zero (a : A) : a + 0 = a zero_add (a : A) : 0 + a = a nsmul : ℕ → A → A := nsmul_rec nsmul_zero' : ∀ x, nsmul 0 x = 0 -- fill in with tactic once we can do this nsmul_succ' : ∀ (n : ℕ) x, nsmul n.succ x = x + nsmul n x -- fill in with tactic section AddMonoid_lemmas variable {A : Type u} [AddMonoid A] {a b c : A} @[simp] theorem add_zero (a : A) : a + 0 = a := AddMonoid.add_zero a @[simp] theorem zero_add (a : A) : 0 + a = a := AddMonoid.zero_add a theorem left_neg_eq_right_neg (hba : b + a = 0) (hac : a + c = 0) : b = c := by rw [←zero_add c, ←hba, add_assoc, hac, add_zero b] end AddMonoid_lemmas /- ### Commutative additive monoids -/ class AddCommMonoid (A : Type u) extends AddMonoid A where add_comm (a b : A) : a + b = b + a instance (A : Type u) [AddCommMonoid A] : AddCommSemigroup A where __ := ‹AddCommMonoid A› /- ### sub_neg_monoids Additive groups can "pick up" several equal but not defeq actions of ℤ. This trick isolates one such action, `gsmul`, and decrees it to be "the canonical one". -/ class SubNegMonoid (A : Type u) extends AddMonoid A, Neg A, Sub A := (sub := λ a b => a + -b) (sub_eq_add_neg : ∀ a b : A, a - b = a + -b) (gsmul : ℤ → A → A := gsmul_rec) (gsmul_zero' : ∀ (a : A), gsmul 0 a = 0) (gsmul_succ' (n : ℕ) (a : A) : gsmul (Int.ofNat n.succ) a = a + gsmul (Int.ofNat n) a) (gsmul_neg' (n : ℕ) (a : A) : gsmul (Int.negSucc n) a = -(gsmul ↑(n.succ) a)) /- ### Additive groups -/ class AddGroup (A : Type u) extends SubNegMonoid A where add_left_neg (a : A) : -a + a = 0 section AddGroup_lemmas variable {A : Type u} [AddGroup A] {a b c : A} @[simp] theorem add_left_neg : ∀ a : A, -a + a = 0 := AddGroup.add_left_neg theorem neg_add_self (a : A) : -a + a = 0 := add_left_neg a @[simp] theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rw [← add_assoc, add_left_neg, zero_add] @[simp] theorem neg_eq_of_add_eq_zero (h : a + b = 0) : -a = b := left_neg_eq_right_neg (neg_add_self a) h @[simp] theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add_left_neg a) @[simp] theorem add_right_neg (a : A) : a + -a = 0 := by rw [←add_left_neg (-a), neg_neg] -- synonym theorem add_neg_self (a : A) : a + -a = 0 := add_right_neg a @[simp] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rw [add_assoc, add_right_neg, add_zero] instance (A : Type u) [AddGroup A] : IsAddRightCancel A where add_right_cancel a b c h := by rw [← add_neg_cancel_right b a, h, add_neg_cancel_right] instance (A : Type u) [AddGroup A] : IsAddLeftCancel A where add_left_cancel a b c h := by rw [← neg_add_cancel_left a b, h, neg_add_cancel_left] end AddGroup_lemmas class AddCommGroup (A : Type u) extends AddGroup A where add_comm (a b : A) : a + b = b + a instance (A : Type u) [AddCommGroup A] : AddCommMonoid A where __ := ‹AddCommGroup A› /- ## Multiplicative semigroups, monoids and groups -/ /- ## Semigroups -/ class Semigroup (G : Type u) extends Mul G where mul_assoc (a b c : G) : (a * b) * c = a * (b * c) theorem mul_assoc {G : Type u} [Semigroup G] : ∀ a b c : G, a * b * c = a * (b * c) := Semigroup.mul_assoc class CommSemigroup (G : Type u) extends Semigroup G where mul_comm (a b : G) : a * b = b * a theorem mul_comm {M : Type u} [CommSemigroup M] : ∀ a b : M, a * b = b * a := CommSemigroup.mul_comm /- ### Cancellative semigroups -/ class IsMulLeftCancel (G : Type u) [Mul G] where mul_left_cancel (a b c : G) : a * b = a * c → b = c class IsMulRightCancel (G : Type u) [Mul G] where mul_right_cancel (a b c : G) : b * a = c * a → b = c section MulLeftCancel variable {G : Type u} [Semigroup G] [IsMulLeftCancel G] {a b c : G} theorem mul_left_cancel : a * b = a * c → b = c := IsMulLeftCancel.mul_left_cancel a b c theorem mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem mul_right_injective (a : G) : function.injective (c * .) := --λ a b => mul_left_cancel @[simp] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ --theorem mul_ne_mul_right (a : G) {b c : G} : a * b ≠ a * c ↔ b ≠ c := --(mul_right_injective a).ne_iff end MulLeftCancel section MulRightCancel variable {G : Type u} [Semigroup G] [IsMulRightCancel G] {a b c : G} theorem mul_right_cancel : b * a = c * a → b = c := IsMulRightCancel.mul_right_cancel a b c theorem mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, λ h => h ▸ rfl⟩ @[simp] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, λ h => h ▸ rfl⟩ end MulRightCancel /- ### Monoids -/ class Monoid (M : Type u) extends Semigroup M, One M where mul_one (m : M) : m * 1 = m one_mul (m : M) : 1 * m = m npow : ℕ → M → M := npow_rec npow_zero' : ∀ x, npow 0 x = 1 -- fill in with tactic once we can do this npow_succ' : ∀ (n : ℕ) x, npow n.succ x = x * npow n x -- fill in with tactic section Monoid variable {M : Type u} [Monoid M] @[defaultInstance high] instance Monoid.HPow : HPow M ℕ M := ⟨λ a n => Monoid.npow n a⟩ @[simp] theorem mul_one : ∀ (a : M), a * 1 = a := Monoid.mul_one @[simp] theorem one_mul : ∀ (a : M), 1 * a = a := Monoid.one_mul theorem npow_eq_pow (n : ℕ) (a : M) : Monoid.npow n a = a^n := rfl @[simp] theorem pow_zero : ∀ (a : M), a ^ (0:ℕ) = 1 := Monoid.npow_zero' theorem pow_succ' : ∀ (n : ℕ) (a : M), a ^ n.succ = a * a ^ n := Monoid.npow_succ' theorem pow_mul_comm (a : M) (n : ℕ) : a^n * a = a * a^n := by induction n with | zero => simp | succ n ih => simp [ih, pow_succ', mul_assoc] theorem pow_succ (n : ℕ) (a : M) : a ^ n.succ = a ^ n * a := by rw [pow_succ', pow_mul_comm] @[simp] theorem pow_one (a : M) : a ^ (1:ℕ) = a := by rw [Nat.one_succ_zero, pow_succ, pow_zero, one_mul] theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with | zero => simp | succ n ih => rw [Nat.add_succ, pow_succ',ih, pow_succ', ← mul_assoc, ← mul_assoc, pow_mul_comm] theorem pow_mul {M} [Monoid M] (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with | zero => simp | succ n ih => rw [Nat.mul_succ, pow_add, ih, pow_succ', pow_mul_comm] theorem left_inv_eq_right_inv {M : Type u} [Monoid M] {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] end Monoid /- ### Commutative monoids -/ class CommMonoid (M : Type u) extends Monoid M where mul_comm (a b : M) : a * b = b * a section CommMonoid variable {M} [CommMonoid M] instance : CommSemigroup M where __ := ‹CommMonoid M› theorem mul_pow {M} [CommMonoid M] (a b : M) (n : ℕ) : (a * b)^n= a^n * b^n := by induction n with | zero => simp | succ n ih => simp [pow_succ', ih, @mul_comm M _, @mul_assoc M _] end CommMonoid /- ### Div inv monoids -/ class DivInvMonoid (G : Type u) extends Monoid G, Inv G, Div G := (div := λ a b => a * b⁻¹) (div_eq_mul_inv : ∀ a b : G, a / b = a * b⁻¹) (gpow : ℤ → G → G := gpow_rec) (gpow_zero' : ∀ (a : G), gpow 0 a = 1) (gpow_succ' : ∀ (n : ℕ) (a : G), gpow (Int.ofNat n.succ) a = a * gpow (Int.ofNat n) a) (gpow_neg' : ∀ (n : ℕ) (a : G), gpow (Int.negSucc n) a = (gpow n.succ a) ⁻¹) /- ### Groups -/ class Group (G : Type u) extends DivInvMonoid G where mul_left_inv (a : G) : a⁻¹ * a = 1 section Group_lemmas variable {G : Type u} [Group G] {a b c : G} @[simp] theorem mul_left_inv : ∀ a : G, a⁻¹ * a = 1 := Group.mul_left_inv theorem inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp] theorem inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp] theorem inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp] theorem inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := by rw [←mul_left_inv (a⁻¹), inv_inv] -- synonym theorem mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp] theorem mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] end Group_lemmas class CommGroup (G : Type u) extends Group G where mul_comm (a b : G) : a * b = b * a instance (G : Type u) [CommGroup G] : CommMonoid G where __ := ‹CommGroup G›
d0426b2c94a5faa82e3a7e63db93a0401646ffe6
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/functions/polymomrphic/ordered_pair_example.lean
f2b37b0fb9eef3270690fde94d080c6f007c3424
[]
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
1,749
lean
/- Explicit type arguments -/ /- A polymorphic type, poly, with one type parameter, here named alpha. Objects of this type represent ordered pairs where both elements are of the same type, e.g., ordered pairs of natural numbers, ordered pairs of strings, etc. -/ inductive my_prod (α : Type) : Type | mk : α → α → my_prod def p := my_prod.mk 3 3 /- Note: The fact that we use a Greek letter, alpha, for the type argument, has no real significance other than being a convention in Lean. -/ def p1 := my_prod.mk 3 5 def swap (α : Type) : my_prod α → my_prod α | (my_prod.mk x y) := my_prod.mk y x def p2 := swap ℕ p1 -- type argument explicit #reduce p2 /- Implicit type arguments -/ /- This version uses curly braces around the declaration of the type argument, α. What this tells Lean is that it should not expect an explicit type parameter, rather it should use type inference to infer the value of this parameter automatically (from the value to which the funtion is applied). -/ def swap' {α : Type} : my_prod α → my_prod α | (my_prod.mk x y) := my_prod.mk y x def p3 := swap' p1 -- type argument implicit -- It worked! /- If you have specified use of implicit arguments you may NOT give arguments explicitly. If for some reason you must (typically because Lean does not have enough information to infer them), turn off implicit arguments by prefixing a given function application @. -/ def p4 := @swap' ℕ p1 -- type argument explicit /- In summary, when you want the programmer to be able to apply a polymorphic functions without explicitly giving type arguments, enclose the declarations of the arguments in curly braces and then do not give these arguments when the f unctions are applied. -/
7857874f9e2c44bb26c526785dd013664fc65bd6
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/subring.lean
b87c731d52a5729e1eec9c0fbfc23db309fd81bf
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
32,751
lean
/- Copyright (c) 2020 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors : Ashvni Narayanan -/ import deprecated.subring import group_theory.subgroup import ring_theory.subsemiring /-! # Subrings Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type whose terms correspond to subrings of `R`. This is the preferred way to talk about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`) are not in this file, and they will ultimately be deprecated. We prove that subrings are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subring R`, sending a subset of `R` to the subring it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)` `(A : subring R) (B : subring S) (s : set R)` * `subring R` : the type of subrings of a ring `R`. * `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings. * `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set. * `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M` form a `galois_insertion`. * `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f` * `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`. * `prod A B : subring (R × S)` : the product of subrings * `f.range : subring B` : the range of the ring homomorphism `f`. * `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`, the subring of `R` where `f x = g x` ## Implementation notes A subring is implemented as a subsemiring which is also an additive subgroup. The initial PR was as a submonoid which is also an additive subgroup. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subring's underlying set. ## Tags subring, subrings -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T] set_option old_structure_cmd true /-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R /-- Reinterpret a `subring` as a `subsemiring`. -/ add_decl_doc subring.to_subsemiring /-- Reinterpret a `subring` as an `add_subgroup`. -/ add_decl_doc subring.to_add_subgroup namespace subring /-- The underlying submonoid of a subring. -/ def to_submonoid (s : subring R) : submonoid R := { carrier := s.carrier, ..s.to_subsemiring.to_submonoid } instance : has_coe (subring R) (set R) := ⟨subring.carrier⟩ instance : has_mem R (subring R) := ⟨λ m S, m ∈ (S:set R)⟩ instance : has_coe_to_sort (subring R) := ⟨Type*, λ S, {x : R // x ∈ S}⟩ /-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R) (hm : ↑sm = s) (ha : ↑sa = s) : subring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem, neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) {x : R} : x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha).to_submonoid = sm := submonoid.ext' hm.symm @[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa =s) : (subring.mk' s sm sa hm ha).to_add_subgroup = sa := add_subgroup.ext' ha.symm end subring /-- Construct a `subring` from a set satisfying `is_subring`. -/ def set.to_subring (S : set R) [is_subring S] : subring R := { carrier := S, one_mem' := is_submonoid.one_mem, mul_mem' := λ a b, is_submonoid.mul_mem, zero_mem' := is_add_submonoid.zero_mem, add_mem' := λ a b, is_add_submonoid.add_mem, neg_mem' := λ a, is_add_subgroup.neg_mem } protected lemma subring.exists {s : subring R} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists protected lemma subring.forall {s : subring R} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall /-- A `subsemiring` containing -1 is a `subring`. -/ def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R := { neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, } ..s.to_submonoid, ..s.to_add_submonoid } namespace subring variables (s : subring R) /-- Two subrings are equal if the underlying subsets are equal. -/ theorem ext' ⦃s t : subring R⦄ (h : (s : set R) = t) : s = t := by { cases s, cases t, congr' } /-- Two subrings are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {s t : subring R} : s = t ↔ (s : set R) = t := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two subrings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h /-- A subring contains the ring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subring contains the ring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subring is closed under negation. -/ theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subring is closed under subtraction -/ theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) } /-- Product of a list of elements in a subring is in the subring. -/ lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subring is in the subring. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/ lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in an `subring` of a `ring` is in the `subring`. -/ lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the subring. -/ lemma prod_mem {R : Type*} [comm_ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subring` of a `ring` indexed by a `finset` is in the `subring`. -/ lemma sum_mem {R : Type*} [ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : R) ∈ s := by simp only [← gsmul_one, gsmul_mem, one_mem] /-- A subring of a ring inherits a ring structure -/ instance to_ring : ring s := { right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl @[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 := ⟨λ h, subtype.ext (trans h s.coe_zero.symm), λ h, h.symm ▸ s.coe_zero⟩ /-- A subring of a `comm_ring` is a `comm_ring`. -/ instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s} /-- A subring of a non-trivial ring is non-trivial. -/ instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s := s.to_subsemiring.nontrivial /-- A subring of a ring with no zero divisors has no zero divisors. -/ instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s := s.to_subsemiring.no_zero_divisors /-- A subring of an integral domain is an integral domain. -/ instance {R} [integral_domain R] (s : subring R) : integral_domain s := { .. s.nontrivial, .. s.no_zero_divisors, .. s.to_comm_ring } /-- A subring of an `ordered_ring` is an `ordered_ring`. -/ instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s := subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/ instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s := subtype.coe_injective.ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/ instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) : linear_ordered_ring s := subtype.coe_injective.linear_ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/ instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) : linear_ordered_comm_ring s := subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural ring hom from a subring of ring `R` to `R`. -/ def subtype (s : subring R) : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-! # Partial order -/ instance : partial_order (subring R) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, .. partial_order.lift (coe : subring R → set R) ext' } lemma le_def {s t : subring R} : s ≤ t ↔ ∀ ⦃x : R⦄, x ∈ s → x ∈ t := iff.rfl @[simp, norm_cast] lemma coe_subset_coe {s t : subring R} : (s : set R) ⊆ t ↔ s ≤ t := iff.rfl @[simp, norm_cast] lemma coe_ssubset_coe {s t : subring R} : (s : set R) ⊂ t ↔ s < t := iff.rfl @[simp, norm_cast] lemma mem_coe {S : subring R} {m : R} : m ∈ (S : set R) ↔ m ∈ S := iff.rfl @[simp, norm_cast] lemma coe_coe (s : subring R) : ↥(s : set R) = s := rfl @[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl /-! # top -/ /-- The subring `R` of the ring `R`. -/ instance : has_top (subring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl /-! # comap -/ /-- The preimage of a subring along a ring homomorphism is a subring. -/ def comap {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) : subring R := { carrier := f ⁻¹' s.carrier, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_subgroup.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! # map -/ /-- The image of a subring along a ring homomorphism is a subring. -/ def map {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring R) : subring S := { carrier := f '' s.carrier, .. s.to_submonoid.map (f : R →* S), .. s.to_add_subgroup.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := ext' $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap end subring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-! # range -/ /-- The range of a ring homomorphism, as a subring of the target. -/ def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S := (⊤ : subring R).map f @[simp] lemma coe_range : (f.range : set S) = set.range f := set.image_univ @[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := by simp [range] lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range := mem_range.mpr ⟨x, rfl⟩ lemma map_range : f.range.map g = (g.comp f).range := (⊤ : subring R).map_map g f -- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } end ring_hom namespace subring /-! # bot -/ instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩ instance : inhabited (subring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) := ring_hom.coe_range (int.cast_ring_hom R) lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x := ring_hom.mem_range /-! # inf -/ /-- The inf of two subrings is their intersection. -/ instance : has_inf (subring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩ @[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subring R) := ⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subring R)) : ((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_subgroup (s : set (subring R)) : (Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _ /-- Subrings of a ring form a complete lattice. -/ instance : complete_lattice (subring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from coe_subset_coe) is_glb_binfi)} /-! # subring closure of a subset -/ /-- The `subring` generated by a set. -/ def closure (s : set R) : subring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S := mem_Inf /-- The subring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx /-- A subring `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ (x : R), p x → p (-x)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) := ⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx ) (add_subgroup.zero_mem _) (add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) ) (λ x y hx hy, add_subgroup.add_mem _ hx hy ) (λ x hx, add_subgroup.neg_mem _ hx ) ( λ x y hx hy, add_subgroup.closure_induction hy (λ q hq, add_subgroup.closure_induction hx ( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) ) ( begin rw zero_mul q, apply add_subgroup.zero_mem _, end ) ( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end ) ( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) ) ( begin rw mul_zero x, apply add_subgroup.zero_mem _, end ) ( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end ) ( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ), λ h, add_subgroup.closure_induction h ( λ x hx, submonoid.closure_induction hx ( λ x hx, subset_closure hx ) ( one_mem _ ) ( λ x y hx hy, mul_mem _ hx hy ) ) ( zero_mem _ ) (λ x y hx hy, add_mem _ hx hy) ( λ x hx, neg_mem _ hx ) ⟩ theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) : (∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) := add_subgroup.closure_induction (mem_closure_iff.1 h) (λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h]; clear_aux_decl; tauto!⟩) ⟨[], by simp⟩ (λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t), by simp [hl2, hm2]⟩) (λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2 ⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp) (by simp [list.map_cons, add_comm] {contextual := tt})⟩) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subring `S` equals `S`. -/ lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subring.gi R).gc.l_Sup lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t` as a subring of `R × S`. -/ def prod (s : subring R) (t : subring S) : subring (R × S) := { carrier := (s : set R).prod t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup} @[norm_cast] lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = (s : set R).prod (t : set S) := rfl lemma mem_prod {s : subring R} {t : subring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subring R) : s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subring S) : (⊤ : subring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subrings is isomorphic to their product as rings. -/ def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } /-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings. Note that this fails without the directedness assumption (the union of two subrings is typically not a subring) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, let U : subring R := subring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) : ((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subring namespace ring_hom variables [ring T] {s : subring R} open subring /-- Restriction of a ring homomorphism to a subring of the domain. -/ def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype @[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def range_restrict (f : R →+* S) : R →+* f.range := f.cod_restrict' f.range $ λ x, ⟨x, subring.mem_top x, rfl⟩ @[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩ lemma range_top_iff_surjective {f : R →+* S} : f.range = (⊤ : subring S) ↔ function.surjective f := subring.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.range = (⊤ : subring S) := range_top_iff_surjective.2 hf /-- The subring of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subring of R -/ def eq_locus (f g : R →+* S) : subring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/ lemma eq_on_set_closure {f g : R →+* S} {s : set R} (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 lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subring generated by a set equals the subring generated by the image of the set. -/ lemma map_closure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subring open ring_hom /-- The ring homomorphism associated to an inclusion of subrings. -/ def inclusion {S T : subring R} (h : S ≤ T) : S →* T := S.subtype.cod_restrict' _ (λ x, h x.2) @[simp] lemma range_subtype (s : subring R) : s.subtype.range = s := ext' $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨mem_coe.2 $ one_mem ⊥, hp.2⟩) end subring namespace ring_equiv variables {s t : subring R} /-- Makes the identity isomorphism from a proof two subrings of a multiplicative monoid are equal. -/ def subring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ subring.ext'_iff.1 h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.range`. -/ def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.range := { to_fun := λ x, f.range_restrict x, inv_fun := λ x, (g ∘ f.range.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end ring_equiv namespace subring variables {s : set R} local attribute [reducible] closure @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx end subring lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) : (k : R) * g ∈ G := by { convert add_subgroup.gsmul_mem G h k, simp }
8ce0ef799489bcf3e204853d137e0c8798f801e6
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/polynomial/algebra_map.lean
b79a4638a68af1fbc0bee5d5fdd46ab4cc827032
[ "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
9,991
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import algebra.algebra.tower /-! # Theory of univariate polynomials We show that `polynomial A` is an R-algebra when `A` is an R-algebra. We promote `eval₂` to an algebra hom in `aeval`. -/ noncomputable theory open finset open_locale big_operators namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] {p q r : polynomial R} variables [semiring A] [algebra R A] /-- Note that this instance also provides `algebra R (polynomial R)`. -/ instance algebra_of_algebra : algebra R (polynomial A) := add_monoid_algebra.algebra lemma algebra_map_apply (r : R) : algebra_map R (polynomial A) r = C (algebra_map R A r) := rfl /-- When we have `[comm_ring R]`, the function `C` is the same as `algebra_map R (polynomial R)`. (But note that `C` is defined when `R` is not necessarily commutative, in which case `algebra_map` is not available.) -/ lemma C_eq_algebra_map {R : Type*} [comm_ring R] (r : R) : C r = algebra_map R (polynomial R) r := rfl instance [nontrivial A] : nontrivial (subalgebra R (polynomial A)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], refine ⟨X, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top, algebra_map_apply, not_forall], intro x, rw [ext_iff, not_forall], refine ⟨1, _⟩, simp [coeff_C], end⟩⟩ @[simp] lemma alg_hom_eval₂_algebra_map {R A B : Type*} [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] (p : polynomial R) (f : A →ₐ[R] B) (a : A) : f (eval₂ (algebra_map R A) a p) = eval₂ (algebra_map R B) (f a) p := begin dsimp [eval₂, finsupp.sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast, alg_hom.commutes], end @[simp] lemma eval₂_algebra_map_X {R A : Type*} [comm_ring R] [ring A] [algebra R A] (p : polynomial R) (f : polynomial R →ₐ[R] A) : eval₂ (algebra_map R A) (f X) p = f p := begin conv_rhs { rw [←polynomial.sum_C_mul_X_eq p], }, dsimp [eval₂, finsupp.sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast], simp [polynomial.C_eq_algebra_map], end @[simp] lemma ring_hom_eval₂_algebra_map_int {R S : Type*} [ring R] [ring S] (p : polynomial ℤ) (f : R →+* S) (r : R) : f (eval₂ (algebra_map ℤ R) r p) = eval₂ (algebra_map ℤ S) (f r) p := alg_hom_eval₂_algebra_map p f.to_int_alg_hom r @[simp] lemma eval₂_algebra_map_int_X {R : Type*} [ring R] (p : polynomial ℤ) (f : polynomial ℤ →+* R) : eval₂ (algebra_map ℤ R) (f X) p = f p := -- Unfortunately `f.to_int_alg_hom` doesn't work here, as typeclasses don't match up correctly. eval₂_algebra_map_X p { commutes' := λ n, by simp, .. f } end comm_semiring section aeval variables [comm_semiring R] {p q : polynomial R} variables [semiring A] [algebra R A] variables {B : Type*} [semiring B] [algebra R B] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom' (algebra_map R A) x (λ a, algebra.commutes _ _) } variables {R A} @[ext] lemma alg_hom_ext {f g : polynomial R →ₐ[R] A} (h : f X = g X) : f = g := by { ext, exact h } theorem aeval_def (p : polynomial R) : aeval x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_zero : aeval x (0 : polynomial R) = 0 := alg_hom.map_zero (aeval x) @[simp] lemma aeval_X : aeval x (X : polynomial R) = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval x (C r) = algebra_map R A r := eval₂_C _ x @[simp] lemma aeval_monomial {n : ℕ} {r : R} : aeval x (monomial n r) = (algebra_map _ _ r) * x^n := eval₂_monomial _ _ @[simp] lemma aeval_X_pow {n : ℕ} : aeval x ((X : polynomial R)^n) = x^n := eval₂_X_pow _ _ @[simp] lemma aeval_add : aeval x (p + q) = aeval x p + aeval x q := alg_hom.map_add _ _ _ @[simp] lemma aeval_one : aeval x (1 : polynomial R) = 1 := alg_hom.map_one _ @[simp] lemma aeval_bit0 : aeval x (bit0 p) = bit0 (aeval x p) := alg_hom.map_bit0 _ _ @[simp] lemma aeval_bit1 : aeval x (bit1 p) = bit1 (aeval x p) := alg_hom.map_bit1 _ _ @[simp] lemma aeval_nat_cast (n : ℕ) : aeval x (n : polynomial R) = n := alg_hom.map_nat_cast _ _ lemma aeval_mul : aeval x (p * q) = aeval x p * aeval x q := alg_hom.map_mul _ _ _ lemma aeval_comp {A : Type*} [comm_semiring A] [algebra R A] (x : A) : aeval x (p.comp q) = (aeval (aeval x q) p) := eval₂_comp (algebra_map R A) @[simp] lemma aeval_map {A : Type*} [comm_semiring A] [algebra R A] [algebra A B] [is_scalar_tower R A B] (b : B) (p : polynomial R) : aeval b (p.map (algebra_map R A)) = aeval b p := by rw [aeval_def, eval₂_map, ←is_scalar_tower.algebra_map_eq, ←aeval_def] theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul_noncomm (algebra_map R A) _ (λ k, algebra.commutes _ _), eval₂_X, ih] } end theorem aeval_alg_hom (f : A →ₐ[R] B) (x : A) : aeval (f x) = f.comp (aeval x) := alg_hom.ext $ λ p, by rw [eval_unique (f.comp (aeval x)), alg_hom.comp_apply, aeval_X, aeval_def] theorem aeval_alg_hom_apply (f : A →ₐ[R] B) (x : A) (p : polynomial R) : aeval (f x) p = f (aeval x p) := alg_hom.ext_iff.1 (aeval_alg_hom f x) p lemma aeval_algebra_map_apply (x : R) (p : polynomial R) : aeval (algebra_map R A x) p = algebra_map R A (p.eval x) := aeval_alg_hom_apply (algebra.of_id R A) x p @[simp] lemma coe_aeval_eq_eval (r : R) : (aeval r : polynomial R → R) = eval r := rfl @[simp] lemma aeval_fn_apply {X : Type*} (g : polynomial R) (f : X → R) (x : X) : ((aeval f) g) x = aeval (f x) g := (aeval_alg_hom_apply (pi.alg_hom.apply _ _ _ x) f g).symm @[norm_cast] lemma aeval_subalgebra_coe (g : polynomial R) {A : Type*} [semiring A] [algebra R A] (s : subalgebra R A) (f : s) : (aeval f g : A) = aeval (f : A) g := (aeval_alg_hom_apply s.val f g).symm lemma coeff_zero_eq_aeval_zero (p : polynomial R) : p.coeff 0 = aeval 0 p := by simp [coeff_zero_eq_eval_zero] variables [comm_ring S] {f : R →+* S} lemma is_root_of_eval₂_map_eq_zero (hf : function.injective f) {r : R} : eval₂ f (f r) p = 0 → p.is_root r := begin intro h, apply hf, rw [←eval₂_hom, h, f.map_zero], end lemma is_root_of_aeval_algebra_map_eq_zero [algebra R S] {p : polynomial R} (inj : function.injective (algebra_map R S)) {r : R} (hr : aeval (algebra_map R S r) p = 0) : p.is_root r := is_root_of_eval₂_map_eq_zero inj hr lemma dvd_term_of_dvd_eval_of_dvd_terms {z p : S} {f : polynomial S} (i : ℕ) (dvd_eval : p ∣ f.eval z) (dvd_terms : ∀ (j ≠ i), p ∣ f.coeff j * z ^ j) : p ∣ f.coeff i * z ^ i := begin by_cases hf : f = 0, { simp [hf] }, by_cases hi : i ∈ f.support, { rw [eval, eval₂, sum_def] at dvd_eval, rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase _ _)] at dvd_eval, refine (dvd_add_left _).mp dvd_eval, apply finset.dvd_sum, intros j hj, exact dvd_terms j (finset.ne_of_mem_erase hj) }, { convert dvd_zero p, convert _root_.zero_mul _, exact finsupp.not_mem_support_iff.mp hi } end lemma dvd_term_of_is_root_of_dvd_terms {r p : S} {f : polynomial S} (i : ℕ) (hr : f.is_root r) (h : ∀ (j ≠ i), p ∣ f.coeff j * r ^ j) : p ∣ f.coeff i * r ^ i := dvd_term_of_dvd_eval_of_dvd_terms i (eq.symm hr ▸ dvd_zero p) h lemma aeval_eq_sum_range [algebra R S] {p : polynomial R} (x : S) : aeval x p = ∑ i in finset.range (p.nat_degree + 1), p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range (algebra_map R S) x } lemma aeval_eq_sum_range' [algebra R S] {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : aeval x p = ∑ i in finset.range n, p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range' (algebra_map R S) hn x } end aeval section ring variables [ring R] /-- The evaluation map is not generally multiplicative when the coefficient ring is noncommutative, but nevertheless any polynomial of the form `p * (X - monomial 0 r)` is sent to zero when evaluated at `r`. This is the key step in our proof of the Cayley-Hamilton theorem. -/ lemma eval_mul_X_sub_C {p : polynomial R} (r : R) : (p * (X - C r)).eval r = 0 := begin simp only [eval, eval₂, ring_hom.id_apply], have bound := calc (p * (X - C r)).nat_degree ≤ p.nat_degree + (X - C r).nat_degree : nat_degree_mul_le ... ≤ p.nat_degree + 1 : add_le_add_left nat_degree_X_sub_C_le _ ... < p.nat_degree + 2 : lt_add_one _, rw sum_over_range' _ _ (p.nat_degree + 2) bound, swap, { simp, }, rw sum_range_succ', conv_lhs { congr, apply_congr, skip, rw [coeff_mul_X_sub_C, sub_mul, mul_assoc, ←pow_succ], }, simp [sum_range_sub', coeff_monomial], end theorem not_is_unit_X_sub_C [nontrivial R] {r : R} : ¬ is_unit (X - C r) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by erw [← eval_mul_X_sub_C, hgf, eval_one] end ring lemma aeval_endomorphism {M : Type*} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) (v : M) (p : polynomial R) : aeval f p v = p.sum (λ n b, b • (f ^ n) v) := begin rw [aeval_def, eval₂], exact (finset.sum_hom p.support (λ h : M →ₗ[R] M, h v)).symm end end polynomial
ce20889e39b681f4cee1ebe0e8d00c99705624aa
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/examples/natural.lean
28ead5dc177fd50f3b4c11d7ec040f635b84d37d
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
2,022
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import data.equiv.basic import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism import ..monoid_object open category_theory open tactic universes u v namespace category_theory section open monoidal_category inductive nat_hom (m n : ℕ) : Type | mk : nat_hom @[simp] lemma equality {m n : ℕ} (f : nat_hom m n) : f = nat_hom.mk m n := by cases f; refl @[simp] def nat_id (X : ℕ) : nat_hom X X := nat_hom.mk X X @[simp] def nat_comp (X Y Z : ℕ) (f : nat_hom X Y) (g : nat_hom Y Z) : nat_hom X Z := nat_hom.mk X Z @[simp] def nat_tensor_obj (X Y : ℕ) : ℕ := X + Y @[simp] def nat_tensor_hom (A B C D : ℕ) (f : nat_hom A B) (g : nat_hom C D) : nat_hom (A + C) (B + D) := nat_hom.mk (A + C) (B + D) instance naturals : monoidal_category (nat) := { hom := λ X Y, nat_hom X Y, id := nat_id, comp := nat_comp, id_comp' := by tidy; rw equality f, comp_id' := by tidy; rw equality f, tensor_obj := nat_tensor_obj, tensor_hom := nat_tensor_hom, tensor_unit := nat.zero, left_unitor := λ X, { hom := nat_hom.mk (nat_tensor_obj 0 X) X, inv := nat_hom.mk X (nat_tensor_obj 0 X) }, right_unitor := λ X, { hom := nat_hom.mk (nat_tensor_obj X 0) X, inv := nat_hom.mk X (nat_tensor_obj X 0) }, associator := λ X Y Z, { hom := nat_hom.mk (nat_tensor_obj (nat_tensor_obj X Y) Z) (nat_tensor_obj X (nat_tensor_obj Y Z)), inv := nat_hom.mk (nat_tensor_obj X (nat_tensor_obj Y Z)) (nat_tensor_obj (nat_tensor_obj X Y) Z)} } end instance nat_monoid_object (n : nat) : monoid_object n := { unit := nat_hom.mk 0 n, product := nat_hom.mk (n + n) n } instance nat_comonoid_object (n : nat) : comonoid_object n := { counit := nat_hom.mk n 0, coproduct := nat_hom.mk n (n + n) } instance nat_frobenius_object (n : nat) : frobenius_object n := {} end category_theory
4c10909e341a8f5d7fec8f15374715d918fb24af
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/num.lean
6c73dd7dc3803c4aeed00413ac8dfd4799117fd4
[ "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
46
lean
#check 14 #check 0 #check 3 #check 2 #check 4
84bc23e1961b62f35574384bd1db408fb0ffb4fa
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/is_R_or_C.lean
149808aefc3811407fea3475a078ada7e0c2d482
[ "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,930
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import data.complex.is_R_or_C import analysis.normed_space.operator_norm import analysis.normed_space.pointwise /-! # Normed spaces over R or C This file is about results on normed spaces over the fields `ℝ` and `ℂ`. ## Main definitions None. ## Main theorems * `continuous_linear_map.op_norm_bound_of_ball_bound`: A bound on the norms of values of a linear map in a ball yields a bound on the operator norm. ## Notes This file exists mainly to avoid importing `is_R_or_C` in the main normed space theory files. -/ open metric variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_add_comm_group E] lemma is_R_or_C.norm_coe_norm {z : E} : ‖(‖z‖ : 𝕜)‖ = ‖z‖ := by simp variables [normed_space 𝕜 E] /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to unit length. -/ @[simp] lemma norm_smul_inv_norm {x : E} (hx : x ≠ 0) : ‖(‖x‖⁻¹ : 𝕜) • x‖ = 1 := begin have : ‖x‖ ≠ 0 := by simp [hx], field_simp [norm_smul] end /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to length `r`. -/ lemma norm_smul_inv_norm' {r : ℝ} (r_nonneg : 0 ≤ r) {x : E} (hx : x ≠ 0) : ‖(r * ‖x‖⁻¹ : 𝕜) • x‖ = r := begin have : ‖x‖ ≠ 0 := by simp [hx], field_simp [norm_smul, is_R_or_C.norm_eq_abs, r_nonneg] with is_R_or_C_simps end lemma linear_map.bound_of_sphere_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ sphere (0 : E) r, ‖f z‖ ≤ c) (z : E) : ‖f z‖ ≤ c / r * ‖z‖ := begin by_cases z_zero : z = 0, { rw z_zero, simp only [linear_map.map_zero, norm_zero, mul_zero], }, set z₁ := (r * ‖z‖⁻¹ : 𝕜) • z with hz₁, have norm_f_z₁ : ‖f z₁‖ ≤ c, { apply h, rw mem_sphere_zero_iff_norm, exact norm_smul_inv_norm' r_pos.le z_zero }, have r_ne_zero : (r : 𝕜) ≠ 0 := is_R_or_C.of_real_ne_zero.mpr r_pos.ne', have eq : f z = ‖z‖ / r * (f z₁), { rw [hz₁, linear_map.map_smul, smul_eq_mul], rw [← mul_assoc, ← mul_assoc, div_mul_cancel _ r_ne_zero, mul_inv_cancel, one_mul], simp only [z_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero, ne.def, not_false_iff], }, rw [eq, norm_mul, norm_div, is_R_or_C.norm_coe_norm, is_R_or_C.norm_of_nonneg r_pos.le, div_mul_eq_mul_div, div_mul_eq_mul_div, mul_comm], apply div_le_div _ _ r_pos rfl.ge, { exact mul_nonneg ((norm_nonneg _).trans norm_f_z₁) (norm_nonneg z), }, apply mul_le_mul norm_f_z₁ rfl.le (norm_nonneg z) ((norm_nonneg _).trans norm_f_z₁), end /-- `linear_map.bound_of_ball_bound` is a version of this over arbitrary nontrivially normed fields. It produces a less precise bound so we keep both versions. -/ lemma linear_map.bound_of_ball_bound' {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ‖f z‖ ≤ c) (z : E) : ‖f z‖ ≤ c / r * ‖z‖ := f.bound_of_sphere_bound r_pos c (λ z hz, h z hz.le) z lemma continuous_linear_map.op_norm_bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →L[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ‖f z‖ ≤ c) : ‖f‖ ≤ c / r := begin apply continuous_linear_map.op_norm_le_bound, { apply div_nonneg _ r_pos.le, exact (norm_nonneg _).trans (h 0 (by simp only [norm_zero, mem_closed_ball, dist_zero_left, r_pos.le])), }, apply linear_map.bound_of_ball_bound' r_pos, exact λ z hz, h z hz, end variables (𝕜) include 𝕜 lemma normed_space.sphere_nonempty_is_R_or_C [nontrivial E] {r : ℝ} (hr : 0 ≤ r) : nonempty (sphere (0:E) r) := begin letI : normed_space ℝ E := normed_space.restrict_scalars ℝ 𝕜 E, exact (normed_space.sphere_nonempty.mpr hr).coe_sort, end
0396f5d7ef78fc140a5a329b017e8940294ee704
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/match2.lean
7d9d62d40d89a00e652906006efa027bf226c86c
[ "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
277
lean
inductive imf (f : nat → nat) : nat → Type | mk1 : ∀ (a : nat), imf (f a) | mk2 : imf (f 0 + 1) definition inv_2 (f : nat → nat) : ∀ (b : nat), imf f b → {x : nat \ x > b} →nat | .(f a) (imf.mk1 .f a) x := a | .(f 0 + 1) (imf.mk2 .f) x := subtype.elt_of x
142c8bfdcb40fdc34f40b476878c47d76b2841f0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/check_constants.lean
a424430144d8a43c597ed7b14f89dd1083b0b3bb
[ "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
11,039
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `and run_cmd script_check_id `and.cases_on run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `auto_param run_cmd script_check_id `bin_tree.empty run_cmd script_check_id `bin_tree.leaf run_cmd script_check_id `bin_tree.node run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.mk run_cmd script_check_id `char.ne_of_vne run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `dite run_cmd script_check_id `empty run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `eq_true_intro run_cmd script_check_id `Exists run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `false run_cmd script_check_id `false.rec run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `format run_cmd script_check_id `function run_cmd script_check_id `function.const run_cmd script_check_id `funext run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `has_andthen.andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_coe_t run_cmd script_check_id `has_coe_to_fun run_cmd script_check_id `has_coe_to_sort run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_repr run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_singleton.singleton run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `hole_command run_cmd script_check_id `id run_cmd script_check_id `id_delta run_cmd script_check_id `id_rhs run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.rfl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `interactive.executor run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io run_cmd script_check_id `io_core run_cmd script_check_id `io_rand_nat run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `is_valid_char_range_1 run_cmd script_check_id `is_valid_char_range_2 run_cmd script_check_id `ite run_cmd script_check_id `lean.parser run_cmd script_check_id `lean.parser.pexpr run_cmd script_check_id `lean.parser.reflectable.expr run_cmd script_check_id `lean.parser.tk run_cmd script_check_id `left_comm run_cmd script_check_id `list run_cmd script_check_id `list.cons run_cmd script_check_id `list.nil run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monad_from_pure_bind run_cmd script_check_id `monad_io_environment_impl run_cmd script_check_id `monad_io_file_system_impl run_cmd script_check_id `monad_io_impl run_cmd script_check_id `monad_io_net_system_impl run_cmd script_check_id `monad_io_process_impl run_cmd script_check_id `monad_io_random_impl run_cmd script_check_id `monad_io_terminal_impl run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.add run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `not run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `of_eq_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `out_param run_cmd script_check_id `pprod run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.snd run_cmd script_check_id `prod.mk run_cmd script_check_id `propext run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.snd run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `punit run_cmd script_check_id `punit.cases_on run_cmd script_check_id `punit.star run_cmd script_check_id `quot.lift run_cmd script_check_id `quot.mk run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `repr run_cmd script_check_id `rfl run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `sizeof run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.rec run_cmd script_check_id `subtype.val run_cmd script_check_id `tactic run_cmd script_check_id `tactic.mk_inj_eq run_cmd script_check_id `tactic.triv run_cmd script_check_id `tactic.try run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `to_pexpr run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.star run_cmd script_check_id `user_attribute run_cmd script_check_id `user_attribute.parse_reflect run_cmd script_check_id `vm_monitor run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `well_founded_tactics run_cmd script_check_id `well_founded_tactics.dec_tac run_cmd script_check_id `well_founded_tactics.default run_cmd script_check_id `well_founded_tactics.rel_tac run_cmd script_check_id `widget.term_goal_widget
8696a1300df0ede35c1e8e4f2394dd8e59266074
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/compiler_proj_bug.lean
788bd834fba627c9551b308c40bfd20e642b913b
[ "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
115
lean
structure S := (a : Nat) (h : a > 0) (b : Nat) def f (s : S) := s.b - s.a #eval f {a := 5, b := 30, h := sorry }
1082fd398fb794aa6ede32a37b580481991362cc
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level4.lean
50db6b78bd75d7b301762517e84db7ce060920c9
[ "Apache-2.0" ]
permissive
agusakov/mathematics_in_lean_game
76e455a688a8826b05160c16c0490b9e3d39f071
ad45fd42148f2203b973537adec7e8a48677ba2a
refs/heads/master
1,666,147,402,274
1,592,119,137,000
1,592,119,137,000
272,111,226
0
0
null
null
null
null
UTF-8
Lean
false
false
699
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 4: `rw` with no arguments You can also use identities like `mul_assoc` and `mul_comm` without arguments. In this case, the rewrite tactic tries to match the left-hand side with an expression in the goal, using the first pattern it finds. Try doing this example without providing any arguments at all. -/ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example4 (a b c : ℝ) : a * b * c = b * c * a := begin [maths_in_lean_game] sorry end end calculating -- hide
68f6e36c3459f1685329cc13663a70682a914b16
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/instances/real.lean
66d7a2f451492954901e93d3859a8b827253301f
[ "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
14,541
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, (set.finite_lt_nat _).image _, _⟩, rintro x ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : is_compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end
8a68be200bc9fd62de2481b2b435feef2eb10a64
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/set_theory/cardinal_ordinal.lean
35f7ec01301b60d7048251a109c9c54fec7a7d08
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
36,022
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 -/ import set_theory.ordinal_arithmetic import tactic.omega /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions and results * The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. It is an order isomorphism between ordinals and cardinals. * The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. * `mul_eq_max` and `add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making simp able to prove inequalities about numeral cardinals. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, nonpos_iff_eq_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans h) c), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO' r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ canonically_ordered_semiring.mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans hb) a) (by simpa only [one_mul] using canonically_ordered_semiring.mul_le_mul_right' (one_lt_omega.le.trans ha) b) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (mul_lt_omega h h) hc) (λ h, by rw mul_eq_self h; exact max_lt h1 h2) lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) : a * b ≤ max a b := begin convert canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self], refine le_trans h (le_max_left a b) end lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b := begin apply le_antisymm, apply mul_le_max_of_omega_le_left h, cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb], have : b ≤ a, exact le_trans (le_of_lt hb) h, rw [max_eq_left this], convert canonically_ordered_semiring.mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one], end lemma mul_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert canonically_ordered_semiring.mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _, rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos }, left, use ha, { rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) }, { rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }}, right, by_cases h2a : a = 0, { right, exact h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h }, left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw [← not_lt], intro h2b, apply ne_of_gt _ h, rw [gt], conv_lhs { rw [← mul_one n] }, rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] }, all_goals {simp}} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using canonically_ordered_semiring.mul_le_mul_right' ((nat_lt_omega 2).le.trans h) c) (self_le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (self_le_add_right _ _) (self_le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (add_lt_omega h h) hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply self_le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≤ a ∨ b = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h, exact lt_of_lt_of_le hb (self_le_add_left b a) }, right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [← add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a := have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha, add_eq_left ha this protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := begin cases le_or_lt omega b with hb hb, { have : a < b := lt_of_lt_of_le ha hb, rw [add_eq_right hb (le_of_lt this), eq_comm] at h, rw [eq_of_add_eq_of_omega_le h this hb] }, { have hc : c < omega, { rw [← not_le], intro hc, apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (self_le_add_left _ a)), rw [← h], apply add_lt_omega ha hb }, rw [lt_omega] at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (λ n ih, trans_rel_left _ (by { rw [nat.cast_succ, power_add, power_one]; exact canonically_ordered_semiring.mul_le_mul_right' ih _ }) (mul_eq_self H1))) H1) lemma power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = 2 ^ c := begin apply le_antisymm, { apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] }, { convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm } end lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : omega ≤ c) : c ^ (n : cardinal.{u}) ≤ c := pow_le h (nat_lt_omega n) lemma powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c := begin apply le_antisymm, { rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt one_lt_omega, rw [power_one] end lemma powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega := begin cases le_or_gt omega c, { rw [powerlt_omega h], apply le_max_left }, rw [powerlt_le], intros c' hc', refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _) end /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α := eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list α) = sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n ... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound ⟨@sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩ ... = omega * mk α : sum_const _ _ ... = max (omega) (mk α) : mul_eq_max (le_refl _) H1 ... = mk α : max_eq_right H1 theorem mk_finset_eq_mk {α : Type u} (h : omega ≤ mk α) : mk (finset α) = mk α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc mk (finset α) ≤ mk (list α) : mk_le_of_surjective list.to_finset_surjective ... = mk α : mk_list_eq_mk h lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) : mk {t : set α // mk t ≤ c} ≤ mk α ^ c := begin refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : mk {t : set α // mk t ≤ c} ≤ max (mk α) omega ^ c := begin transitivity mk {t : set (ulift.{u} nat ⊕ α) // mk t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs }, refine le_trans (mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (self_le_add_right omega (mk α))) _, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : mk {t : set α // t ⊆ s ∧ mk t ≤ c} ≤ max (mk s) omega ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : omega ≤ #α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s } lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : omega ≤ #α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h } lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : omega ≤ #α) (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β} (hα : #α < omega) (h1 : lift.{u (max v w)} (#α) = lift.{v (max u w)} (#β)) (h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) : lift.{u (max v w)} (#(sᶜ : set α)) = lift.{v (max u w)} (#(tᶜ : set β)) := begin have hα' := hα, have h1' := h1, rw [← mk_sum_compl s, ← mk_sum_compl t] at h1, rw [← mk_sum_compl s, add_lt_omega_iff] at hα, lift #s to ℕ using hα.1 with n hn, lift #(sᶜ : set α) to ℕ using hα.2 with m hm, have : #(tᶜ : set β) < omega, { refine lt_of_le_of_lt (mk_subtype_le _) _, rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' }, lift #(tᶜ : set β) to ℕ using this with k hk, simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2, simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1 end lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β} (hα : #α < omega) (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < omega) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite hα rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.set.range f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β) (hs : #α < omega) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin cases (le_or_lt omega (#α)) with hα hα, { apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2, cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3, { constructor, exact g2.trans (g.trans g3.symm) }, { rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp }, rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 }, { exact extend_function_finite f hα h } end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ @[simp] lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := lt_of_lt_of_le zero_lt_one (self_le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h), λ h, le_trans (one_le_iff_pos.mpr h) (self_le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : omega ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < omega ↔ c < omega := by simp [bit0, add_lt_omega_iff] @[simp] theorem omega_le_bit0 {c : cardinal} : omega ≤ bit0 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ omega ≤ c := begin by_cases h : omega ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] }, { simp only [h, iff_false], apply ne_of_gt, rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], omega } end @[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < omega ↔ c < omega := by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega] @[simp] theorem omega_le_bit1 {c : cardinal} : omega ≤ bit1 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := begin split, { assume h, apply bit0_le_bit1.1 (le_trans (self_le_add_right (bit0 a) 1) h) }, { assume h, calc a + a + 1 ≤ a + b + 1 : add_le_add_right (add_le_add_left h a) 1 ... ≤ b + b + 1 : add_le_add_right (add_le_add_right h b) 1 } end @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ omega ≤ a)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2, le_of_not_ge I1] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit1 a ≤ b := le_trans (le_of_lt (bit1_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha], } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_trans ha (le_of_lt h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < omega)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2, not_lt.mpr ha] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_le_one : (1 : cardinal) ≤ 1 := le_refl _ end bit end cardinal
15ecceab523b8681c3db96eb759ebb85e28a2e0b
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/finsupp/order.lean
0151903062e780c2ebfa563146be7cecb392184a
[ "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
7,363
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Aaron Anderson -/ import data.finsupp.basic /-! # Pointwise order on finitely supported functions This file lifts order structures on `α` to `ι →₀ α`. ## Main declarations * `finsupp.order_embedding_to_fun`: The order embedding from finitely supported functions to functions. * `finsupp.order_iso_multiset`: The order isomorphism between `ℕ`-valued finitely supported functions and multisets. -/ noncomputable theory open_locale classical big_operators open finset variables {ι α : Type*} namespace finsupp /-! ### Order structures -/ section has_zero variables [has_zero α] section has_le variables [has_le α] instance : has_le (ι →₀ α) := ⟨λ f g, ∀ i, f i ≤ g i⟩ lemma le_def {f g : ι →₀ α} : f ≤ g ↔ ∀ i, f i ≤ g i := iff.rfl /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun : (ι →₀ α) ↪o (ι → α) := { to_fun := λ f, f, inj' := λ f g h, finsupp.ext $ λ i, by { dsimp at h, rw h }, map_rel_iff' := λ a b, (@le_def _ _ _ _ a b).symm } @[simp] lemma order_embedding_to_fun_apply {f : ι →₀ α} {i : ι} : order_embedding_to_fun f i = f i := rfl end has_le section preorder variables [preorder α] instance : preorder (ι →₀ α) := { le_refl := λ f i, le_rfl, le_trans := λ f g h hfg hgh i, (hfg i).trans (hgh i), .. finsupp.has_le } lemma monotone_to_fun : monotone (finsupp.to_fun : (ι →₀ α) → (ι → α)) := λ f g h a, le_def.1 h a end preorder instance [partial_order α] : partial_order (ι →₀ α) := { le_antisymm := λ f g hfg hgf, ext $ λ i, (hfg i).antisymm (hgf i), .. finsupp.preorder } instance [semilattice_inf α] : semilattice_inf (ι →₀ α) := { inf := zip_with (⊓) inf_idem, inf_le_left := λ f g i, inf_le_left, inf_le_right := λ f g i, inf_le_right, le_inf := λ f g i h1 h2 s, le_inf (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma inf_apply [semilattice_inf α] {i : ι} {f g : ι →₀ α} : (f ⊓ g) i = f i ⊓ g i := rfl instance [semilattice_sup α] : semilattice_sup (ι →₀ α) := { sup := zip_with (⊔) sup_idem, le_sup_left := λ f g i, le_sup_left, le_sup_right := λ f g i, le_sup_right, sup_le := λ f g h hf hg i, sup_le (hf i) (hg i), ..finsupp.partial_order } @[simp] lemma sup_apply [semilattice_sup α] {i : ι} {f g : ι →₀ α} : (f ⊔ g) i = f i ⊔ g i := rfl instance lattice [lattice α] : lattice (ι →₀ α) := { .. finsupp.semilattice_inf, .. finsupp.semilattice_sup } end has_zero /-! ### Algebraic order structures -/ instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (ι →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (ι →₀ α) := { le_of_add_le_add_left := λ f g i h s, le_of_add_le_add_left (h s), add_left_cancel := λ f g i h, ext $ λ s, add_left_cancel (ext_iff.1 h s), .. finsupp.ordered_add_comm_monoid } instance [ordered_add_comm_monoid α] [contravariant_class α α (+) (≤)] : contravariant_class (ι →₀ α) (ι →₀ α) (+) (≤) := ⟨λ f g h H x, le_of_add_le_add_left $ H x⟩ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] instance : order_bot (ι →₀ α) := { bot := 0, bot_le := by simp only [le_def, coe_zero, pi.zero_apply, implies_true_iff, zero_le]} protected lemma bot_eq_zero : (⊥ : ι →₀ α) = 0 := rfl @[simp] lemma add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] lemma le_iff' (f g : ι →₀ α) {s : finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ lemma le_iff (f g : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' f g $ subset.refl _ instance decidable_le [decidable_rel (@has_le.le α _)] : decidable_rel (@has_le.le (ι →₀ α) _) := λ f g, decidable_of_iff _ (le_iff f g).symm @[simp] lemma single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i := (le_iff' _ _ support_single_subset).trans $ by simp variables [has_sub α] [has_ordered_sub α] {f g : ι →₀ α} {i : ι} {a b : α} /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : has_sub (ι →₀ α) := ⟨zip_with (λ m n, m - n) (tsub_self 0)⟩ instance : has_ordered_sub (ι →₀ α) := ⟨λ n m k, forall_congr $ λ x, tsub_le_iff_right⟩ instance : canonically_ordered_add_monoid (ι →₀ α) := { exists_add_of_le := λ f g h, ⟨g - f, ext $ λ x, (add_tsub_cancel_of_le $ h x).symm⟩, le_self_add := λ f g x, le_self_add, .. finsupp.order_bot, .. finsupp.ordered_add_comm_monoid } @[simp] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl lemma tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a := rfl @[simp] lemma single_tsub : single i (a - b) = single i a - single i b := begin ext j, obtain rfl | h := eq_or_ne i j, { rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] } end lemma support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.support := by simp only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, ne.def, coe_tsub, pi.sub_apply, not_imp_not, zero_le, implies_true_iff] {contextual := tt} lemma subset_support_tsub {f1 f2 : ι →₀ α} : f1.support \ f2.support ⊆ (f1 - f2).support := by simp [subset_iff] {contextual := tt} end canonically_ordered_add_monoid section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [decidable_eq ι] {f g : ι →₀ α} @[simp] lemma support_inf : (f ⊓ g).support = f.support ∩ g.support := begin ext, simp only [inf_apply, mem_support_iff, ne.def, finset.mem_union, finset.mem_filter, finset.mem_inter], simp only [inf_eq_min, ←nonpos_iff_eq_zero, min_le_iff, not_or_distrib], end @[simp] lemma support_sup : (f ⊔ g).support = f.support ∪ g.support := begin ext, simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ←bot_eq_zero], rw [_root_.sup_eq_bot_iff, not_and_distrib], end lemma disjoint_iff : disjoint f g ↔ disjoint f.support g.support := begin rw [disjoint_iff, disjoint_iff, finsupp.bot_eq_zero, ← finsupp.support_eq_empty, finsupp.support_inf], refl, end end canonically_linear_ordered_add_monoid /-! ### Some lemmas about `ℕ` -/ section nat lemma sub_single_one_add {a : ι} {u u' : ι →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := tsub_add_eq_add_tsub $ single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h lemma add_sub_single_one {a : ι} {u u' : ι →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := (add_tsub_assoc_of_le (single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h) _).symm end nat end finsupp
658d9b68c968a277828ea0d22f9ef150e1eac532
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/analysis/calculus/fderiv.lean
27c3a425f386feceeb64061532860ff23625830f
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
72,797
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.asymptotics analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory set_option class.instance_max_depth 90 section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : {n | x + d n ∈ s} ∈ l) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 ((norm_eq_zero (x' - x)).1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter lattice.inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, apply mem_sets_of_superset (ne_mem_of_tendsto_norm_at_top hc (0:𝕜)) _, assume y hy, rw [mem_preimage], convert mem_of_nhds hU, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := by { ext, rw hxs.eq h h.differentiable_within_at.has_fderiv_within_at } /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ (is_open_univ.unique_diff_within_at (mem_univ _)), rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section congr /-! ### congr properties of the derivative -/ theorem has_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := by { rw (ext h₁), exact is_o_congr (by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx]) (univ_mem_sets' $ λ _, rfl) } lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := begin apply (has_fderiv_at_filter_congr_of_mem_sets hx hL _).2 h, exact λx, rfl end lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : {y | f₁ y = f y} ∈ 𝓝 x) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x) (hL : {y | f₁ y = f y} ∈ 𝓝 x) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f s x ∨ differentiable_within_at 𝕜 f₁ s x, { cases h, { apply has_fderiv_within_at.fderiv_within _ hs, exact has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at hL hx }, { symmetry, apply has_fderiv_within_at.fderiv_within _ hs, apply has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at _ hx.symm, convert hL, ext y, exact eq_comm } }, { push_neg at h, have A : fderiv_within 𝕜 f s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, have A₁ : fderiv_within 𝕜 f₁ s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, rw [A, A₁] } end lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : {y | f₁ y = f y} ∈ 𝓝 x) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id : E →L[𝕜] E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id : E →L[𝕜] E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] E) x := has_fderiv_at_filter_id _ _ lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_within_const (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const _ end lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := begin have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0, { ext, have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl, simp, simp [this] }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := begin have : (λ (x' : E), e x' - e x - e (x' - x)) = λx', 0, by { ext, simp }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on end continuous_linear_map section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_neg, smul_add] theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section neg /-! ### Derivative of the negative of a function -/ theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (h.const_smul (-1:𝕜)).congr (by simp) (by simp) theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds lattice.inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at end continuous section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := begin have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)), { ext x, delta is_bounded_bilinear_map.deriv, change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2)) = b (x.1 - p.1, x.2 - p.2), have : b x = b (x.1, x.2), by { cases x, refl }, rw this, have : b p = b (p.1, p.2), by { cases p, refl }, rw this, simp only [h.map_sub_left, h.map_sub_right], abel }, rw [has_fderiv_at, has_fderiv_at_filter, this], rcases h.bound with ⟨C, Cpos, hC⟩, have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2)) (λx, ∥x - p∥ * ∥x - p∥) (𝓝 p) := ⟨C, filter.univ_mem_sets' (λx, begin simp only [mem_set_of_eq, norm_mul, norm_norm], calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _ ... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg, le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg] ... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩, have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥) (λx, 1 * ∥x - p∥) (𝓝 p), { refine asymptotics.is_o.mul_is_O (asymptotics.is_o.norm_left _) (asymptotics.is_O_refl _ _), apply (asymptotics.is_o_one_iff ℝ).2, rw [← sub_self p], exact tendsto_id.sub tendsto_const_nhds }, simp only [one_mul, asymptotics.is_o_norm_right] at B, exact A.trans_is_o B end lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {f₂ : E → G} {f₂' : E →L[𝕜] G} lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := begin have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) = (λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl, rw [has_fderiv_at_filter, this], rw [asymptotics.is_o_prod_left], exact ⟨hf₁, hf₂⟩ end lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end cartesian_product section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = continuous_linear_map.comp (fderiv_within 𝕜 g t (f x)) (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = continuous_linear_map.comp (fderiv 𝕜 g (f x)) (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) end composition section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := begin convert hc.smul (has_fderiv_within_at_const f x s), -- Help Lean find an instance letI : distrib_mul_action 𝕜 (E →L[𝕜] F) := continuous_linear_map.module.to_distrib_mul_action, rw [smul_zero, zero_add] end theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.smul_const f end lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ set_option class.instance_max_depth 120 variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := begin have := hc.mul (has_fderiv_within_at_const d x s), letI : distrib_mul_action 𝕜 (E →L[𝕜] 𝕜) := continuous_linear_map.module.to_distrib_mul_action, rwa [smul_zero, zero_add] at this end theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.image_tangent_cone_subset {x : E} (h : has_fderiv_within_at f f' s x) : f' '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (f '' s) (f x) := begin rw image_subset_iff, rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have A : ∀v ∈ tangent_cone_at 𝕜 s x, f' v ∈ tangent_cone_at 𝕜 (f '' s) (f x), { assume v hv, have := h.image_tangent_cone_subset, rw image_subset_iff at this, exact this hv }, have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (A w hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
585a55fcf137e00a95ba270d1ee2367f3814be3f
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/bases.lean
486c8b7415f61d843d1ec73f893692f805324cbc
[ "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
41,156
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable import data.pprod /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antitone_basis` : proves a filter is countably generated if and only if it admits a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter open_locale filter classical section sort variables {α β γ : Type*} {ι ι' : Sort*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := {t | ∃ i, p i ∧ s i = t}, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, ⟨i, hi, rfl⟩⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, ⟨k, hk, rfl⟩, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], simp only [ge_iff_le, le_principal_iff, mem_principal, subtype.coe_mk], exact subset_inter_iff.mp W_sub }, ext U, simp [mem_filter_iff, mem_infi_of_directed this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' := begin ext t, rw [hl.mem_iff, hl'.mem_iff] end lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem in ⟨i, pi⟩ protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι := nonempty_of_exists h.ex_mem protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl protected lemma _root_.filter_basis.has_basis {α : Type*} (B : filter_basis α) : has_basis (B.filter) (λ s : set α, s ∈ B) id := ⟨λ t, B.mem_filter_iff⟩ lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_of_superset (h' i' hi') ht⟩⟩, rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩, rcases h i hi with ⟨i', hi', hs's⟩, exact ⟨i', hi', subset.trans hs's ht⟩ end lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩ lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.has_basis p t := hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_mem_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_mem_subset_iff.symm⟩ lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := begin simp only [has_basis_iff, exists_prop, id, and_assoc], exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_of_superset hl hts⟩⟩) end lemma has_basis.comp_of_surjective (h : l.has_basis p s) {g : ι' → ι} (hg : function.surjective g) : l.has_basis (p ∘ g) (s ∘ g) := ⟨λ t, h.mem_iff.trans hg.exists⟩ lemma has_basis.comp_equiv (h : l.has_basis p s) (e : ι' ≃ ι) : l.has_basis (p ∘ e) (s ∘ e) := h.comp_of_surjective e.surjective /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, split, { simp only [mem_inf_iff, exists_prop, hl.mem_iff, hl'.mem_iff], rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩, use [⟨i, i'⟩, ⟨hi, hi'⟩, inter_subset_inter ht ht'] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H } end⟩ lemma has_basis.inf {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := (hl.inf' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_infi {ι : Sort*} {ι' : ι → Type*} {l : ι → filter α} {p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) : (⨅ i, l i).has_basis (λ If : set ι × Π i, ι' i, finite If.1 ∧ ∀ i ∈ If.1, p i (If.2 i)) (λ If : set ι × Π i, ι' i, ⋂ i ∈ If.1, s i (If.2 i)) := ⟨begin intro t, split, { simp only [mem_infi', (hl _).mem_iff], rintros ⟨I, hI, V, hV, -, hVt, -⟩, choose u hu using hV, refine ⟨⟨I, u⟩, ⟨hI, λ i _, (hu i).1⟩, _⟩, rw hVt, exact Inter_mono (λ i, Inter_mono $ λ hi, (hu i).2) }, { rintros ⟨⟨I, f⟩, ⟨hI₁, hI₂⟩, hsub⟩, refine mem_of_superset _ hsub, exact (bInter_mem hI₁).mpr (λ i hi, mem_infi_of_mem i $ (hl i).mem_of_mem $ hI₂ _ hi) } end⟩ lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis_pure (x : α) : (pure x : filter α).has_basis (λ i : unit, true) (λ i, {x}) := by simp only [← principal_singleton, has_basis_principal] lemma has_basis.sup' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup, hl.mem_iff, hl'.mem_iff, pprod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.sup {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := (hl.sup' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_supr {ι : Sort*} {ι' : ι → Type*} {l : ι → filter α} {p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) : (⨆ i, l i).has_basis (λ f : Π i, ι' i, ∀ i, p i (f i)) (λ f : Π i, ι' i, ⋃ i, s i (f i)) := has_basis_iff.mpr $ λ t, by simp only [has_basis_iff, (hl _).mem_iff, classical.skolem, forall_and_distrib, Union_subset_iff, mem_supr] lemma has_basis.sup_principal (hl : l.has_basis p s) (t : set α) : (l ⊔ 𝓟 t).has_basis p (λ i, s i ∪ t) := ⟨λ u, by simp only [(hl.sup' (has_basis_principal t)).mem_iff, pprod.exists, exists_prop, and_true, unique.exists_iff]⟩ lemma has_basis.sup_pure (hl : l.has_basis p s) (x : α) : (l ⊔ pure x).has_basis p (λ i, s i ∪ {x}) := by simp only [← principal_singleton, hl.sup_principal] lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf' hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma has_basis.disjoint_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : disjoint l l' ↔ ∃ i (hi : p i) i' (hi' : p' i'), disjoint (s i) (s' i') := not_iff_not.mp $ by simp only [disjoint_iff, ← ne.def, ← ne_bot_iff, hl.inf_basis_ne_bot_iff hl', not_exists, bot_eq_empty, ne_empty_iff_nonempty, inf_eq_inter] lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff), exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_of_superset ht hts⟩, end lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm @[simp] lemma disjoint_principal_right {f : filter α} {s : set α} : disjoint f (𝓟 s) ↔ sᶜ ∈ f := by rw [mem_iff_inf_principal_compl, compl_compl, disjoint_iff] @[simp] lemma disjoint_principal_left {f : filter α} {s : set α} : disjoint (𝓟 s) f ↔ sᶜ ∈ f := by rw [disjoint.comm, disjoint_principal_right] @[simp] lemma disjoint_principal_principal {s t : set α} : disjoint (𝓟 s) (𝓟 t) ↔ disjoint s t := by simp [disjoint_iff_subset_compl_left] alias disjoint_principal_principal ↔ _ disjoint.filter_principal @[simp] lemma disjoint_pure_pure {x y : α} : disjoint (pure x : filter α) (pure y) ↔ x ≠ y := by simp only [← principal_singleton, disjoint_principal_principal, disjoint_singleton] lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall₂_congr $ λ _ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi_of_directed (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite {ι : Type*} (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi_of_directed _ ne).trans $ by simp only [mem_principal], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' {ι : Type*} {p : ι → Prop} {s : ι → set α} (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, s i ×ˢ s i) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, t ×ˢ t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i (hi : p i), s i := begin ext x, suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i, by simpa only [mem_Inter, mem_set_of_eq, mem_sInter], simp_rw h.mem_iff, split, { intros h i hi, exact h (s i) ⟨i, hi, subset.refl _⟩ }, { rintros h _ ⟨i, hi, sub⟩, exact sub (h i hi) }, end variables {ι'' : Type*} [preorder ι''] (l) (s'' : ι'' → set α) /-- `is_antitone_basis s` means the image of `s` is a filter basis such that `s` is decreasing. -/ @[protect_proj] structure is_antitone_basis extends is_basis (λ _, true) s'' : Prop := (antitone : antitone s'') /-- We say that a filter `l` has an antitone basis `s : ι → set α`, if `t ∈ l` if and only if `t` includes `s i` for some `i`, and `s` is decreasing. -/ @[protect_proj] structure has_antitone_basis (l : filter α) (s : ι'' → set α) extends has_basis l (λ _, true) s : Prop := (antitone : antitone s) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simpa only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod'' (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : pprod ι ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := (hla.comap prod.fst).inf' (hlb.comap prod.snd) lemma has_basis.prod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop} {sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, sa i ×ˢ sb i) := begin simp only [has_basis_iff, (hla.prod hlb).mem_iff], refine λ t, ⟨_, _⟩, { rintros ⟨⟨i, j⟩, ⟨hi, hj⟩, hsub : sa i ×ˢ sb j ⊆ t⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, exact ⟨k, hk, (set.prod_mono ki kj).trans hsub⟩ }, { rintro ⟨i, hi, h⟩, exact ⟨⟨i, i⟩, ⟨hi, hi⟩, h⟩ }, end lemma has_antitone_basis.prod {f : filter α} {g : filter β} {s : ℕ → set α} {t : ℕ → set β} (hf : has_antitone_basis f s) (hg : has_antitone_basis g t) : has_antitone_basis (f ×ᶠ g) (λ n, s n ×ˢ t n) := begin have h : has_basis (f ×ᶠ g) _ _ := has_basis.prod' hf.to_has_basis hg.to_has_basis _, swap, { intros i j, simp only [true_and, forall_true_left], exact ⟨max i j, hf.antitone (le_max_left _ _), hg.antitone (le_max_right _ _)⟩, }, refine ⟨h, λ n m hn_le_m, set.prod_mono _ _⟩, exacts [hf.antitone hn_le_m, hg.antitone hn_le_m] end lemma has_basis.coprod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop} {sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la.coprod lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, prod.fst ⁻¹' sa i.1 ∪ prod.snd ⁻¹' sb i.2) := (hla.comap prod.fst).sup (hlb.comap prod.snd) end two_types open equiv lemma prod_assoc (f : filter α) (g : filter β) (h : filter γ) : map (prod_assoc α β γ) ((f ×ᶠ g) ×ᶠ h) = f ×ᶠ (g ×ᶠ h) := begin apply ((((basis_sets f).prod $ basis_sets g).prod $ basis_sets h).map _).eq_of_same_basis, simpa only [prod_assoc_image, function.comp, and_assoc] using ((basis_sets f).prod $ (basis_sets g).prod $ basis_sets h).comp_equiv (prod_assoc _ _ _) end end filter end sort namespace filter variables {α β γ ι ι' : Type*} /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ class is_countably_generated (f : filter α) : Prop := (out [] : ∃ s : set (set α), countable s ∧ f = generate s) /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default : filter_basis ℕ) }⟩ lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩⟩ lemma antitone_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, antitone t ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, exact le_rfl }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_rfl }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ section is_countably_generated protected lemma has_antitone_basis.mem [preorder ι] {l : filter α} {s : ι → set α} (hs : l.has_antitone_basis s) (i : ι) : s i ∈ l := hs.to_has_basis.mem_of_mem trivial /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma has_basis.exists_antitone_subbasis {f : filter α} [h : f.is_countably_generated] {p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antitone_basis (λ i, s (x i)) := begin obtain ⟨x', hx'⟩ : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i), { unfreezingI { rcases h with ⟨s, hsc, rfl⟩ }, rw generate_eq_binfi, exact countable_binfi_principal_eq_seq_infi hsc }, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem (this $ n + 1) (hs.mem_of_mem xn.coe_prop))), have x_mono : antitone (λ i, s (x i)), { refine antitone_nat_of_succ_le (λ i, _), exact (hs.set_index_subset _).trans (inter_subset_right _ _) }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antitone_basis (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), x_mono⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by an antitone sequence of sets. -/ lemma exists_antitone_basis (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, f.has_antitone_basis x := let ⟨x, hxf, hx⟩ := f.basis_sets.exists_antitone_subbasis in ⟨x, hx⟩ lemma exists_antitone_seq (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, antitone x ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := f.exists_antitone_basis in ⟨x, hx.antitone, λ s, by simp [hx.to_has_basis.mem_iff]⟩ instance inf.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊓ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end instance comap.is_countably_generated (l : filter β) [l.is_countably_generated] (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hxl⟩ := l.exists_antitone_basis in has_countable_basis.is_countably_generated ⟨hxl.to_has_basis.comap _, countable_encodable _⟩ instance sup.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊔ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.sup ht.to_has_basis, set.countable_encodable _⟩ end end is_countably_generated @[instance] lemma is_countably_generated_seq [encodable β] (x : β → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin use [range x, countable_range x], rw [generate_eq_binfi, infi_range] end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antitone_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antitone_basis x := begin split, { introI h, exact f.exists_antitone_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end @[instance] lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := is_countably_generated_of_seq ⟨λ _, s, infi_const.symm⟩ @[instance] lemma is_countably_generated_pure (a : α) : is_countably_generated (pure a) := by { rw ← principal_singleton, exact is_countably_generated_principal _, } @[instance] lemma is_countably_generated_bot : is_countably_generated (⊥ : filter α) := @principal_empty α ▸ is_countably_generated_principal _ @[instance] lemma is_countably_generated_top : is_countably_generated (⊤ : filter α) := @principal_univ α ▸ is_countably_generated_principal _ instance is_countably_generated.prod {f : filter α} {g : filter β} [hf : f.is_countably_generated] [hg : g.is_countably_generated] : is_countably_generated (f ×ᶠ g) := begin simp_rw is_countably_generated_iff_exists_antitone_basis at hf hg ⊢, rcases hf with ⟨s, hs⟩, rcases hg with ⟨t, ht⟩, refine ⟨_, hs.prod ht⟩, end end filter
3dba25058f8dc89646522ac80f9e7d22bfe34f33
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/function.hlean
6363ff8ac2a33a1dba9338cef4fb371b272ccb8e
[ "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
11,390
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about embeddings and surjections -/ import hit.trunc types.equiv cubical.square open equiv sigma sigma.ops eq trunc is_trunc pi is_equiv fiber prod variables {A B C : Type} (f : A → B) {b : B} /- the image of a map is the (-1)-truncated fiber -/ definition image' [constructor] (f : A → B) (b : B) : Type := ∥ fiber f b ∥ definition is_prop_image' [instance] (f : A → B) (b : B) : is_prop (image' f b) := !is_trunc_trunc definition image [constructor] (f : A → B) (b : B) : Prop := Prop.mk (image' f b) _ definition image.mk [constructor] {f : A → B} {b : B} (a : A) (p : f a = b) : image f b := tr (fiber.mk a p) protected definition image.rec [unfold 8] [recursor 8] {f : A → B} {b : B} {P : image' f b → Type} [H : Πv, is_prop (P v)] (H : Π(a : A) (p : f a = b), P (image.mk a p)) (v : image' f b) : P v := begin unfold [image'] at *, induction v with v, induction v with a p, exact H a p end definition is_embedding [class] (f : A → B) := Π(a a' : A), is_equiv (ap f : a = a' → f a = f a') definition is_surjective [class] (f : A → B) := Π(b : B), image f b definition is_split_surjective [class] (f : A → B) := Π(b : B), fiber f b structure is_retraction [class] (f : A → B) := (sect : B → A) (right_inverse : Π(b : B), f (sect b) = b) structure is_section [class] (f : A → B) := (retr : B → A) (left_inverse : Π(a : A), retr (f a) = a) definition is_weakly_constant [class] (f : A → B) := Π(a a' : A), f a = f a' structure is_constant [class] (f : A → B) := (pt : B) (eq : Π(a : A), f a = pt) structure is_conditionally_constant [class] (f : A → B) := (g : ∥A∥ → B) (eq : Π(a : A), f a = g (tr a)) namespace function abbreviation sect [unfold 4] := @is_retraction.sect abbreviation right_inverse [unfold 4] := @is_retraction.right_inverse abbreviation retr [unfold 4] := @is_section.retr abbreviation left_inverse [unfold 4] := @is_section.left_inverse definition is_equiv_ap_of_embedding [instance] [H : is_embedding f] (a a' : A) : is_equiv (ap f : a = a' → f a = f a') := H a a' definition ap_inv_idp {a : A} {H : is_equiv (ap f : a = a → f a = f a)} : (ap f)⁻¹ᶠ idp = idp :> a = a := !left_inv variable {f} definition is_injective_of_is_embedding [reducible] [H : is_embedding f] {a a' : A} : f a = f a' → a = a' := (ap f)⁻¹ definition is_embedding_of_is_injective [HA : is_set A] [HB : is_set B] (H : Π(a a' : A), f a = f a' → a = a') : is_embedding f := begin intro a a', fapply adjointify, {exact (H a a')}, {intro p, apply is_set.elim}, {intro p, apply is_set.elim} end variable (f) definition is_prop_is_embedding [instance] : is_prop (is_embedding f) := by unfold is_embedding; exact _ definition is_embedding_equiv_is_injective [HA : is_set A] [HB : is_set B] : is_embedding f ≃ (Π(a a' : A), f a = f a' → a = a') := begin fapply equiv.MK, { apply @is_injective_of_is_embedding}, { apply is_embedding_of_is_injective}, { intro H, apply is_prop.elim}, { intro H, apply is_prop.elim, } end definition is_prop_fiber_of_is_embedding [H : is_embedding f] (b : B) : is_prop (fiber f b) := begin apply is_prop.mk, intro v w, induction v with a p, induction w with a' q, induction q, fapply fiber_eq, { esimp, apply is_injective_of_is_embedding p}, { esimp [is_injective_of_is_embedding], symmetry, apply right_inv} end definition is_prop_fun_of_is_embedding [H : is_embedding f] : is_trunc_fun -1 f := is_prop_fiber_of_is_embedding f definition is_embedding_of_is_prop_fun [constructor] [H : is_trunc_fun -1 f] : is_embedding f := begin intro a a', fapply adjointify, { intro p, exact ap point (@is_prop.elim (fiber f (f a')) _ (fiber.mk a p) (fiber.mk a' idp))}, { intro p, rewrite [-ap_compose], esimp, apply ap_con_eq (@point_eq _ _ f (f a'))}, { intro p, induction p, apply ap (ap point), apply is_prop_elim_self} end variable {f} definition is_surjective_rec_on {P : Type} (H : is_surjective f) (b : B) [Pt : is_prop P] (IH : fiber f b → P) : P := trunc.rec_on (H b) IH variable (f) definition is_surjective_of_is_split_surjective [instance] [H : is_split_surjective f] : is_surjective f := λb, tr (H b) definition is_prop_is_surjective [instance] : is_prop (is_surjective f) := begin unfold is_surjective, exact _ end definition is_surjective_cancel_right {A B C : Type} (g : B → C) (f : A → B) [H : is_surjective (g ∘ f)] : is_surjective g := begin intro c, induction H c with a p, exact tr (fiber.mk (f a) p) end definition is_weakly_constant_ap [instance] [H : is_weakly_constant f] (a a' : A) : is_weakly_constant (ap f : a = a' → f a = f a') := take p q : a = a', have Π{b c : A} {r : b = c}, (H a b)⁻¹ ⬝ H a c = ap f r, from (λb c r, eq.rec_on r !con.left_inv), this⁻¹ ⬝ this definition is_constant_ap [unfold 4] [instance] [H : is_constant f] (a a' : A) : is_constant (ap f : a = a' → f a = f a') := begin induction H with b q, fapply is_constant.mk, { exact q a ⬝ (q a')⁻¹}, { intro p, induction p, exact !con.right_inv⁻¹} end definition is_contr_is_retraction [instance] [H : is_equiv f] : is_contr (is_retraction f) := begin have H2 : (Σ(g : B → A), Πb, f (g b) = b) ≃ is_retraction f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, apply is_equiv.is_contr_right_inverse end definition is_contr_is_section [instance] [H : is_equiv f] : is_contr (is_section f) := begin have H2 : (Σ(g : B → A), Πa, g (f a) = a) ≃ is_section f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, fapply is_trunc_equiv_closed, {apply sigma_equiv_sigma_right, intro g, apply eq_equiv_homotopy}, fapply is_trunc_equiv_closed, {apply fiber.sigma_char}, fapply is_contr_fiber_of_is_equiv, exact to_is_equiv (arrow_equiv_arrow_left_rev A (equiv.mk f H)), end definition is_embedding_of_is_equiv [instance] [H : is_equiv f] : is_embedding f := λa a', _ definition is_equiv_of_is_surjective_of_is_embedding [H : is_embedding f] [H' : is_surjective f] : is_equiv f := @is_equiv_of_is_contr_fun _ _ _ (λb, is_surjective_rec_on H' b (λa, is_contr.mk a (λa', fiber_eq ((ap f)⁻¹ ((point_eq a) ⬝ (point_eq a')⁻¹)) (by rewrite (right_inv (ap f)); rewrite inv_con_cancel_right)))) definition is_split_surjective_of_is_retraction [H : is_retraction f] : is_split_surjective f := λb, fiber.mk (sect f b) (right_inverse f b) definition is_constant_compose_point [constructor] [instance] (b : B) : is_constant (f ∘ point : fiber f b → B) := is_constant.mk b (λv, by induction v with a p;exact p) definition is_embedding_of_is_prop_fiber [H : Π(b : B), is_prop (fiber f b)] : is_embedding f := is_embedding_of_is_prop_fun _ definition is_retraction_of_is_equiv [instance] [H : is_equiv f] : is_retraction f := is_retraction.mk f⁻¹ (right_inv f) definition is_section_of_is_equiv [instance] [H : is_equiv f] : is_section f := is_section.mk f⁻¹ (left_inv f) definition is_equiv_of_is_section_of_is_retraction [H1 : is_retraction f] [H2 : is_section f] : is_equiv f := let g := sect f in let h := retr f in adjointify f g (right_inverse f) (λa, calc g (f a) = h (f (g (f a))) : left_inverse ... = h (f a) : right_inverse f ... = a : left_inverse) section local attribute is_equiv_of_is_section_of_is_retraction [instance] [priority 10000] local attribute trunctype.struct [instance] [priority 1] -- remove after #842 is closed variable (f) definition is_prop_is_retraction_prod_is_section : is_prop (is_retraction f × is_section f) := begin apply is_prop_of_imp_is_contr, intro H, induction H with H1 H2, exact _, end end definition is_retraction_trunc_functor [instance] (r : A → B) [H : is_retraction r] (n : trunc_index) : is_retraction (trunc_functor n r) := is_retraction.mk (trunc_functor n (sect r)) (λb, ((trunc_functor_compose n (sect r) r) b)⁻¹ ⬝ trunc_homotopy n (right_inverse r) b ⬝ trunc_functor_id n B b) -- Lemma 3.11.7 definition is_contr_retract (r : A → B) [H : is_retraction r] : is_contr A → is_contr B := begin intro CA, apply is_contr.mk (r (center A)), intro b, exact ap r (center_eq (is_retraction.sect r b)) ⬝ (is_retraction.right_inverse r b) end local attribute is_prop_is_retraction_prod_is_section [instance] definition is_retraction_prod_is_section_equiv_is_equiv [constructor] : (is_retraction f × is_section f) ≃ is_equiv f := begin apply equiv_of_is_prop, intro H, induction H, apply is_equiv_of_is_section_of_is_retraction, intro H, split, repeat exact _ end definition is_retraction_equiv_is_split_surjective : is_retraction f ≃ is_split_surjective f := begin fapply equiv.MK, { intro H, induction H with g p, intro b, constructor, exact p b}, { intro H, constructor, intro b, exact point_eq (H b)}, { intro H, esimp, apply eq_of_homotopy, intro b, esimp, induction H b, reflexivity}, { intro H, induction H with g p, reflexivity}, end definition is_embedding_compose (g : B → C) (f : A → B) (H₁ : is_embedding g) (H₂ : is_embedding f) : is_embedding (g ∘ f) := begin intros, apply @(is_equiv.homotopy_closed (ap g ∘ ap f)), { apply is_equiv_compose}, symmetry, exact ap_compose g f end definition is_surjective_compose (g : B → C) (f : A → B) (H₁ : is_surjective g) (H₂ : is_surjective f) : is_surjective (g ∘ f) := begin intro c, induction H₁ c with b p, induction H₂ b with a q, exact image.mk a (ap g q ⬝ p) end definition is_split_surjective_compose (g : B → C) (f : A → B) (H₁ : is_split_surjective g) (H₂ : is_split_surjective f) : is_split_surjective (g ∘ f) := begin intro c, induction H₁ c with b p, induction H₂ b with a q, exact fiber.mk a (ap g q ⬝ p) end definition is_injective_compose (g : B → C) (f : A → B) (H₁ : Π⦃b b'⦄, g b = g b' → b = b') (H₂ : Π⦃a a'⦄, f a = f a' → a = a') ⦃a a' : A⦄ (p : g (f a) = g (f a')) : a = a' := H₂ (H₁ p) /- The definitions is_surjective_of_is_equiv is_equiv_equiv_is_embedding_times_is_surjective are in types.trunc See types.arrow_2 for retractions -/ end function
e9b50925e610e4340e41a6d38918c5b398b1081f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/model_theory/encoding.lean
68e4c9e97bf9f8134afb9b199d327c5f0a5c9b9f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,295
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import computability.encoding import logic.small.list import model_theory.syntax import set_theory.cardinal.ordinal /-! # Encodings and Cardinality of First-Order Syntax > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main Definitions * `first_order.language.term.encoding` encodes terms as lists. * `first_order.language.bounded_formula.encoding` encodes bounded formulas as lists. ## Main Results * `first_order.language.term.card_le` shows that the number of terms in `L.term α` is at most `max ℵ₀ # (α ⊕ Σ i, L.functions i)`. * `first_order.language.bounded_formula.card_le` shows that the number of bounded formulas in `Σ n, L.bounded_formula α n` is at most `max ℵ₀ (cardinal.lift.{max u v} (#α) + cardinal.lift.{u'} L.card)`. ## TODO * `primcodable` instances for terms and formulas, based on the `encoding`s * Computability facts about term and formula operations, to set up a computability approach to incompleteness -/ universes u v w u' v' namespace first_order namespace language variables {L : language.{u v}} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} open_locale first_order cardinal open computability list Structure cardinal fin namespace term /-- Encodes a term as a list of variables and function symbols. -/ def list_encode : L.term α → list (α ⊕ Σ i, L.functions i) | (var i) := [sum.inl i] | (func f ts) := ((sum.inr (⟨_, f⟩ : Σ i, L.functions i)) :: ((list.fin_range _).bind (λ i, (ts i).list_encode))) /-- Decodes a list of variables and function symbols as a list of terms. -/ def list_decode : list (α ⊕ Σ i, L.functions i) → list (option (L.term α)) | [] := [] | ((sum.inl a) :: l) := some (var a) :: list_decode l | ((sum.inr ⟨n, f⟩) :: l) := if h : ∀ (i : fin n), ((list_decode l).nth i).join.is_some then func f (λ i, option.get (h i)) :: ((list_decode l).drop n) else [none] theorem list_decode_encode_list (l : list (L.term α)) : list_decode (l.bind list_encode) = l.map option.some := begin suffices h : ∀ (t : L.term α) (l : list (α ⊕ Σ i, L.functions i)), list_decode (t.list_encode ++ l) = some t :: list_decode l, { induction l with t l lih, { refl }, { rw [cons_bind, h t (l.bind list_encode), lih, list.map] } }, { intro t, induction t with a n f ts ih; intro l, { rw [list_encode, singleton_append, list_decode] }, { rw [list_encode, cons_append, list_decode], have h : list_decode ((fin_range n).bind (λ (i : fin n), (ts i).list_encode) ++ l) = (fin_range n).map (option.some ∘ ts) ++ list_decode l, { induction (fin_range n) with i l' l'ih, { refl }, { rw [cons_bind, list.append_assoc, ih, map_cons, l'ih, cons_append] } }, have h' : ∀ i, (list_decode ((fin_range n).bind (λ (i : fin n), (ts i).list_encode) ++ l)).nth ↑i = some (some (ts i)), { intro i, rw [h, nth_append, nth_map], { simp only [option.map_eq_some', function.comp_app, nth_eq_some], refine ⟨i, ⟨lt_of_lt_of_le i.2 (ge_of_eq (length_fin_range _)), _⟩, rfl⟩, rw [nth_le_fin_range, fin.eta] }, { refine lt_of_lt_of_le i.2 _, simp } }, refine (dif_pos (λ i, option.is_some_iff_exists.2 ⟨ts i, _⟩)).trans _, { rw [option.join_eq_some, h'] }, refine congr (congr rfl (congr rfl (congr rfl (funext (λ i, option.get_of_mem _ _))))) _, { simp [h'] }, { rw [h, drop_left'], rw [length_map, length_fin_range] } } } end /-- An encoding of terms as lists. -/ @[simps] protected def encoding : encoding (L.term α) := { Γ := α ⊕ Σ i, L.functions i, encode := list_encode, decode := λ l, (list_decode l).head'.join, decode_encode := λ t, begin have h := list_decode_encode_list [t], rw [bind_singleton] at h, simp only [h, option.join, head', list.map, option.some_bind, id.def], end } lemma list_encode_injective : function.injective (list_encode : L.term α → list (α ⊕ Σ i, L.functions i)) := term.encoding.encode_injective theorem card_le : # (L.term α) ≤ max ℵ₀ (# (α ⊕ Σ i, L.functions i)) := lift_le.1 (trans term.encoding.card_le_card_list (lift_le.2 (mk_list_le_max _))) theorem card_sigma : # (Σ n, (L.term (α ⊕ fin n))) = max ℵ₀ (# (α ⊕ Σ i, L.functions i)) := begin refine le_antisymm _ _, { rw mk_sigma, refine (sum_le_supr_lift _).trans _, rw [mk_nat, lift_aleph_0, mul_eq_max_of_aleph_0_le_left le_rfl, max_le_iff, csupr_le_iff' (bdd_above_range _)], { refine ⟨le_max_left _ _, λ i, card_le.trans _⟩, refine max_le (le_max_left _ _) _, rw [← add_eq_max le_rfl, mk_sum, mk_sum, mk_sum, add_comm (cardinal.lift (#α)), lift_add, add_assoc, lift_lift, lift_lift, mk_fin, lift_nat_cast], exact add_le_add_right (nat_lt_aleph_0 _).le _ }, { rw [← one_le_iff_ne_zero], refine trans _ (le_csupr (bdd_above_range _) 1), rw [one_le_iff_ne_zero, mk_ne_zero_iff], exact ⟨var (sum.inr 0)⟩ } }, { rw [max_le_iff, ← infinite_iff], refine ⟨infinite.of_injective (λ i, ⟨i + 1, var (sum.inr i)⟩) (λ i j ij, _), _⟩, { cases ij, refl }, { rw [cardinal.le_def], refine ⟨⟨sum.elim (λ i, ⟨0, var (sum.inl i)⟩) (λ F, ⟨1, func F.2 (λ _, var (sum.inr 0))⟩), _⟩⟩, { rintros (a | a) (b | b) h, { simp only [sum.elim_inl, eq_self_iff_true, heq_iff_eq, true_and] at h, rw h }, { simp only [sum.elim_inl, sum.elim_inr, nat.zero_ne_one, false_and] at h, exact h.elim }, { simp only [sum.elim_inr, sum.elim_inl, nat.one_ne_zero, false_and] at h, exact h.elim }, { simp only [sum.elim_inr, eq_self_iff_true, heq_iff_eq, true_and] at h, rw sigma.ext_iff.2 ⟨h.1, h.2.1⟩, } } } } end instance [encodable α] [encodable ((Σ i, L.functions i))] : encodable (L.term α) := encodable.of_left_injection list_encode (λ l, (list_decode l).head'.join) (λ t, begin rw [← bind_singleton list_encode, list_decode_encode_list], simp only [option.join, head', list.map, option.some_bind, id.def], end) instance [h1 : countable α] [h2 : countable (Σl, L.functions l)] : countable (L.term α) := begin refine mk_le_aleph_0_iff.1 (card_le.trans (max_le_iff.2 _)), simp only [le_refl, mk_sum, add_le_aleph_0, lift_le_aleph_0, true_and], exact ⟨cardinal.mk_le_aleph_0, cardinal.mk_le_aleph_0⟩, end instance small [small.{u} α] : small.{u} (L.term α) := small_of_injective list_encode_injective end term namespace bounded_formula /-- Encodes a bounded formula as a list of symbols. -/ def list_encode : ∀ {n : ℕ}, L.bounded_formula α n → list ((Σ k, L.term (α ⊕ fin k)) ⊕ (Σ n, L.relations n) ⊕ ℕ) | n falsum := [sum.inr (sum.inr (n + 2))] | n (equal t₁ t₂) := [sum.inl ⟨_, t₁⟩, sum.inl ⟨_, t₂⟩] | n (rel R ts) := [sum.inr (sum.inl ⟨_, R⟩), sum.inr (sum.inr n)] ++ ((list.fin_range _).map (λ i, sum.inl ⟨n, (ts i)⟩)) | n (imp φ₁ φ₂) := (sum.inr (sum.inr 0)) :: φ₁.list_encode ++ φ₂.list_encode | n (all φ) := (sum.inr (sum.inr 1)) :: φ.list_encode /-- Applies the `forall` quantifier to an element of `(Σ n, L.bounded_formula α n)`, or returns `default` if not possible. -/ def sigma_all : (Σ n, L.bounded_formula α n) → Σ n, L.bounded_formula α n | ⟨(n + 1), φ⟩ := ⟨n, φ.all⟩ | _ := default /-- Applies `imp` to two elements of `(Σ n, L.bounded_formula α n)`, or returns `default` if not possible. -/ def sigma_imp : (Σ n, L.bounded_formula α n) → (Σ n, L.bounded_formula α n) → (Σ n, L.bounded_formula α n) | ⟨m, φ⟩ ⟨n, ψ⟩ := if h : m = n then ⟨m, φ.imp (eq.mp (by rw h) ψ)⟩ else default /-- Decodes a list of symbols as a list of formulas. -/ @[simp] def list_decode : Π (l : list ((Σ k, L.term (α ⊕ fin k)) ⊕ (Σ n, L.relations n) ⊕ ℕ)), (Σ n, L.bounded_formula α n) × { l' : list ((Σ k, L.term (α ⊕ fin k)) ⊕ (Σ n, L.relations n) ⊕ ℕ) // l'.sizeof ≤ max 1 l.sizeof } | ((sum.inr (sum.inr (n + 2))) :: l) := ⟨⟨n, falsum⟩, l, le_max_of_le_right le_add_self⟩ | ((sum.inl ⟨n₁, t₁⟩) :: sum.inl ⟨n₂, t₂⟩ :: l) := ⟨if h : n₁ = n₂ then ⟨n₁, equal t₁ (eq.mp (by rw h) t₂)⟩ else default, l, begin simp only [list.sizeof, ← add_assoc], exact le_max_of_le_right le_add_self, end⟩ | (sum.inr (sum.inl ⟨n, R⟩) :: (sum.inr (sum.inr k)) :: l) := ⟨ if h : ∀ (i : fin n), ((l.map sum.get_left).nth i).join.is_some then if h' : ∀ i, (option.get (h i)).1 = k then ⟨k, bounded_formula.rel R (λ i, eq.mp (by rw h' i) (option.get (h i)).2)⟩ else default else default, l.drop n, le_max_of_le_right (le_add_left (le_add_left (list.drop_sizeof_le _ _)))⟩ | ((sum.inr (sum.inr 0)) :: l) := have (↑((list_decode l).2) : list ((Σ k, L.term (α ⊕ fin k)) ⊕ (Σ n, L.relations n) ⊕ ℕ)).sizeof < 1 + (1 + 1) + l.sizeof, from begin refine lt_of_le_of_lt (list_decode l).2.2 (max_lt _ (nat.lt_add_of_pos_left dec_trivial)), rw [add_assoc, add_comm, nat.lt_succ_iff, add_assoc], exact le_self_add, end, ⟨sigma_imp (list_decode l).1 (list_decode (list_decode l).2).1, (list_decode (list_decode l).2).2, le_max_of_le_right (trans (list_decode _).2.2 (max_le (le_add_right le_self_add) (trans (list_decode _).2.2 (max_le (le_add_right le_self_add) le_add_self))))⟩ | ((sum.inr (sum.inr 1)) :: l) := ⟨sigma_all (list_decode l).1, (list_decode l).2, (list_decode l).2.2.trans (max_le_max le_rfl le_add_self)⟩ | _ := ⟨default, [], le_max_left _ _⟩ @[simp] theorem list_decode_encode_list (l : list (Σ n, L.bounded_formula α n)) : (list_decode (l.bind (λ φ, φ.2.list_encode))).1 = l.head := begin suffices h : ∀ (φ : (Σ n, L.bounded_formula α n)) l, (list_decode (list_encode φ.2 ++ l)).1 = φ ∧ (list_decode (list_encode φ.2 ++ l)).2.1 = l, { induction l with φ l lih, { rw [list.nil_bind], simp [list_decode], }, { rw [cons_bind, (h φ _).1, head_cons] } }, { rintro ⟨n, φ⟩, induction φ with _ _ _ _ _ _ _ ts _ _ _ ih1 ih2 _ _ ih; intro l, { rw [list_encode, singleton_append, list_decode], simp only [eq_self_iff_true, heq_iff_eq, and_self], }, { rw [list_encode, cons_append, cons_append, list_decode, dif_pos], { simp only [eq_mp_eq_cast, cast_eq, eq_self_iff_true, heq_iff_eq, and_self, nil_append], }, { simp only [eq_self_iff_true, heq_iff_eq, and_self], } }, { rw [list_encode, cons_append, cons_append, singleton_append, cons_append, list_decode], { have h : ∀ (i : fin φ_l), ((list.map sum.get_left (list.map (λ (i : fin φ_l), sum.inl (⟨(⟨φ_n, rel φ_R ts⟩ : Σ n, L.bounded_formula α n).fst, ts i⟩ : Σ n, L.term (α ⊕ fin n))) (fin_range φ_l) ++ l)).nth ↑i).join = some ⟨_, ts i⟩, { intro i, simp only [option.join, map_append, map_map, option.bind_eq_some, id.def, exists_eq_right, nth_eq_some, length_append, length_map, length_fin_range], refine ⟨lt_of_lt_of_le i.2 le_self_add, _⟩, rw [nth_le_append, nth_le_map], { simp only [sum.get_left, nth_le_fin_range, fin.eta, function.comp_app, eq_self_iff_true, heq_iff_eq, and_self] }, { exact lt_of_lt_of_le i.is_lt (ge_of_eq (length_fin_range _)) }, { rw [length_map, length_fin_range], exact i.2 } }, rw dif_pos, swap, { exact λ i, option.is_some_iff_exists.2 ⟨⟨_, ts i⟩, h i⟩ }, rw dif_pos, swap, { intro i, obtain ⟨h1, h2⟩ := option.eq_some_iff_get_eq.1 (h i), rw h2 }, simp only [eq_self_iff_true, heq_iff_eq, true_and], refine ⟨funext (λ i, _), _⟩, { obtain ⟨h1, h2⟩ := option.eq_some_iff_get_eq.1 (h i), rw [eq_mp_eq_cast, cast_eq_iff_heq], exact (sigma.ext_iff.1 ((sigma.eta (option.get h1)).trans h2)).2 }, rw [list.drop_append_eq_append_drop, length_map, length_fin_range, nat.sub_self, drop, drop_eq_nil_of_le, nil_append], rw [length_map, length_fin_range], }, }, { rw [list_encode, list.append_assoc, cons_append, list_decode], simp only [subtype.val_eq_coe] at *, rw [(ih1 _).1, (ih1 _).2, (ih2 _).1, (ih2 _).2, sigma_imp, dif_pos rfl], exact ⟨rfl, rfl⟩, }, { rw [list_encode, cons_append, list_decode], simp only, simp only [subtype.val_eq_coe] at *, rw [(ih _).1, (ih _).2, sigma_all], exact ⟨rfl, rfl⟩ } } end /-- An encoding of bounded formulas as lists. -/ @[simps] protected def encoding : encoding (Σ n, L.bounded_formula α n) := { Γ := (Σ k, L.term (α ⊕ fin k)) ⊕ (Σ n, L.relations n) ⊕ ℕ, encode := λ φ, φ.2.list_encode, decode := λ l, (list_decode l).1, decode_encode := λ φ, begin have h := list_decode_encode_list [φ], rw [bind_singleton] at h, rw h, refl, end } lemma list_encode_sigma_injective : function.injective (λ (φ : Σ n, L.bounded_formula α n), φ.2.list_encode) := bounded_formula.encoding.encode_injective theorem card_le : # (Σ n, L.bounded_formula α n) ≤ max ℵ₀ (cardinal.lift.{max u v} (#α) + cardinal.lift.{u'} L.card) := begin refine lift_le.1 ((bounded_formula.encoding.card_le_card_list).trans _), rw [encoding_Γ, mk_list_eq_max_mk_aleph_0, lift_max, lift_aleph_0, lift_max, lift_aleph_0, max_le_iff], refine ⟨_, le_max_left _ _⟩, rw [mk_sum, term.card_sigma, mk_sum, ← add_eq_max le_rfl, mk_sum, mk_nat], simp only [lift_add, lift_lift, lift_aleph_0], rw [← add_assoc, add_comm, ← add_assoc, ← add_assoc, aleph_0_add_aleph_0, add_assoc, add_eq_max le_rfl, add_assoc, card, symbols, mk_sum, lift_add, lift_lift, lift_lift], end end bounded_formula end language end first_order
c8fea082bf17450db602a847dbc4744a13dbe5df
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebraic_geometry/presheafed_space/has_colimits.lean
735ea8d255825ffbca62a334d1a4cb2989ff9d47
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
10,222
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 algebraic_geometry.presheafed_space import topology.category.Top.limits import topology.sheaves.limits import category_theory.limits.concrete_category /-! # `PresheafedSpace C` has colimits. If `C` has limits, then the category `PresheafedSpace C` has colimits, and the forgetful functor to `Top` preserves these colimits. When restricted to a diagram where the underlying continuous maps are open embeddings, this says that we can glue presheaved spaces. Given a diagram `F : J ⥤ PresheafedSpace C`, we first build the colimit of the underlying topological spaces, as `colimit (F ⋙ PresheafedSpace.forget C)`. Call that colimit space `X`. Our strategy is to push each of the presheaves `F.obj j` forward along the continuous map `colimit.ι (F ⋙ PresheafedSpace.forget C) j` to `X`. Since pushforward is functorial, we obtain a diagram `J ⥤ (presheaf C X)ᵒᵖ` of presheaves on a single space `X`. (Note that the arrows now point the other direction, because this is the way `PresheafedSpace C` is set up.) The limit of this diagram then constitutes the colimit presheaf. -/ noncomputable theory universes v u open category_theory open Top open Top.presheaf open topological_space open opposite open category_theory.category open category_theory.limits open category_theory.functor variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] namespace algebraic_geometry namespace PresheafedSpace @[simp] lemma map_id_c_app (F : J ⥤ PresheafedSpace C) (j) (U) : (F.map (𝟙 j)).c.app (op U) = (pushforward.id (F.obj j).presheaf).inv.app (op U) ≫ (pushforward_eq (by { simp, refl }) (F.obj j).presheaf).hom.app (op U) := begin cases U, dsimp, simp [PresheafedSpace.congr_app (F.map_id j)], refl, end @[simp] lemma map_comp_c_app (F : J ⥤ PresheafedSpace C) {j₁ j₂ j₃} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃) (U) : (F.map (f ≫ g)).c.app (op U) = (F.map g).c.app (op U) ≫ (pushforward_map (F.map g).base (F.map f).c).app (op U) ≫ (pushforward.comp (F.obj j₁).presheaf (F.map f).base (F.map g).base).inv.app (op U) ≫ (pushforward_eq (by { rw F.map_comp, refl }) _).hom.app _ := begin cases U, dsimp, simp only [PresheafedSpace.congr_app (F.map_comp f g)], dsimp, simp, end /-- Given a diagram of presheafed spaces, we can push all the presheaves forward to the colimit `X` of the underlying topological spaces, obtaining a diagram in `(presheaf C X)ᵒᵖ`. -/ @[simps] def pushforward_diagram_to_colimit (F : J ⥤ PresheafedSpace C) : J ⥤ (presheaf C (colimit (F ⋙ PresheafedSpace.forget C)))ᵒᵖ := { obj := λ j, op ((colimit.ι (F ⋙ PresheafedSpace.forget C) j) _* (F.obj j).presheaf), map := λ j j' f, (pushforward_map (colimit.ι (F ⋙ PresheafedSpace.forget C) j') (F.map f).c ≫ (pushforward.comp (F.obj j).presheaf ((F ⋙ PresheafedSpace.forget C).map f) (colimit.ι (F ⋙ PresheafedSpace.forget C) j')).inv ≫ (pushforward_eq (colimit.w (F ⋙ PresheafedSpace.forget C) f) (F.obj j).presheaf).hom).op, map_id' := λ j, begin apply (op_equiv _ _).injective, ext U, op_induction U, cases U, dsimp, simp, dsimp, simp, end, map_comp' := λ j₁ j₂ j₃ f g, begin apply (op_equiv _ _).injective, ext U, dsimp, simp only [map_comp_c_app, id.def, eq_to_hom_op, pushforward_map_app, eq_to_hom_map, assoc, id_comp, pushforward.comp_inv_app, pushforward_eq_hom_app], dsimp, simp only [eq_to_hom_trans, id_comp], congr' 1, -- The key fact is `(F.map f).c.congr`, -- which allows us in rewrite in the argument of `(F.map f).c.app`. rw (F.map f).c.congr, -- Now we pick up the pieces. First, we say what we want to replace that open set by: swap 3, refine op ((opens.map (colimit.ι (F ⋙ PresheafedSpace.forget C) j₂)).obj (unop U)), -- Now we show the open sets are equal. swap 2, { apply unop_injective, rw ←opens.map_comp_obj, congr, exact colimit.w (F ⋙ PresheafedSpace.forget C) g, }, -- Finally, the original goal is now easy: swap 2, { simp, refl, }, end, } variables [has_limits C] /-- Auxilliary definition for `PresheafedSpace.has_colimits`. -/ @[simps] def colimit (F : J ⥤ PresheafedSpace C) : PresheafedSpace C := { carrier := colimit (F ⋙ PresheafedSpace.forget C), presheaf := limit (pushforward_diagram_to_colimit F).left_op, } /-- Auxilliary definition for `PresheafedSpace.has_colimits`. -/ @[simps] def colimit_cocone (F : J ⥤ PresheafedSpace C) : cocone F := { X := colimit F, ι := { app := λ j, { base := colimit.ι (F ⋙ PresheafedSpace.forget C) j, c := limit.π _ (op j), }, naturality' := λ j j' f, begin fapply PresheafedSpace.ext, { ext x, exact colimit.w_apply (F ⋙ PresheafedSpace.forget C) f x, }, { ext U, op_induction U, cases U, dsimp, simp only [PresheafedSpace.id_c_app, eq_to_hom_op, eq_to_hom_map, assoc, pushforward.comp_inv_app], rw ← congr_arg nat_trans.app (limit.w (pushforward_diagram_to_colimit F).left_op f.op), dsimp, simp only [eq_to_hom_op, eq_to_hom_map, assoc, id_comp, pushforward.comp_inv_app], congr, dsimp, simp only [id_comp], rw ←is_iso.inv_comp_eq, simp, refl, } end, }, } namespace colimit_cocone_is_colimit /-- Auxilliary definition for `PresheafedSpace.colimit_cocone_is_colimit`. -/ def desc_c_app (F : J ⥤ PresheafedSpace C) (s : cocone F) (U : (opens ↥(s.X.carrier))ᵒᵖ) : s.X.presheaf.obj U ⟶ (colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s) _* limit (pushforward_diagram_to_colimit F).left_op).obj U := begin refine limit.lift _ { X := s.X.presheaf.obj U, π := { app := λ j, _, naturality' := λ j j' f, _, }} ≫ (limit_obj_iso_limit_comp_evaluation _ _).inv, -- We still need to construct the `app` and `naturality'` fields omitted above. { refine (s.ι.app (unop j)).c.app U ≫ (F.obj (unop j)).presheaf.map (eq_to_hom _), dsimp, rw ←opens.map_comp_obj, simp, }, { rw (PresheafedSpace.congr_app (s.w f.unop).symm U), dsimp, have w := functor.congr_obj (congr_arg opens.map (colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (unop U), simp only [opens.map_comp_obj_unop] at w, replace w := congr_arg op w, have w' := nat_trans.congr (F.map f.unop).c w, rw w', dsimp, simp, dsimp, simp, refl, }, end lemma desc_c_naturality (F : J ⥤ PresheafedSpace C) (s : cocone F) {U V : (opens ↥(s.X.carrier))ᵒᵖ} (i : U ⟶ V) : s.X.presheaf.map i ≫ desc_c_app F s V = desc_c_app F s U ≫ (colimit.desc (F ⋙ forget C) ((forget C).map_cocone s) _* (colimit_cocone F).X.presheaf).map i := begin dsimp [desc_c_app], ext, simp only [limit.lift_π, nat_trans.naturality, limit.lift_π_assoc, eq_to_hom_map, assoc, pushforward_obj_map, nat_trans.naturality_assoc, op_map, limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc, limit_obj_iso_limit_comp_evaluation_inv_π_app], dsimp, have w := functor.congr_hom (congr_arg opens.map (colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (i.unop), simp only [opens.map_comp_map] at w, replace w := congr_arg has_hom.hom.op w, rw w, dsimp, simp, end end colimit_cocone_is_colimit open colimit_cocone_is_colimit /-- Auxilliary definition for `PresheafedSpace.has_colimits`. -/ def colimit_cocone_is_colimit (F : J ⥤ PresheafedSpace C) : is_colimit (colimit_cocone F) := { desc := λ s, { base := colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s), c := { app := λ U, desc_c_app F s U, naturality' := λ U V i, desc_c_naturality F s i }, }, fac' := -- tidy can do this but it takes too long begin intros s j, dsimp, fapply PresheafedSpace.ext, { simp, }, { ext, dsimp [desc_c_app], simp only [eq_to_hom_op, limit.lift_π_assoc, eq_to_hom_map, assoc, pushforward.comp_inv_app, limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc], dsimp, simp }, end, uniq' := λ s m w, begin -- We need to use the identity on the continuous maps twice, so we prepare that first: have t : m.base = colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s), { ext, dsimp, simp only [colimit.ι_desc_apply, map_cocone_ι_app], rw ← w j, simp, }, fapply PresheafedSpace.ext, -- could `ext` please not reorder goals? { exact t, }, { ext U j, dsimp [desc_c_app], simp only [limit.lift_π, eq_to_hom_op, eq_to_hom_map, assoc, limit_obj_iso_limit_comp_evaluation_inv_π_app], rw PresheafedSpace.congr_app (w (unop j)).symm U, dsimp, have w := congr_arg op (functor.congr_obj (congr_arg opens.map t) (unop U)), rw nat_trans.congr (limit.π (pushforward_diagram_to_colimit F).left_op j) w, simp, dsimp, simp, } end, } /-- When `C` has limits, the category of presheaved spaces with values in `C` itself has colimits. -/ instance : has_colimits (PresheafedSpace C) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } /-- The underlying topological space of a colimit of presheaved spaces is the colimit of the underlying topological spaces. -/ instance forget_preserves_colimits : preserves_colimits (PresheafedSpace.forget C) := { preserves_colimits_of_shape := λ J 𝒥, by exactI { preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_is_colimit F) begin apply is_colimit.of_iso_colimit (colimit.is_colimit _), fapply cocones.ext, { refl, }, { intro j, dsimp, simp, } end } } end PresheafedSpace end algebraic_geometry
c2b15b798c0b5a67cd372c71e139f834e6bddc6e
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/notes/exam1inClassReview.lean
e87da4ac076b88e183faa1bcb69f3c22ba27d9bf
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
1,515
lean
/- The identity function for any type -/ namespace review --polymorphic identity function def id (α : Type) (a : α) : α := a #eval id bool tt #eval id string "Hello" --does the same thing as id but with different notation def id' (α : Type) : α → α | a := a #eval id' bool tt #eval id' string "Hello" --Type Inference -- {} allows for implicit arguments def id'' {a : Type} : a → a | a := a #eval id'' tt #eval id'' "Hello" #check (@id'' nat) --@ turns off implicit arguments /- Polymorphic Data Type We will be making boxed again to practice -/ inductive boxed_nat : Type | box_nat : ℕ → boxed_nat --another way to do the same thing as above inductive boxed_nat' : Type | box_nat (n : ℕ) : boxed_nat' open boxed_nat def unbox_nat : boxed_nat → ℕ | (box_nat v) := v --This makes the Data Type Polymorphic inductive boxed (α : Type) : Type | box : α → boxed open boxed def unbox {α : Type} : boxed α → α | (box v) := v /- We are going to be making a new Polymorphic Data Type First lets talk about set theory: Set Product: When we take two sets and combine them, we get every possible combination of the elements of the two sets Our new data type will be called Prod -/ inductive prod (α β: Type) : Type | pair (a : α) (b : β) : prod def fst {α β : Type} : prod α β → α | (prod.pair a b) := a def snd {α β : Type} : prod α β → β | (prod.pair a b) := b def p1 := prod.pair 3 "Hello" #eval fst p1 #eval snd p1 end review
07dbaa8fdbe3d8466d63448a8015ea561cc02266
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/non_zero_divisors.lean
457475fe960e820be427411d47816f743ded91aa
[ "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
2,445
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Devon Tuma -/ import group_theory.submonoid.basic /-! # Non-zero divisors In this file we define the submonoid `non_zero_divisors` of a `monoid_with_zero`. -/ section non_zero_divisors /-- The submonoid of non-zero-divisors of a `monoid_with_zero` `R`. -/ def non_zero_divisors (R : Type*) [monoid_with_zero R] : submonoid R := { carrier := {x | ∀ z, z * x = 0 → z = 0}, one_mem' := λ z hz, by rwa mul_one at hz, mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } variables {R A : Type*} [comm_ring R] [integral_domain A] lemma mul_mem_non_zero_divisors {a b : R} : a * b ∈ non_zero_divisors R ↔ a ∈ non_zero_divisors R ∧ b ∈ non_zero_divisors R := begin split, { intro h, split; intros x h'; apply h, { rw [←mul_assoc, h', zero_mul] }, { rw [mul_comm a b, ←mul_assoc, h', zero_mul] } }, { rintros ⟨ha, hb⟩ x hx, apply ha, apply hb, rw [mul_assoc, hx] }, end lemma eq_zero_of_ne_zero_of_mul_right_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma eq_zero_of_ne_zero_of_mul_left_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : x * y = 0) : y = 0 := or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_right_eq_zero hnx⟩ lemma map_ne_zero_of_mem_non_zero_divisors [nontrivial R] {B : Type*} [ring B] {g : R →+* B} (hg : function.injective g) {x : non_zero_divisors R} : g x ≠ 0 := λ h0, one_ne_zero (x.2 1 ((one_mul x.1).symm ▸ (hg (trans h0 g.map_zero.symm)))) lemma map_mem_non_zero_divisors {B : Type*} [integral_domain B] {g : A →+* B} (hg : function.injective g) {x : non_zero_divisors A} : g x ∈ non_zero_divisors B := λ z hz, eq_zero_of_ne_zero_of_mul_right_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz lemma le_non_zero_divisors_of_domain {M : submonoid A} (hM : ↑0 ∉ M) : M ≤ non_zero_divisors A := λ x hx y hy, or.rec_on (eq_zero_or_eq_zero_of_mul_eq_zero hy) (λ h, h) (λ h, absurd (h ▸ hx : (0 : A) ∈ M) hM) end non_zero_divisors
4b0a5366406d91f6d6a8c6906b73a8eb17c29ca3
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/string/basic.lean
233683e960f5ff074047bdb823433b2a843e5e19
[ "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
8,675
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic /-- In the VM, strings are implemented using a dynamic array and UTF-8 encoding. TODO: we currently cannot mark string_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s⟩ namespace string instance : has_lt string := ⟨λ s₁ s₂, s₁.data < s₂.data⟩ /-- Remark: this function has a VM builtin efficient implementation. -/ instance has_decidable_lt (s₁ s₂ : string) : decidable (s₁ < s₂) := list.has_decidable_lt s₁.data s₂.data instance has_decidable_eq : decidable_eq string := λ ⟨x⟩ ⟨y⟩, match list.has_dec_eq x y with | is_true p := is_true (congr_arg string_imp.mk p) | is_false p := is_false (λ q, p (string_imp.mk.inj q)) end def empty : string := ⟨[]⟩ def length : string → nat | ⟨s⟩ := s.length /-- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def push : string → char → string | ⟨s⟩ c := ⟨s ++ [c]⟩ /-- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def append : string → string → string | ⟨a⟩ ⟨b⟩ := ⟨a ++ b⟩ /-- O(n) in the VM, where n is the length of the string -/ def to_list : string → list char | ⟨s⟩ := s def fold {α} (a : α) (f : α → char → α) (s : string) : α := s.to_list.foldl f a /-- In the VM, the string iterator is implemented as a pointer to the string being iterated + index. TODO: we currently cannot mark interator_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure iterator_imp := (fst : list char) (snd : list char) def iterator := iterator_imp def mk_iterator : string → iterator | ⟨s⟩ := ⟨[], s⟩ namespace iterator def curr : iterator → char | ⟨p, c::n⟩ := c | _ := default /-- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time if it is. -/ def set_curr : iterator → char → iterator | ⟨p, c::n⟩ c' := ⟨p, c'::n⟩ | it c' := it def next : iterator → iterator | ⟨p, c::n⟩ := ⟨c::p, n⟩ | ⟨p, []⟩ := ⟨p, []⟩ def prev : iterator → iterator | ⟨c::p, n⟩ := ⟨p, c::n⟩ | ⟨[], n⟩ := ⟨[], n⟩ def has_next : iterator → bool | ⟨p, []⟩ := ff | _ := tt def has_prev : iterator → bool | ⟨[], n⟩ := ff | _ := tt def insert : iterator → string → iterator | ⟨p, n⟩ ⟨s⟩ := ⟨p, s++n⟩ def remove : iterator → nat → iterator | ⟨p, n⟩ m := ⟨p, n.drop m⟩ /-- In the VM, `to_string` is a constant time operation. -/ def to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse ++ n⟩ def to_end : iterator → iterator | ⟨p, n⟩ := ⟨n.reverse ++ p, []⟩ def next_to_string : iterator → string | ⟨p, n⟩ := ⟨n⟩ def prev_to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse⟩ protected def extract_core : list char → list char → option (list char) | [] cs := none | (c::cs₁) cs₂ := if cs₁ = cs₂ then some [c] else match extract_core cs₁ cs₂ with | none := none | some r := some (c::r) end def extract : iterator → iterator → option string | ⟨p₁, n₁⟩ ⟨p₂, n₂⟩ := if p₁.reverse ++ n₁ ≠ p₂.reverse ++ n₂ then none else if n₁ = n₂ then some "" else match iterator.extract_core n₁ n₂ with | none := none | some r := some ⟨r⟩ end end iterator end string /-! The following definitions do not have builtin support in the VM -/ instance : inhabited string := ⟨string.empty⟩ instance : has_sizeof string := ⟨string.length⟩ instance : has_append string := ⟨string.append⟩ namespace string def str : string → char → string := push def is_empty (s : string) : bool := to_bool (s.length = 0) def front (s : string) : char := s.mk_iterator.curr def back (s : string) : char := s.mk_iterator.to_end.prev.curr def join (l : list string) : string := l.foldl (λ r s, r ++ s) "" def singleton (c : char) : string := empty.push c def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string namespace iterator def nextn : iterator → nat → iterator | it 0 := it | it (i+1) := nextn it.next i def prevn : iterator → nat → iterator | it 0 := it | it (i+1) := prevn it.prev i end iterator def pop_back (s : string) : string := s.mk_iterator.to_end.prev.prev_to_string def popn_back (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).prev_to_string def backn (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).next_to_string end string protected def char.to_string (c : char) : string := string.singleton c private def to_nat_core : string.iterator → nat → nat → nat | it 0 r := r | it (i+1) r := let c := it.curr in let r := r*10 + c.to_nat - '0'.to_nat in to_nat_core it.next i r def string.to_nat (s : string) : nat := to_nat_core s.mk_iterator s.length 0 namespace string private lemma nil_ne_append_singleton : ∀ (c : char) (l : list char), [] ≠ l ++ [c] | c [] := λ h, list.no_confusion h | c (d::l) := λ h, list.no_confusion h lemma empty_ne_str : ∀ (c : char) (s : string), empty ≠ str s c | c ⟨l⟩ := λ h : string_imp.mk [] = string_imp.mk (l ++ [c]), string_imp.no_confusion h $ λ h, nil_ne_append_singleton _ _ h lemma str_ne_empty (c : char) (s : string) : str s c ≠ empty := (empty_ne_str c s).symm private lemma str_ne_str_left_aux : ∀ {c₁ c₂ : char} (l₁ l₂ : list char), c₁ ≠ c₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := list.no_confusion h₂ (λ h _, absurd h h₁) | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (str_ne_str_left_aux l₁ l₂ h₁) lemma str_ne_str_left : ∀ {c₁ c₂ : char} (s₁ s₂ : string), c₁ ≠ c₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_left_aux l₁ l₂ h₁) private lemma str_ne_str_right_aux : ∀ (c₁ c₂ : char) {l₁ l₂ : list char}, l₁ ≠ l₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := absurd rfl h₁ | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have aux₁ : d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have d₁ = d₂, from list.no_confusion aux₁ (λ h _, h), have aux₂ : l₁ ≠ l₂, from λ h, have d₁ :: l₁ = d₂ :: l₂, from eq.subst h (eq.subst this rfl), absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion aux₁ (λ _ h, h), absurd this (str_ne_str_right_aux c₁ c₂ aux₂) lemma str_ne_str_right : ∀ (c₁ c₂ : char) {s₁ s₂ : string}, s₁ ≠ s₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have aux : l₁ ≠ l₂, from λ h, have string_imp.mk l₁ = string_imp.mk l₂, from eq.subst h rfl, absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_right_aux c₁ c₂ aux) end string
c717ec6fed1b0408fa2c3677485dc42bf3e2bc41
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/init/prod.lean
ef2381b64ceb78348213d33b5c140714f1fc16ae
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,267
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.prod Author: Leonardo de Moura, Jeremy Avigad -/ prelude import init.wf definition pair := @prod.mk namespace prod notation A * B := prod A B notation A × B := prod A B namespace low_precedence_times reserve infixr `*`:30 -- conflicts with notation for multiplication infixr `*` := prod end low_precedence_times notation `pr₁` := pr1 notation `pr₂` := pr2 -- notation for n-ary tuples notation `(` h `,` t:(foldl `,` (e r, prod.mk r e) h) `)` := t open well_founded section variables {A B : Type} variable (Ra : A → A → Prop) variable (Rb : B → B → Prop) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Prop := left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂), right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Prop := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end context parameters {A B : Type} parameters {Ra : A → A → Prop} {Rb : B → B → Prop} infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @lex.rec_on A B Ra Rb (λp₁ p₂, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod
6e0ffda7bfb79dc893f2b0b7100d6059bff32716
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/metric_space/basic.lean
4a34ea24186fad7b52a91ec4cbbcb6109c7c819a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
137,031
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import tactic.positivity import topology.algebra.order.compact import topology.metric_space.emetric_space import topology.bornology.constructions /-! # Metric spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines metric spaces. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity ## Main definitions * `has_dist α`: Endows a space `α` with a function `dist a b`. * `pseudo_metric_space α`: A space endowed with a distance function, which can be zero even if the two elements are non-equal. * `metric.ball x ε`: The set of all points `y` with `dist y x < ε`. * `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded. * `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`. Additional useful definitions: * `nndist a b`: `dist` as a function to the non-negative reals. * `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`. * `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`. * `proper_space α`: A `pseudo_metric_space` where all closed balls are compact. * `metric.diam s` : The `supr` of the distances of members of `s`. Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite. TODO (anyone): Add "Main results" section. ## Implementation notes Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize to `metric_space` at the end. ## Tags metric, pseudo_metric, dist -/ open set filter topological_space bornology open_locale uniformity topology big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} {X ι : Type*} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_fun dist dist_self dist_comm dist_triangle $ λ ε ε0, ⟨ε / 2, half_pos ε0, λ x hx y hy, add_halves ε ▸ add_lt_add hx hy⟩ /-- This is an internal lemma used to construct a bornology from a metric in `bornology.of_dist`. -/ private lemma bounded_iff_aux {α : Type*} (dist : α → α → ℝ) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (s : set α) (a : α) : (∃ c, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ c) ↔ (∃ r, ∀ ⦃x⦄, x ∈ s → dist x a ≤ r) := begin split; rintro ⟨C, hC⟩, { rcases s.eq_empty_or_nonempty with rfl | ⟨x, hx⟩, { exact ⟨0, by simp⟩ }, { exact ⟨C + dist x a, λ y hy, (dist_triangle y x a).trans (add_le_add_right (hC hy hx) _)⟩ } }, { exact ⟨C + C, λ x hx y hy, (dist_triangle x a y).trans (add_le_add (hC hx) (by {rw dist_comm, exact hC hy}))⟩ } end /-- Construct a bornology from a distance function and metric space axioms. -/ def bornology.of_dist {α : Type*} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : bornology α := bornology.of_bounded { s : set α | ∃ C, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C } ⟨0, λ x hx y, hx.elim⟩ (λ s ⟨c, hc⟩ t h, ⟨c, λ x hx y hy, hc (h hx) (h hy)⟩) (λ s hs t ht, begin rcases s.eq_empty_or_nonempty with rfl | ⟨z, hz⟩, { exact (empty_union t).symm ▸ ht }, { simp only [λ u, bounded_iff_aux dist dist_comm dist_triangle u z] at hs ht ⊢, rcases ⟨hs, ht⟩ with ⟨⟨r₁, hr₁⟩, ⟨r₂, hr₂⟩⟩, exact ⟨max r₁ r₂, λ x hx, or.elim hx (λ hx', (hr₁ hx').trans (le_max_left _ _)) (λ hx', (hr₂ hx').trans (le_max_right _ _))⟩ } end) (λ z, ⟨0, λ x hx y hy, by { rw [eq_of_mem_singleton hx, eq_of_mem_singleton hy], exact (dist_self z).le }⟩) /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ @[ext] class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/ private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_right this zero_lt_two /-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is used. -/ protected meta def pseudo_metric_space.edist_dist_tac : tactic unit := tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac] /-- Pseudo metric and Metric spaces A pseudo metric space is endowed with a distance for which the requirement `d(x,y)=0 → x = y` might not hold. A metric space is a pseudo metric space such that `d(x,y)=0 → x = y`. Each pseudo metric space induces a canonical `uniform_space` and hence a canonical `topological_space` This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each (pseudo) metric space induces a (pseudo) emetric space structure. It is included in the structure, but filled in by default. -/ class pseudo_metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ℝ≥0∞ := λ x y, @coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) (to_bornology : bornology α := bornology.of_dist dist dist_self dist_comm dist_triangle) (cobounded_sets : (bornology.cobounded α).sets = { s | ∃ C, ∀ ⦃x⦄, x ∈ sᶜ → ∀ ⦃y⦄, y ∈ sᶜ → dist x y ≤ C } . control_laws_tac) /-- Two pseudo metric space structures with the same distance function coincide. -/ @[ext] lemma pseudo_metric_space.ext {α : Type*} {m m' : pseudo_metric_space α} (h : m.to_has_dist = m'.to_has_dist) : m = m' := begin unfreezingI { rcases m, rcases m' }, dsimp at h, unfreezingI { subst h }, congr, { ext x y : 2, dsimp at m_edist_dist m'_edist_dist, simp [m_edist_dist, m'_edist_dist] }, { dsimp at m_uniformity_dist m'_uniformity_dist, rw ← m'_uniformity_dist at m_uniformity_dist, exact uniform_space_eq m_uniformity_dist }, { ext1, dsimp at m_cobounded_sets m'_cobounded_sets, rw ← m'_cobounded_sets at m_cobounded_sets, exact filter_eq m_cobounded_sets } end variables [pseudo_metric_space α] attribute [priority 100, instance] pseudo_metric_space.to_uniform_space attribute [priority 100, instance] pseudo_metric_space.to_bornology @[priority 200] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩ /-- Construct a pseudo-metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def pseudo_metric_space.of_dist_topology {α : Type u} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) : pseudo_metric_space α := { dist := dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := { is_open_uniformity := λ s, (H s).trans $ forall₂_congr $ λ x _, ((uniform_space.has_basis_of_fun (exists_gt (0 : ℝ)) dist _ _ _ _).comap (prod.mk x)).mem_iff.symm.trans mem_comap_prod_mk, to_core := (uniform_space_of_dist dist dist_self dist_comm dist_triangle).to_core }, uniformity_dist := rfl, to_bornology := bornology.of_dist dist dist_self dist_comm dist_triangle, cobounded_sets := rfl } @[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := pseudo_metric_space.edist_dist x y theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := pseudo_metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 } lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 } /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico_self, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle section open tactic tactic.positivity /-- Extension for the `positivity` tactic: distances are nonnegative. -/ @[positivity] meta def _root_.tactic.positivity_dist : expr → tactic strictness | `(dist %%a %%b) := nonnegative <$> mk_app ``dist_nonneg [a, b] | _ := failed end @[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b := abs_of_nonneg dist_nonneg /-- A version of `has_dist` that takes value in `ℝ≥0`. -/ class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0) export has_nndist (nndist) /-- Distance as a nonnegative real number. -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] } @[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--In a pseudometric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := (edist_dist x y).symm ▸ ennreal.of_real_lt_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.rfl @[simp] lemma edist_lt_of_real {x y : α} {r : ℝ} : edist x y < ennreal.of_real r ↔ dist x y < r := by rw [edist_dist, ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg] @[simp] lemma edist_le_of_real {x y : α} {r : ℝ} (hr : 0 ≤ r) : edist x y ≤ ennreal.of_real r ↔ dist x y ≤ r := by rw [edist_dist, ennreal.of_real_le_of_real_iff hr] /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) := by rw [dist_nndist, real.to_nnreal_coe] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := dist_triangle _ _ _ theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := dist_triangle_left _ _ _ theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := dist_triangle_right _ _ _ /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate pseudometric space as a topology -/ variables {x y z : α} {δ ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw [dist_comm, mem_ball] theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := dist_nonneg.trans_lt hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption @[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε := ⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩ @[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt] @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty] /-- If a point belongs to an open ball, then there is a strictly smaller radius whose ball also contains it. See also `exists_lt_subset_ball`. -/ lemma exists_lt_mem_ball_of_mem_ball (h : x ∈ ball y ε) : ∃ ε' < ε, x ∈ ball y ε' := begin simp only [mem_ball] at h ⊢, exact ⟨(ε + dist x y) / 2, by linarith, by linarith⟩, end lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } @[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x) @[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ := Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn, hn.trans (lt_add_one _) /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by rw [dist_comm, mem_closed_ball] /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_sphere' : y ∈ sphere x ε ↔ dist x y = ε := by rw [dist_comm, mem_sphere] theorem ne_of_mem_sphere (h : y ∈ sphere x ε) (hε : ε ≠ 0) : y ≠ x := by { contrapose! hε, symmetry, simpa [hε] using h } theorem sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : sphere x ε = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, ne_of_mem_sphere hy hε (subsingleton.elim _ _) theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : is_empty (sphere x ε) := by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α] theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption @[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε := ⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩ @[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le] theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq lemma closed_ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (closed_ball x δ) (ball y ε) := set.disjoint_left.mpr $ λ a ha1 ha2, (h.trans $ dist_triangle_left _ _ _).not_lt $ add_lt_add_of_le_of_lt ha1 ha2 lemma ball_disjoint_closed_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (closed_ball y ε) := (closed_ball_disjoint_ball $ by rwa [add_comm, dist_comm]).symm lemma ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (ball y ε) := (closed_ball_disjoint_ball h).mono_left ball_subset_closed_ball lemma closed_ball_disjoint_closed_ball (h : δ + ε < dist x y) : disjoint (closed_ball x δ) (closed_ball y ε) := set.disjoint_left.mpr $ λ a ha1 ha2, h.not_le $ (dist_triangle_left _ _ _).trans $ add_le_add ha1 ha2 theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := set.disjoint_left.mpr $ λ y hy₁ hy₂, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm.le_bot] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm.le_bot] theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by rw [mem_ball', mem_ball] theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε := by rw [mem_closed_ball', mem_closed_ball] theorem mem_sphere_comm : x ∈ sphere y ε ↔ y ∈ sphere x ε := by rw [mem_sphere', mem_sphere] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h lemma closed_ball_eq_bInter_ball : closed_ball x ε = ⋂ δ > ε, ball x δ := by ext y; rw [mem_closed_ball, ← forall_lt_iff_le', mem_Inter₂]; refl lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... < ε₁ + dist x y : add_lt_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h lemma closed_ball_subset_ball' (h : ε₁ + dist x y < ε₂) : closed_ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... < ε₂ : h lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball (h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y ≤ ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2 lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2 lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := begin rw inter_comm at h, rw [add_comm, dist_comm], exact dist_lt_add_of_nonempty_closed_ball_inter_ball h end lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := dist_lt_add_of_nonempty_closed_ball_inter_ball $ h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl) @[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x) lemma Union_inter_closed_ball_nat (s : set α) (x : α) : (⋃ (n : ℕ), s ∩ closed_ball x n) = s := by rw [← inter_Union, Union_closed_ball_nat, inter_univ] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ /-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z := frequently_iff.1 H (Ici_mem_at_top (dist y x)), exact h _ hR end /-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z := frequently_iff.1 H (Ioi_mem_at_top (dist y x)), exact h _ hR end theorem is_bounded_iff {s : set α} : is_bounded s ↔ ∃ C : ℝ, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := by rw [is_bounded_def, ← filter.mem_sets, (@pseudo_metric_space.cobounded_sets α _).out, mem_set_of_eq, compl_compl] theorem is_bounded_iff_eventually {s : set α} : is_bounded s ↔ ∀ᶠ C in at_top, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := is_bounded_iff.trans ⟨λ ⟨C, h⟩, eventually_at_top.2 ⟨C, λ C' hC' x hx y hy, (h hx hy).trans hC'⟩, eventually.exists⟩ theorem is_bounded_iff_exists_ge {s : set α} (c : ℝ) : is_bounded s ↔ ∃ C, c ≤ C ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := ⟨λ h, ((eventually_ge_at_top c).and (is_bounded_iff_eventually.1 h)).exists, λ h, is_bounded_iff.2 $ h.imp $ λ _, and.right⟩ theorem is_bounded_iff_nndist {s : set α} : is_bounded s ↔ ∃ C : ℝ≥0, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → nndist x y ≤ C := by simp only [is_bounded_iff_exists_ge 0, nnreal.exists, ← nnreal.coe_le_coe, ← dist_nndist, nnreal.coe_mk, exists_prop] theorem to_uniform_space_eq : ‹pseudo_metric_space α›.to_uniform_space = uniform_space_of_dist dist dist_self dist_comm dist_triangle := uniform_space_eq pseudo_metric_space.uniformity_dist theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw [to_uniform_space_eq], exact uniform_space.has_basis_of_fun (exists_gt _) _ _ _ _ _ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_rat : (𝓤 α).has_basis (λ r : ℚ, 0 < r) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ _, rat.cast_pos.2) $ λ ε hε, let ⟨r, hr0, hrε⟩ := exists_rat_btwn hε in ⟨r, rat.cast_pos.1 hr0, hrε.le⟩ theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, by exact_mod_cast hn.le⟩) theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) := metric.mk_uniformity_basis (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) : (𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ r, and.left) $ λ r hr, ⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩, min_le_left _ _⟩ /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) := metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε := metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := begin simp only [uniformity_basis_dist.uniform_embedding_iff uniformity_basis_dist, exists_prop], refl end /-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ /-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing uniform convergence using `dist` -/ lemma tendsto_uniformly_on_filter_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {p' : filter β} : tendsto_uniformly_on_filter F f p p' ↔ ∀ ε > 0, ∀ᶠ (n : ι × β) in (p ×ᶠ p'), dist (f n.snd) (F n.fst n.snd) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, refine (H ε εpos).mono (λ n hn, hε hn), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff /-- A version of `filter.eventually_prod_iff` where the second filter consists of neighborhoods in a pseudo-metric space.-/ lemma eventually_prod_nhds_iff {f : filter ι} {x₀ : α} {p : ι × α → Prop}: (∀ᶠ x in f ×ᶠ 𝓝 x₀, p x) ↔ ∃ (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) (ε > 0), ∀ {i}, pa i → ∀ {x}, dist x x₀ < ε → p (i, x) := begin simp_rw [eventually_prod_iff, metric.eventually_nhds_iff], refine exists_congr (λ q, exists_congr $ λ hq, _), split, { rintro ⟨r, ⟨ε, hε, hεr⟩, hp⟩, exact ⟨ε, hε, λ i hi x hx, hp hi $ hεr hx⟩ }, { rintro ⟨ε, hε, hp⟩, exact ⟨λ x, dist x x₀ < ε, ⟨ε, hε, λ y, id⟩, @hp⟩ } end /-- A version of `filter.eventually_prod_iff` where the first filter consists of neighborhoods in a pseudo-metric space.-/ lemma eventually_nhds_prod_iff {ι α} [pseudo_metric_space α] {f : filter ι} {x₀ : α} {p : α × ι → Prop}: (∀ᶠ x in 𝓝 x₀ ×ᶠ f, p x) ↔ ∃ (ε > (0 : ℝ)) (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) , ∀ {x}, dist x x₀ < ε → ∀ {i}, pa i → p (x, i) := begin rw [eventually_swap_iff, metric.eventually_prod_nhds_iff], split; { rintro ⟨a1, a2, a3, a4, a5⟩, refine ⟨a3, a4, a1, a2, λ b1 b2 b3 b4, a5 b4 b2⟩ } end theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1) theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1) theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) : closed_ball c ε ∈ 𝓝 x := mem_of_superset (is_open_ball.mem_nhds h) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ, forall_congr $ λ x, by simp; itauto theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [pseudo_metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } /-- A variant of `tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_max_order β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε := (at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} : is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball centered at `x` and intersecting `s` only at `x`. -/ lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.ball x ε ∩ s = {x} := nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball of positive radius centered at `x` and intersecting `s` only at `x`. -/ lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.closed_ball x ε ∩ s = {x} := nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx lemma _root_.dense.exists_dist_lt {s : set α} (hs : dense s) (x : α) {ε : ℝ} (hε : 0 < ε) : ∃ y ∈ s, dist x y < ε := begin have : (ball x ε).nonempty, by simp [hε], simpa only [mem_ball'] using hs.exists_mem_open is_open_ball this end lemma _root_.dense_range.exists_dist_lt {β : Type*} {f : β → α} (hf : dense_range f) (x : α) {ε : ℝ} (hε : 0 < ε) : ∃ y, dist x (f y) < ε := exists_range_iff.1 (hf.exists_dist_lt x hε) end metric open metric /-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma pseudo_metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := pseudo_metric.uniformity_basis_edist.eq_binfi /-- A pseudometric space induces a pseudoemetric space -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α := { edist := edist, edist_self := by simp [edist_dist], edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹pseudo_metric_space α› } /-- In a pseudometric space, an open ball of infinite radius is the whole space -/ lemma metric.eball_top_eq_univ (x : α) : emetric.ball x ∞ = set.univ := set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x) /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } @[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ := eq_univ_of_forall $ λ y, edist_lt_top _ _ lemma metric.inseparable_iff {x y : α} : inseparable x y ↔ dist x y = 0 := by rw [emetric.inseparable_iff, edist_nndist, dist_nndist, ennreal.coe_eq_zero, nnreal.coe_eq_zero] /-- Build a new pseudometric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : pseudo_metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans pseudo_metric_space.uniformity_dist } lemma pseudo_metric_space.replace_uniformity_eq {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : m.replace_uniformity H = m := by { ext, refl } /-- Build a new pseudo metric space from an old one where the bundled topological structure is provably (but typically non-definitionaly) equal to some given topological structure. See Note [forgetful inheritance]. -/ @[reducible] def pseudo_metric_space.replace_topology {γ} [U : topological_space γ] (m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) : pseudo_metric_space γ := @pseudo_metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl lemma pseudo_metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) : m.replace_topology H = m := by { ext, refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : pseudo_metric_space α := let m : pseudo_metric_space α := { dist := dist, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := edist, edist_dist := λ x y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the emetric space. -/ def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- Build a new pseudometric space from an old one where the bundled bornology structure is provably (but typically non-definitionaly) equal to some given bornology structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_bornology {α} [B : bornology α] (m : pseudo_metric_space α) (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : pseudo_metric_space α := { to_bornology := B, cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, (H s).trans $ by rw [is_bounded_iff, mem_set_of_eq, compl_compl], .. m } lemma pseudo_metric_space.replace_bornology_eq {α} [m : pseudo_metric_space α] [B : bornology α] (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : pseudo_metric_space.replace_bornology _ H = m := by { ext, refl } /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences (λ n, {p:α×α | dist p.1 p.2 < B n}) (λ n, dist_mem_uniformity $ hB n) H theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a pseudometric space. -/ instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, |x - y|, dist_self := by simp [abs_zero], dist_comm := assume x y, abs_sub_comm _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _ theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| := by simp [real.dist_eq] theorem real.dist_left_le_of_mem_uIcc {x y z : ℝ} (h : y ∈ uIcc x z) : dist x y ≤ dist x z := by simpa only [dist_comm x] using abs_sub_left_of_mem_uIcc h theorem real.dist_right_le_of_mem_uIcc {x y z : ℝ} (h : y ∈ uIcc x z) : dist y z ≤ dist x z := by simpa only [dist_comm _ z] using abs_sub_right_of_mem_uIcc h theorem real.dist_le_of_mem_uIcc {x y x' y' : ℝ} (hx : x ∈ uIcc x' y') (hy : y ∈ uIcc x' y') : dist x y ≤ dist x' y' := abs_sub_le_of_uIcc_subset_uIcc $ uIcc_subset_uIcc (by rwa uIcc_comm) (by rwa uIcc_comm) theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ y' - x' := by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub] using real.dist_le_of_mem_uIcc (Icc_subset_uIcc hx) (Icc_subset_uIcc hy) theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) : dist x y ≤ 1 := by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm] lemma real.ball_eq_Ioo (x r : ℝ) : ball x r = Ioo (x - r) (x + r) := set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq, abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt_comm] lemma real.closed_ball_eq_Icc {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le_comm] theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) := by rw [real.closed_ball_eq_Icc, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] section metric_ordered variables [preorder α] [compact_Icc_space α] lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) := is_compact_Icc.totally_bounded lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) := totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) := totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) := totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b) end metric_ordered /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h /-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball `closed_ball x r` is contained in `u`. -/ lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) : ∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u := begin obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u := nhds_basis_closed_ball.mem_iff.1 hu, have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos, filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε, end end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the pseudometric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- In a pseudometric space, unifom Cauchy sequences are characterized by the fact that, eventually, the distance between all its elements is uniformly, arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.uniform_cauchy_seq_on_iff {γ : Type*} {F : β → γ → α} {s : set γ} : uniform_cauchy_seq_on F at_top s ↔ ∀ ε : ℝ, ε > 0 → ∃ (N : β), ∀ m : β, m ≥ N → ∀ n : β, n ≥ N → ∀ x : γ, x ∈ s → dist (F m x) (F n x) < ε := begin split, { intros h ε hε, let u := { a : α × α | dist a.fst a.snd < ε }, have hu : u ∈ 𝓤 α := metric.mem_uniformity_dist.mpr ⟨ε, hε, (λ a b, by simp)⟩, rw ←@filter.eventually_at_top_prod_self' _ _ _ (λ m, ∀ x : γ, x ∈ s → dist (F m.fst x) (F m.snd x) < ε), specialize h u hu, rw prod_at_top_at_top_eq at h, exact h.mono (λ n h x hx, set.mem_set_of_eq.mp (h x hx)), }, { intros h u hu, rcases (metric.mem_uniformity_dist.mp hu) with ⟨ε, hε, hab⟩, rcases h ε hε with ⟨N, hN⟩, rw [prod_at_top_at_top_eq, eventually_at_top], use (N, N), intros b hb x hx, rcases hb with ⟨hbl, hbr⟩, exact hab (hN b.fst hbl.ge b.snd hbr.ge x hx), }, end /-- If the distance between `s n` and `s m`, `n ≤ m` is bounded above by `b n` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0' {s : β → α} (b : β → ℝ) (h : ∀ n m : β, n ≤ m → dist (s n) (s m) ≤ b n) (h₀ : tendsto b at_top (𝓝 0)) : cauchy_seq s := metric.cauchy_seq_iff'.2 $ λ ε ε0, (h₀.eventually (gt_mem_nhds ε0)).exists.imp $ λ N hN n hn, calc dist (s n) (s N) = dist (s N) (s n) : dist_comm _ _ ... ≤ b N : h _ _ hn ... < ε : hN /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (𝓝 0)) : cauchy_seq s := cauchy_seq_of_le_tendsto_0' b (λ n m hnm, h _ _ _ le_rfl hnm) h₀ /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, rsuffices ⟨R, R0, H⟩ : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_rfl, le_rfl⟩, dist_self _⟩, have S0 := λ n, le_cSup (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ (le_trans hn hm') _ (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Pseudometric space structure pulled back by a function. -/ def pseudo_metric_space.induced {α β} (f : α → β) (m : pseudo_metric_space β) : pseudo_metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := (uniformity_basis_dist.comap _).eq_binfi, to_bornology := bornology.induced f, cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, by simp only [compl_mem_comap, filter.mem_sets, ← is_bounded_def, mem_set_of_eq, compl_compl, is_bounded_iff, ball_image_iff] } /-- Pull back a pseudometric space structure by an inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/ def inducing.comap_pseudo_metric_space {α β} [topological_space α] [pseudo_metric_space β] {f : α → β} (hf : inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_topology hf.induced /-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β] (f : α → β) (h : uniform_inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.pseudo_metric_space {p : α → Prop} : pseudo_metric_space (subtype p) := pseudo_metric_space.induced coe ‹_› theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl theorem subtype.nndist_eq {p : α → Prop} (x y : subtype p) : nndist x y = nndist (x : α) y := rfl namespace mul_opposite @[to_additive] instance : pseudo_metric_space (αᵐᵒᵖ) := pseudo_metric_space.induced mul_opposite.unop ‹_› @[simp, to_additive] theorem dist_unop (x y : αᵐᵒᵖ) : dist (unop x) (unop y) = dist x y := rfl @[simp, to_additive] theorem dist_op (x y : α) : dist (op x) (op y) = dist x y := rfl @[simp, to_additive] theorem nndist_unop (x y : αᵐᵒᵖ) : nndist (unop x) (unop y) = nndist x y := rfl @[simp, to_additive] theorem nndist_op (x y : α) : nndist (op x) (op y) = nndist x y := rfl end mul_opposite section nnreal instance : pseudo_metric_space ℝ≥0 := subtype.pseudo_metric_space lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : nndist a b = max (a - b) (b - a) := begin wlog h : b ≤ a, { rw [nndist_comm, max_comm], exact this b a (le_of_not_le h) }, rw [← nnreal.coe_eq, ← dist_nndist, nnreal.dist_eq, tsub_eq_zero_iff_le.2 h, max_eq_left (zero_le $ a - b), ← nnreal.coe_sub h, abs_of_nonneg (a - b).coe_nonneg], end @[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z := by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le'] @[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z := by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, } lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b := begin suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b), { exact nnreal.coe_le_coe.mp this, }, linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))], end end nnreal section ulift variables [pseudo_metric_space β] instance : pseudo_metric_space (ulift β) := pseudo_metric_space.induced ulift.down ‹_› lemma ulift.dist_eq (x y : ulift β) : dist x y = dist x.down y.down := rfl lemma ulift.nndist_eq (x y : ulift β) : nndist x y = nndist x.down y.down := rfl @[simp] lemma ulift.dist_up_up (x y : β) : dist (ulift.up x) (ulift.up y) = dist x y := rfl @[simp] lemma ulift.nndist_up_up (x y : β) : nndist (ulift.up x) (ulift.up y) = nndist x y := rfl end ulift section prod variables [pseudo_metric_space β] instance prod.pseudo_metric_space_max : pseudo_metric_space (α × β) := (pseudo_emetric_space.to_pseudo_metric_space_of_dist (λ x y : α × β, dist x.1 y.1 ⊔ dist x.2 y.2) (λ x y, (max_lt (edist_lt_top _ _) (edist_lt_top _ _)).ne) (λ x y, by simp only [sup_eq_max, dist_edist, ← ennreal.to_real_max (edist_ne_top _ _) (edist_ne_top _ _), prod.edist_eq])) .replace_bornology $ λ s, by { simp only [← is_bounded_image_fst_and_snd, is_bounded_iff_eventually, ball_image_iff, ← eventually_and, ← forall_and_distrib, ← max_le_iff], refl } lemma prod.dist_eq {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl @[simp] lemma dist_prod_same_left {x : α} {y₁ y₂ : β} : dist (x, y₁) (x, y₂) = dist y₁ y₂ := by simp [prod.dist_eq, dist_nonneg] @[simp] lemma dist_prod_same_right {x₁ x₂ : α} {y : β} : dist (x₁, y) (x₂, y) = dist x₁ x₂ := by simp [prod.dist_eq, dist_nonneg] theorem ball_prod_same (x : α) (y : β) (r : ℝ) : ball x r ×ˢ ball y r = ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem closed_ball_prod_same (x : α) (y : β) (r : ℝ) : closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) @[continuity] theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous @[continuity] theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg : _) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma continuous_iff_continuous_dist [topological_space β] {f : β → α} : continuous f ↔ continuous (λ x : β × β, dist (f x.1) (f x.2)) := ⟨λ h, (h.comp continuous_fst).dist (h.comp continuous_snd), λ h, continuous_iff_continuous_at.2 $ λ x, tendsto_iff_dist_tendsto_zero.2 $ (h.comp (continuous_id.prod_mk continuous_const)).tendsto' _ _ $ dist_self _⟩ lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_dist.subtype_mk _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq @[simp] theorem closure_sphere : closure (sphere x ε) = sphere x ε := is_closed_sphere.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in pseudometric spaces-/ theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a lemma closed_ball_zero' (x : α) : closed_ball x 0 = closure {x} := subset.antisymm (λ y hy, mem_closure_iff.2 $ λ ε ε0, ⟨x, mem_singleton x, (mem_closed_ball.1 hy).trans_lt ε0⟩) (closure_minimal (singleton_subset_iff.2 (dist_self x).le) is_closed_ball) lemma dense_iff {s : set α} : dense s ↔ ∀ x, ∀ r > 0, (ball x r ∩ s).nonempty := forall_congr $ λ x, by simp only [mem_closure_iff, set.nonempty, exists_prop, mem_inter_iff, mem_ball', and_comm] lemma dense_range_iff {f : β → α} : dense_range f ↔ ∀ x, ∀ r > 0, ∃ y, dist x (f y) < r := forall_congr $ λ x, by simp only [mem_closure_iff, exists_range_iff] /-- If a set `s` is separable, then the corresponding subtype is separable in a metric space. This is not obvious, as the countable set whose closure covers `s` does not need in general to be contained in `s`. -/ lemma _root_.topological_space.is_separable.separable_space {s : set α} (hs : is_separable s) : separable_space s := begin classical, rcases eq_empty_or_nonempty s with rfl|⟨⟨x₀, x₀s⟩⟩, { apply_instance }, rcases hs with ⟨c, hc, h'c⟩, haveI : encodable c := hc.to_encodable, obtain ⟨u, -, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), let f : c × ℕ → α := λ p, if h : (metric.ball (p.1 : α) (u p.2) ∩ s).nonempty then h.some else x₀, have fs : ∀ p, f p ∈ s, { rintros ⟨y, n⟩, by_cases h : (ball (y : α) (u n) ∩ s).nonempty, { simpa only [f, h, dif_pos] using h.some_spec.2 }, { simpa only [f, h, not_false_iff, dif_neg] } }, let g : c × ℕ → s := λ p, ⟨f p, fs p⟩, apply separable_space_of_dense_range g, apply metric.dense_range_iff.2, rintros ⟨x, xs⟩ r (rpos : 0 < r), obtain ⟨n, hn⟩ : ∃ n, u n < r / 2 := ((tendsto_order.1 u_lim).2 _ (half_pos rpos)).exists, obtain ⟨z, zc, hz⟩ : ∃ z ∈ c, dist x z < u n := metric.mem_closure_iff.1 (h'c xs) _ (u_pos n), refine ⟨(⟨z, zc⟩, n), _⟩, change dist x (f (⟨z, zc⟩, n)) < r, have A : (metric.ball z (u n) ∩ s).nonempty := ⟨x, hz, xs⟩, dsimp [f], simp only [A, dif_pos], calc dist x A.some ≤ dist x z + dist z A.some : dist_triangle _ _ _ ... < r/2 + r/2 : add_lt_add (hz.trans hn) ((metric.mem_ball'.1 A.some_spec.1).trans hn) ... = r : add_halves _ end /-- The preimage of a separable set by an inducing map is separable. -/ protected lemma _root_.inducing.is_separable_preimage {f : β → α} [topological_space β] (hf : inducing f) {s : set α} (hs : is_separable s) : is_separable (f ⁻¹' s) := begin haveI : second_countable_topology s, { haveI : separable_space s := hs.separable_space, exact uniform_space.second_countable_of_separable _ }, let g : f ⁻¹' s → s := cod_restrict (f ∘ coe) s (λ x, x.2), have : inducing g := (hf.comp inducing_coe).cod_restrict _, haveI : second_countable_topology (f ⁻¹' s) := this.second_countable_topology, rw show f ⁻¹' s = coe '' (univ : set (f ⁻¹' s)), by simpa only [image_univ, subtype.range_coe_subtype], exact (is_separable_of_separable_space _).image continuous_subtype_coe end protected lemma _root_.embedding.is_separable_preimage {f : β → α} [topological_space β] (hf : embedding f) {s : set α} (hs : is_separable s) : is_separable (f ⁻¹' s) := hf.to_inducing.is_separable_preimage hs /-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/ lemma _root_.continuous_on.is_separable_image [topological_space β] {f : α → β} {s : set α} (hf : continuous_on f s) (hs : is_separable s) : is_separable (f '' s) := begin rw show f '' s = s.restrict f '' univ, by ext ; simp, exact (is_separable_univ_iff.2 hs.separable_space).image (continuous_on_iff_continuous_restrict.1 hf), end end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] /-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/ instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) := begin /- we construct the instance from the pseudoemetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine (pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g : Π b, π b, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) (λ f g, _) (λ f g, _)).replace_bornology (λ s, _), show edist f g ≠ ⊤, from ne_of_lt ((finset.sup_lt_iff bot_lt_top).2 $ λ b hb, edist_lt_top _ _), show ↑(sup univ (λ b, nndist (f b) (g b))) = (sup univ (λ b, edist (f b) (g b))).to_real, by simp only [edist_nndist, ← ennreal.coe_finset_sup, ennreal.coe_to_real], show (@is_bounded _ pi.bornology s ↔ @is_bounded _ pseudo_metric_space.to_bornology _), { simp only [← is_bounded_def, is_bounded_iff_eventually, ← forall_is_bounded_image_eval_iff, ball_image_iff, ← eventually_all, function.eval_apply, @dist_nndist (π _)], refine eventually_congr ((eventually_ge_at_top 0).mono $ λ C hC, _), lift C to ℝ≥0 using hC, refine ⟨λ H x hx y hy, nnreal.coe_le_coe.2 $ finset.sup_le $ λ b hb, H b x hx y hy, λ H b x hx y hy, nnreal.coe_le_coe.2 _⟩, simpa only using finset.sup_le_iff.1 (nnreal.coe_le_coe.1 $ H hx hy) b (finset.mem_univ b) } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := nnreal.eq rfl lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl lemma nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} : nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r := by simp [nndist_pi_def] lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to ℝ≥0 using hr.le, simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)], end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr, exact nndist_pi_le_iff end lemma dist_pi_le_iff' [nonempty β] {f g : Π b, π b} {r : ℝ} : dist f g ≤ r ↔ ∀ b, dist (f b) (g b) ≤ r := begin by_cases hr : 0 ≤ r, { exact dist_pi_le_iff hr }, { exact iff_of_false (λ h, hr $ dist_nonneg.trans h) (λ h, hr $ dist_nonneg.trans $ h $ classical.arbitrary _) } end lemma dist_pi_const_le (a b : α) : dist (λ _ : β, a) (λ _, b) ≤ dist a b := (dist_pi_le_iff dist_nonneg).2 $ λ _, le_rfl lemma nndist_pi_const_le (a b : α) : nndist (λ _ : β, a) (λ _, b) ≤ nndist a b := nndist_pi_le_iff.2 $ λ _, le_rfl @[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b := by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b) @[simp] lemma nndist_pi_const [nonempty β] (a b : α) : nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'` for a version assuming `nonempty β` instead of `0 < r`. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = set.pi univ (λ b, ball (x b) r) := by { ext p, simp [dist_pi_lt_iff hr] } /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi` for a version assuming `0 < r` instead of `nonempty β`. -/ lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : ball x r = set.pi univ (λ b, ball (x b) r) := (lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr] /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'` for a version assuming `nonempty β` instead of `0 ≤ r`. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := by { ext p, simp [dist_pi_le_iff hr] } /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi` for a version assuming `0 ≤ r` instead of `nonempty β`. -/ lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := (le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr] @[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) := eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above] @[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) := by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max] lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ dist x' y' := begin refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_uIcc _ _).trans (dist_le_pi_dist _ _ b)); refine Icc_subset_uIcc _, exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩] end end pi section compact /-- Any compact set in a pseudometric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, set.finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A pseudometric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [pseudo_metric_space α] : Prop := (is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) export proper_space (is_compact_closed_ball) /-- In a proper pseudometric space, all spheres are compact. -/ lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : is_compact (sphere x r) := is_compact_of_is_closed_subset (is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball /-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/ instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : compact_space (sphere x r) := is_compact_iff_compact_space.mp (is_compact_sphere _ _) /-- A proper pseudo metric space is sigma compact, and therefore second countable. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin -- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't -- add an instance for `sigma_compact_space`. suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α, rcases em (nonempty α) with ⟨⟨x⟩⟩|hn, { exact ⟨⟨λ n, closed_ball x n, λ n, is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ }, { exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ } end lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R le_rfl).inter_right is_closed_ball } end⟩ /- A compact pseudometric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, is_closed_ball.is_compact⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $ λ x ε ε0, is_compact_closed_ball _ _ /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y yt x xt).le), rcases (is_compact_iff_totally_bounded_is_complete.1 (is_compact_closed_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, -, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A binary product of proper spaces is proper. -/ instance prod_proper_space {α : Type*} {β : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [proper_space α] [proper_space β] : proper_space (α × β) := { is_compact_closed_ball := begin rintros ⟨x, y⟩ r, rw ← closed_ball_prod_same x y, apply (is_compact_closed_ball x r).prod (is_compact_closed_ball y r), end } /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply is_compact_univ_pi (λb, _), apply (h b).is_compact_closed_ball end variables [proper_space α] {x : α} {r : ℝ} {s : set α} /-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' ∈ Ioo 0 r, s ⊆ ball x r' := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ }, have : is_compact s, from is_compact_of_is_closed_subset (is_compact_closed_ball x r) hs (subset.trans h ball_subset_closed_ball), obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x), from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on, have hyr : dist y x < r, from h hys, rcases exists_between hyr with ⟨r', hyr', hrr'⟩, exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩ end /-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' < r, s ⊆ ball x r' := begin cases le_or_lt r 0 with hr hr, { rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s }, exact (exists_lt r).imp (λ r' hr', ⟨hr', empty_subset _⟩) }, { exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) } end end proper_space lemma is_compact.is_separable {s : set α} (hs : is_compact s) : is_separable s := begin haveI : compact_space s := is_compact_iff_compact_space.mp hs, exact is_separable_of_separable_space_subtype s, end namespace metric section second_countable open topological_space /-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, s.countable ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _), rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩, choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0), refine ⟨s, hsc, Union₂_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩, exact_mod_cast hyx x end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a pseudometric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} lemma bounded_iff_is_bounded (s : set α) : bounded s ↔ is_bounded s := begin change bounded s ↔ sᶜ ∈ (cobounded α).sets, simp [pseudo_metric_space.cobounded_sets, metric.bounded], end @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y hy z hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.mono ball_subset_closed_ball /-- Spheres are bounded -/ lemma bounded_sphere : bounded (sphere x r) := bounded_closed_ball.mono sphere_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y hy x hx) _⟩ } }, { exact bounded_closed_ball.mono hC } end lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r := (bounded_iff_subset_ball c).1 h lemma bounded.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r := begin rcases h.subset_ball c with ⟨r, hr⟩, refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩, exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _)) end lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure₂ continuous_dist ha hb h⟩ alias bounded_closure_of_bounded ← bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded. -/ lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) := begin refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end /-- The union of two sets is bounded iff each of the sets is bounded. -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : I.finite) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] protected lemma bounded.prod [pseudo_metric_space β] {s : set α} {t : set β} (hs : bounded s) (ht : bounded t) : bounded (s ×ˢ t) := begin refine bounded_iff_mem_bounded.mpr (λ x hx, _), rcases hs.subset_ball x.1 with ⟨rs, hrs⟩, rcases ht.subset_ball x.2 with ⟨rt, hrt⟩, suffices : s ×ˢ t ⊆ closed_ball x (max rs rt), from bounded_closed_ball.mono this, rw [← @prod.mk.eta _ _ x, ← closed_ball_prod_same], exact prod_mono (hrs.trans $ closed_ball_subset_closed_ball $ le_max_left _ _) (hrt.trans $ closed_ball_subset_closed_ball $ le_max_right _ _) end /-- A totally bounded set is bounded -/ lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s := -- We cover the totally bounded set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A compact set is bounded -/ lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s := -- A compact set is totally bounded, thus bounded h.totally_bounded.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : s.finite) : bounded s := h.is_compact.bounded alias bounded_of_finite ← _root_.set.finite.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩, by rintro H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩; exact H x y⟩ lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α} (hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) : bounded (range f) := begin rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one with ⟨s, hsf, hs1⟩, rw [← image_univ, ← union_compl_self s, image_union, bounded_union], use [(hsf.image f).bounded, 1], rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩) end lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2 lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) := bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a) /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := is_compact_univ.bounded.mono (subset_univ _) lemma bounded_range_of_tendsto (u : ℕ → α) {x : α} (hu : tendsto u at_top (𝓝 x)) : bounded (range u) := hu.cauchy_seq.bounded_range /-- If a function is continuous within a set `s` at every point of a compact set `k`, then it is bounded on some open neighborhood of `k` in `s`. -/ lemma exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hf : ∀ x ∈ k, continuous_within_at f s x) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) := begin apply hk.induction_on, { exact ⟨∅, subset.refl _, is_open_empty, by simp only [image_empty, bounded_empty, empty_inter]⟩ }, { rintros s s' hss' ⟨t, s't, t_open, t_bounded⟩, exact ⟨t, hss'.trans s't, t_open, t_bounded⟩ }, { rintros s s' ⟨t, st, t_open, t_bounded⟩ ⟨t', s't', t'_open, t'_bounded⟩, refine ⟨t ∪ t', union_subset_union st s't', t_open.union t'_open, _⟩, rw [union_inter_distrib_right, image_union], exact t_bounded.union t'_bounded }, { assume x hx, have A : ball (f x) 1 ∈ 𝓝 (f x), from ball_mem_nhds _ zero_lt_one, have B : f ⁻¹' (ball (f x) 1) ∈ 𝓝[s] x, from hf x hx A, obtain ⟨u, u_open, xu, uf⟩ : ∃ (u : set β), is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' ball (f x) 1, from _root_.mem_nhds_within.1 B, refine ⟨u, _, u, subset.refl _, u_open, _⟩, { apply nhds_within_le_nhds, exact u_open.mem_nhds xu }, { apply bounded.mono (image_subset _ uf), exact bounded_ball.mono (image_preimage_subset _ _) } } end /-- If a function is continuous at every point of a compact set `k`, then it is bounded on some open neighborhood of `k`. -/ lemma exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at [topological_space β] {k : set β} {f : β → α} (hk : is_compact k) (hf : ∀ x ∈ k, continuous_at f x) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) := begin simp_rw ← continuous_within_at_univ at hf, simpa only [inter_univ] using exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk hf, end /-- If a function is continuous on a set `s` containing a compact set `k`, then it is bounded on some open neighborhood of `k` in `s`. -/ lemma exists_is_open_bounded_image_inter_of_is_compact_of_continuous_on [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hks : k ⊆ s) (hf : continuous_on f s) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) := exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk (λ x hx, hf x (hks hx)) /-- If a function is continuous on a neighborhood of a compact set `k`, then it is bounded on some open neighborhood of `k`. -/ lemma exists_is_open_bounded_image_of_is_compact_of_continuous_on [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hs : is_open s) (hks : k ⊆ s) (hf : continuous_on f s) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) := exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at hk (λ x hx, hf.continuous_at (hs.mem_nhds (hks hx))) /-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/ lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) : is_compact s := begin unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) }, { exact is_compact_empty }, { rcases hb.subset_ball x with ⟨r, hr⟩, exact is_compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr } end /-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/ lemma bounded.is_compact_closure [proper_space α] (h : bounded s) : is_compact (closure s) := is_compact_of_is_closed_bounded is_closed_closure h.closure /-- The **Heine–Borel theorem**: In a proper Hausdorff space, a set is compact if and only if it is closed and bounded. -/ lemma is_compact_iff_is_closed_bounded [t2_space α] [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩ lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) := ⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩ section conditionally_complete_linear_order variables [preorder α] [compact_Icc_space α] lemma bounded_Icc (a b : α) : bounded (Icc a b) := (totally_bounded_Icc a b).bounded lemma bounded_Ico (a b : α) : bounded (Ico a b) := (totally_bounded_Ico a b).bounded lemma bounded_Ioc (a b : α) : bounded (Ioc a b) := (totally_bounded_Ioc a b).bounded lemma bounded_Ioo (a b : α) : bounded (Ioo a b) := (totally_bounded_Ioo a b).bounded /-- In a pseudo metric space with a conditionally complete linear order such that the order and the metric structure give the same topology, any order-bounded set is metric-bounded. -/ lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) : bounded s := let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u) end conditionally_complete_linear_order end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top $ ediam_le_of_forall_dist_le hC) (λ h, ⟨diam s, λ x hx y hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h lemma ediam_univ_eq_top_iff_noncompact [proper_space α] : emetric.diam (univ : set α) = ∞ ↔ noncompact_space α := by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not] @[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] : emetric.diam (univ : set α) = ∞ := ediam_univ_eq_top_iff_noncompact.mpr ‹_› @[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] : diam (univ : set α) = 0 := by simp [diam] /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ := by rwa [bounded_iff_ediam_ne_top, not_not] at h /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := by rw [diam, ediam_of_unbounded h, ennreal.top_to_real] /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.mono (subset_union_left _ _), have ht : bounded t, from H.mono (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) : diam s ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add (h ha) (h hb) ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_subset_closed_ball h subset.rfl /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := diam_le_of_subset_closed_ball h ball_subset_closed_ball /-- If a family of complete sets with diameter tending to `0` is such that each finite intersection is nonempty, then the total intersection is also nonempty. -/ lemma _root_.is_complete.nonempty_Inter_of_nonempty_bInter {s : ℕ → set α} (h0 : is_complete (s 0)) (hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty) (h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) : (⋂ n, s n).nonempty := begin let u := λ N, (h N).some, have I : ∀ n N, n ≤ N → u N ∈ s n, { assume n N hn, apply mem_of_subset_of_mem _ ((h N).some_spec), assume x hx, simp only [mem_Inter] at hx, exact hx n hn }, have : ∀ n, u n ∈ s 0 := λ n, I 0 n (zero_le _), have : cauchy_seq u, { apply cauchy_seq_of_le_tendsto_0 _ _ h', assume m n N hm hn, exact dist_le_diam_of_mem (h's N) (I _ _ hm) (I _ _ hn) }, obtain ⟨x, hx, xlim⟩ : ∃ (x : α) (H : x ∈ s 0), tendsto (λ (n : ℕ), u n) at_top (𝓝 x) := cauchy_seq_tendsto_of_is_complete h0 (λ n, I 0 n (zero_le _)) this, refine ⟨x, mem_Inter.2 (λ n, _)⟩, apply (hs n).mem_of_tendsto xlim, filter_upwards [Ici_mem_at_top n] with p hp, exact I n p hp, end /-- In a complete space, if a family of closed sets with diameter tending to `0` is such that each finite intersection is nonempty, then the total intersection is also nonempty. -/ lemma nonempty_Inter_of_nonempty_bInter [complete_space α] {s : ℕ → set α} (hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty) (h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) : (⋂ n, s n).nonempty := (hs 0).is_complete.nonempty_Inter_of_nonempty_bInter hs h's h h' end diam lemma exists_local_min_mem_ball [proper_space α] [topological_space β] [conditionally_complete_linear_order β] [order_topology β] {f : α → β} {a z : α} {r : ℝ} (hf : continuous_on f (closed_ball a r)) (hz : z ∈ closed_ball a r) (hf1 : ∀ z' ∈ sphere a r, f z < f z') : ∃ z ∈ ball a r, is_local_min f z := begin simp_rw [← closed_ball_diff_ball] at hf1, exact (is_compact_closed_ball a r).exists_local_min_mem_open ball_subset_closed_ball hf hz hf1 is_open_ball, end end metric namespace tactic open positivity /-- Extension for the `positivity` tactic: the diameter of a set is always nonnegative. -/ @[positivity] meta def positivity_diam : expr → tactic strictness | `(metric.diam %%s) := nonnegative <$> mk_app ``metric.diam_nonneg [s] | e := pp e >>= fail ∘ format.bracket "The expression " " is not of the form `metric.diam s`" end tactic lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α := begin refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _), rcases hs.bounded.subset_ball x with ⟨r, hr⟩, exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩ end lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α := by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) : comap (λ y, dist y x) at_top = cocompact α := (comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) : comap (dist x) at_top = cocompact α := (comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α) (h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) := by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff } /-- We now define `metric_space`, extending `pseudo_metric_space`. -/ class metric_space (α : Type u) extends pseudo_metric_space α : Type u := (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) /-- Two metric space structures with the same distance coincide. -/ @[ext] lemma metric_space.ext {α : Type*} {m m' : metric_space α} (h : m.to_has_dist = m'.to_has_dist) : m = m' := begin have h' : m.to_pseudo_metric_space = m'.to_pseudo_metric_space := pseudo_metric_space.ext h, unfreezingI { rcases m, rcases m' }, dsimp at h', unfreezingI { subst h' }, end /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def metric_space.of_dist_topology {α : Type u} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α := { eq_of_dist_eq_zero := eq_of_dist_eq_zero, ..pseudo_metric_space.of_dist_topology dist dist_self dist_comm dist_triangle H } variables {γ : Type w} [metric_space γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] namespace metric variables {x : γ} {s : set γ} @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero @[simp] lemma sphere_zero : sphere x 0 = {x} := set.ext $ λ y, dist_eq_zero lemma subsingleton_closed_ball (x : γ) {r : ℝ} (hr : r ≤ 0) : (closed_ball x r).subsingleton := begin rcases hr.lt_or_eq with hr|rfl, { rw closed_ball_eq_empty.2 hr, exact subsingleton_empty }, { rw closed_ball_zero, exact subsingleton_singleton } end lemma subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).subsingleton := (subsingleton_closed_ball x hr).anti sphere_subset_closed_ball @[priority 100] -- see Note [lower instance priority] instance _root_.metric_space.to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) := begin simp only [uniform_embedding_iff_uniform_inducing, uniformity_basis_dist.uniform_inducing_iff uniformity_basis_dist, exists_prop], refl end /-- If a `pseudo_metric_space` is a T₀ space, then it is a `metric_space`. -/ def _root_.metric_space.of_t0_pseudo_metric_space (α : Type*) [pseudo_metric_space α] [t0_space α] : metric_space α := { eq_of_dist_eq_zero := λ x y hdist, inseparable.eq $ metric.inseparable_iff.2 hdist, ..‹pseudo_metric_space α› } /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance _root_.metric_space.to_emetric_space : emetric_space γ := emetric_space.of_t0_pseudo_emetric_space γ lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε) (hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s := is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α] {ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : closed_embedding f := closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf /-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then `f` is a uniform embedding with respect to the discrete uniformity on `β`. -/ lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f := uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf end metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : metric_space γ := { eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, ..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, } lemma metric_space.replace_uniformity_eq {γ} [U : uniform_space γ] (m : metric_space γ) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : m.replace_uniformity H = m := by { ext, refl } /-- Build a new metric space from an old one where the bundled topological structure is provably (but typically non-definitionaly) equal to some given topological structure. See Note [forgetful inheritance]. -/ @[reducible] def metric_space.replace_topology {γ} [U : topological_space γ] (m : metric_space γ) (H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) : metric_space γ := @metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl lemma metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : metric_space γ) (H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) : m.replace_topology H = m := by { ext, refl } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := @metric_space.of_t0_pseudo_metric_space α (pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h) _ /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [emetric_space α] (h : ∀ x y : α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λ x y, rfl) /-- Build a new metric space from an old one where the bundled bornology structure is provably (but typically non-definitionaly) equal to some given bornology structure. See Note [forgetful inheritance]. -/ def metric_space.replace_bornology {α} [B : bornology α] (m : metric_space α) (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : metric_space α := { to_bornology := B, .. pseudo_metric_space.replace_bornology _ H, .. m } lemma metric_space.replace_bornology_eq {α} [m : metric_space α] [B : bornology α] (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : metric_space.replace_bornology _ H = m := by { ext, refl } /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : metric_space β) : metric_space γ := { eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), ..pseudo_metric_space.induced f m.to_pseudo_metric_space } /-- Pull back a metric space structure by a uniform embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ @[reducible] def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) : metric_space α := (metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm /-- Pull back a metric space structure by an embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/ @[reducible] def embedding.comap_metric_space {α β} [topological_space α] [metric_space β] (f : α → β) (h : embedding f) : metric_space α := begin letI : uniform_space α := embedding.comap_uniform_space f h, exact uniform_embedding.comap_metric_space f (h.to_uniform_embedding f), end instance subtype.metric_space {α : Type*} {p : α → Prop} [metric_space α] : metric_space (subtype p) := metric_space.induced coe subtype.coe_injective ‹_› @[to_additive] instance {α : Type*} [metric_space α] : metric_space (αᵐᵒᵖ) := metric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_› instance : metric_space empty := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, edist := λ _ _, 0, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, to_uniform_space := empty.uniform_space, uniformity_dist := subsingleton.elim _ _ } instance : metric_space punit.{u + 1} := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, edist := λ _ _, 0, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, to_uniform_space := punit.uniform_space, uniformity_dist := begin simp only, haveI : ne_bot (⨅ ε > (0 : ℝ), 𝓟 {p : punit.{u + 1} × punit.{u + 1} | 0 < ε}), { exact @uniformity.ne_bot _ (uniform_space_of_dist (λ _ _, 0) (λ _, rfl) (λ _ _, rfl) (λ _ _ _, by rw zero_add)) _ }, refine (eq_top_of_ne_bot _).trans (eq_top_of_ne_bot _).symm, end} section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h, ..real.pseudo_metric_space } end real section nnreal instance : metric_space ℝ≥0 := subtype.metric_space end nnreal instance [metric_space β] : metric_space (ulift β) := metric_space.induced ulift.down ulift.down_injective ‹_› section prod instance prod.metric_space_max [metric_space β] : metric_space (γ × β) := { eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, ..prod.pseudo_metric_space_max, } end prod section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ { eq_of_dist_eq_zero := assume f g eq0, begin have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero], have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1, simp only [finset.sup_le_iff] at eq2, exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b) end, ..pseudo_metric_space_pi } end pi namespace metric section second_countable open topological_space /-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric section eq_rel instance {α : Type u} [pseudo_metric_space α] : has_dist (uniform_space.separation_quotient α) := { dist := λ p q, quotient.lift_on₂' p q dist $ λ x y x' y' hx hy, by rw [dist_edist, dist_edist, ← uniform_space.separation_quotient.edist_mk x, ← uniform_space.separation_quotient.edist_mk x', quot.sound hx, quot.sound hy] } lemma uniform_space.separation_quotient.dist_mk {α : Type u} [pseudo_metric_space α] (p q : α) : @dist (uniform_space.separation_quotient α) _ (quot.mk _ p) (quot.mk _ q) = dist p q := rfl instance {α : Type u} [pseudo_metric_space α] : metric_space (uniform_space.separation_quotient α) := emetric_space.to_metric_space_of_dist dist (λ x y, quotient.induction_on₂' x y edist_ne_top) $ λ x y, quotient.induction_on₂' x y dist_edist end eq_rel /-! ### `additive`, `multiplicative` The distance on those type synonyms is inherited without change. -/ open additive multiplicative section variables [has_dist X] instance : has_dist (additive X) := ‹has_dist X› instance : has_dist (multiplicative X) := ‹has_dist X› @[simp] lemma dist_of_mul (a b : X) : dist (of_mul a) (of_mul b) = dist a b := rfl @[simp] lemma dist_of_add (a b : X) : dist (of_add a) (of_add b) = dist a b := rfl @[simp] lemma dist_to_mul (a b : additive X) : dist (to_mul a) (to_mul b) = dist a b := rfl @[simp] lemma dist_to_add (a b : multiplicative X) : dist (to_add a) (to_add b) = dist a b := rfl end section variables [pseudo_metric_space X] instance : pseudo_metric_space (additive X) := ‹pseudo_metric_space X› instance : pseudo_metric_space (multiplicative X) := ‹pseudo_metric_space X› @[simp] lemma nndist_of_mul (a b : X) : nndist (of_mul a) (of_mul b) = nndist a b := rfl @[simp] lemma nndist_of_add (a b : X) : nndist (of_add a) (of_add b) = nndist a b := rfl @[simp] lemma nndist_to_mul (a b : additive X) : nndist (to_mul a) (to_mul b) = nndist a b := rfl @[simp] lemma nndist_to_add (a b : multiplicative X) : nndist (to_add a) (to_add b) = nndist a b := rfl end instance [metric_space X] : metric_space (additive X) := ‹metric_space X› instance [metric_space X] : metric_space (multiplicative X) := ‹metric_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space (additive X) := ‹proper_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space (multiplicative X) := ‹proper_space X› /-! ### Order dual The distance on this type synonym is inherited without change. -/ open order_dual section variables [has_dist X] instance : has_dist Xᵒᵈ := ‹has_dist X› @[simp] lemma dist_to_dual (a b : X) : dist (to_dual a) (to_dual b) = dist a b := rfl @[simp] lemma dist_of_dual (a b : Xᵒᵈ) : dist (of_dual a) (of_dual b) = dist a b := rfl end section variables [pseudo_metric_space X] instance : pseudo_metric_space Xᵒᵈ := ‹pseudo_metric_space X› @[simp] lemma nndist_to_dual (a b : X) : nndist (to_dual a) (to_dual b) = nndist a b := rfl @[simp] lemma nndist_of_dual (a b : Xᵒᵈ) : nndist (of_dual a) (of_dual b) = nndist a b := rfl end instance [metric_space X] : metric_space Xᵒᵈ := ‹metric_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space Xᵒᵈ := ‹proper_space X›
4912c9d7dbba4f4050c5493ea582c233e55098cf
6e44fda625e48340c6ffc7b1109a9e3b208e5384
/src/topology/definitions.lean
bbc518681608c5ea7c55c448efd64aacfb997276
[]
no_license
JasonKYi/learn_mspaces
9f998a265b907af6be6a54061637fcf1f6d1ee9d
54083e81da420d2d362a7024a8c86bea8529fe66
refs/heads/master
1,619,008,842,896
1,609,897,382,000
1,609,897,382,000
249,780,600
5
0
null
null
null
null
UTF-8
Lean
false
false
3,461
lean
import topology.basic namespace definitions open set variables {X : Type*} [topological_space X] variables {Y : Type*} [topological_space Y] def is_continuous (f : X → Y) : Prop := ∀ U : set Y, is_open U → is_open (f ⁻¹' U) def is_continuous_at (f : X → Y) (x : X) : Prop := ∀ U : set Y, f x ∈ U → is_open U → is_open (f ⁻¹' U) structure topological_space_equiv (X Y) [topological_space X] [topological_space Y] extends X ≃ Y := (contin : is_continuous to_fun) (inv_contin : is_continuous inv_fun) notation X ` ≃* ` Y := topological_space_equiv X Y /- We define the notion of being closed and the closure similar to how we defined it for metric spaces: its complemnet is open and the smallest closed set containing the set. We will use mathlib's definition -/ /- We also define limit points for topological spaces similarly -/ def limit_points (U : set X) := {x : X | ∀ U' : set X, is_open U' → x ∈ U' → U' ∩ U ≠ ∅} /- The interior of a set U is defined to be the uninon of all open sets smaller than U thats open -/ /- A point x is an interior point of a set U if there exist an open set Nₓ, x ∈ Nₓ and Nₓ ⊆ U -/ def interior_points (U : set X) := {x : X | ∃ (U' : set X) (h₀ : is_open U') (h₁ : U' ⊆ U), x ∈ U'} /- We consider convergence in topological spaces. We say as sequence xₙ : ℕ → X converges to some x ∈ X iff. for all open U containing x, there exists some N ∈ ℕ, for all n ≥ N, xₙ ∈ U -/ def converge_to (x : ℕ → X) (l : X) := ∀ (U : set X) (h : is_open U), l ∈ U → ∃ N : ℕ, ∀ n ≥ N, x n ∈ U /- Creating a coercion between the a set of A to a set of X where A ⊆ X. -/ instance {A : set X} : has_coe (set A) (set X) := ⟨λ S, subtype.val '' S⟩ /- We create the natrual definition of the subspace of a topological space with the subspace topology -/ instance {A : set X} : topological_space A := { is_open := λ U, ∃ (V : set X) (H : is_open V), A ∩ V = U, is_open_univ := begin refine ⟨univ, is_open_univ, _⟩, rw [univ_subtype, inter_univ], ext, split; intro ha, have : (⟨x, ha⟩ : A) ∈ ⋃ (x : X) (h : x ∈ A), ({⟨x, h⟩} : set A), finish, refine ⟨_, this, rfl⟩, rcases ha with ⟨x, hx, rfl⟩, rw mem_Union at hx, cases hx with i hi, rw mem_Union at hi, cases hi with ha hx, rw mem_singleton_iff at hx, rw hx, exact ha, end, is_open_inter := begin rintro s t ⟨Vₛ, hs, hcaps⟩ ⟨Vₜ, ht, hcapt⟩, refine ⟨Vₛ ∩ Vₜ, is_open_inter hs ht, _⟩, rw [show (((s ∩ t : set A) : set X) = (s : set X) ∩ t), by {ext, split; tidy}, ← hcaps, ← hcapt], ext, split; tidy, end, is_open_sUnion := begin rintro s hs, sorry end } /- We define the natural mapping between a subspace to the whole space (inclusion map) -/ def inclusion_map (A : set X) : A → X := λ x, x notation `𝒾 ` A := inclusion_map A /- A topological space is called Hausdorff iff. for all x, y in X, there exists U, V ⊆ X, such that x ∈ U, y ∈ V and U V are disjoint -/ def is_Hausdorff (X : Type*) [topological_space X] := ∀ x y : X, x ≠ y → ∃ (U V : set X) (hU : is_open U) (hV : is_open V) (hx : x ∈ U) (hy : y ∈ V), U ∩ V = ∅ attribute [reducible] limit_points interior_points is_Hausdorff end definitions
abba90ca42e2b4d7b415413f6d6f911b95873e2e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/filter/partial.lean
2abe4b83c2d33860a051da9b65af419901d93ed0
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,877
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import order.filter.basic import data.pfun /-! # `tendsto` for relations and partial functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file generalizes `filter` definitions from functions to partial functions and relations. ## Considering functions and partial functions as relations A function `f : α → β` can be considered as the relation `rel α β` which relates `x` and `f x` for all `x`, and nothing else. This relation is called `function.graph f`. A partial function `f : α →. β` can be considered as the relation `rel α β` which relates `x` and `f x` for all `x` for which `f x` exists, and nothing else. This relation is called `pfun.graph' f`. In this regard, a function is a relation for which every element in `α` is related to exactly one element in `β` and a partial function is a relation for which every element in `α` is related to at most one element in `β`. This file leverages this analogy to generalize `filter` definitions from functions to partial functions and relations. ## Notes `set.preimage` can be generalized to relations in two ways: * `rel.preimage` returns the image of the set under the inverse relation. * `rel.core` returns the set of elements that are only related to those in the set. Both generalizations are sensible in the context of filters, so `filter.comap` and `filter.tendsto` get two generalizations each. We first take care of relations. Then the definitions for partial functions are taken as special cases of the definitions for relations. -/ universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} open_locale filter /-! ### Relations -/ /-- The forward map of a filter under a relation. Generalization of `filter.map` to relations. Note that `rel.core` generalizes `set.preimage`. -/ def rmap (r : rel α β) (l : filter α) : filter β := { sets := {s | r.core s ∈ l}, univ_sets := by simp, sets_of_superset := λ s t hs st, mem_of_superset hs $ rel.core_mono _ st, inter_sets := λ s t hs ht, by simp [rel.core_inter, inter_mem hs ht] } theorem rmap_sets (r : rel α β) (l : filter α) : (l.rmap r).sets = r.core ⁻¹' l.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.rfl @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ /-- Generic "limit of a relation" predicate. `rtendsto r l₁ l₂` asserts that for every `l₂`-neighborhood `a`, the `r`-core of `a` is an `l₁`-neighborhood. One generalization of `filter.tendsto` to relations. -/ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.rfl /-- One way of taking the inverse map of a filter under a relation. One generalization of `filter.comap` to relations. Note that `rel.core` generalizes `set.preimage`. -/ def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem, set.subset_univ _⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, (r.core_inter a' b').subset.trans (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.rfl⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_rcomap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → r.core s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, { exact λ h s t tl₂, mem_of_superset (h t tl₂) }, { exact λ h t tl₂, h _ t tl₂ set.subset.rfl } end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satisfying the lhs may be empty. /-- One way of taking the inverse map of a filter under a relation. Generalization of `filter.comap` to relations. -/ def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem, set.subset_univ _⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, (@rel.preimage_inter _ _ r _ _).trans (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, r.preimage t ⊆ s := iff.rfl theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter.ext $ λ t, begin simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintro ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, (rel.preimage_mono _ hv).trans h⟩ }, rintro ⟨t, tsets, ht⟩, exact ⟨s.preimage t, ⟨t, tsets, set.subset.rfl⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ /-- Generic "limit of a relation" predicate. `rtendsto' r l₁ l₂` asserts that for every `l₂`-neighborhood `a`, the `r`-preimage of `a` is an `l₁`-neighborhood. One generalization of `filter.tendsto` to relations. -/ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto' rcomap', simp [le_def, rel.mem_image], split, { exact λ h s hs, h _ _ hs set.subset.rfl }, { exact λ h s t ht, mem_of_superset (h t ht) } end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /-! ### Partial functions -/ /-- The forward map of a filter under a partial function. Generalization of `filter.map` to partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.rfl /-- Generic "limit of a partial function" predicate. `ptendsto r l₁ l₂` asserts that for every `l₂`-neighborhood `a`, the `p`-core of `a` is an `l₁`-neighborhood. One generalization of `filter.tendsto` to partial function. -/ def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.rfl theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.rfl theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ 𝓟 s) := begin ext t, simp only [pfun.core_res, mem_pmap, mem_map, mem_inf_principal, imp_iff_not_or], refl end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ 𝓟 s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } /-- Inverse map of a filter under a partial function. One generalization of `filter.comap` to partial functions. -/ def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l /-- Generic "limit of a partial function" predicate. `ptendsto' r l₁ l₂` asserts that for every `l₂`-neighborhood `a`, the `p`-preimage of `a` is an `l₁`-neighborhood. One generalization of `filter.tendsto` to partial functions. -/ def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], exact λ h s sl₂, mem_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], intros h' s sl₂, rw pfun.preimage_eq, exact inter_mem (h' s sl₂) h end end filter
bc6096cb1db78e8727346cfc07981bb111b76fca
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/power_basis.lean
8cb2b73074fd17e2e688ceac34905dc060bfcdd2
[ "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
20,274
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.minpoly.field /-! # Power basis > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a structure `power_basis R S`, giving a basis of the `R`-algebra `S` as a finite list of powers `1, x, ..., x^n`. For example, if `x` is algebraic over a ring/field, adjoining `x` gives a `power_basis` structure generated by `x`. ## Definitions * `power_basis R A`: a structure containing an `x` and an `n` such that `1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module). * `finrank (hf : f ≠ 0) : finite_dimensional.finrank K (adjoin_root f) = f.nat_degree`, the dimension of `adjoin_root f` equals the degree of `f` * `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y` * `power_basis.equiv`: if two power bases satisfy the same equations, they are equivalent as algebras ## Implementation notes Throughout this file, `R`, `S`, `A`, `B` ... are `comm_ring`s, and `K`, `L`, ... are `field`s. `S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra. ## Tags power basis, powerbasis -/ open polynomial open_locale polynomial variables {R S T : Type*} [comm_ring R] [ring S] [algebra R S] variables {A B : Type*} [comm_ring A] [comm_ring B] [is_domain B] [algebra A B] variables {K : Type*} [field K] /-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)` is a basis for the `R`-algebra `S` (viewed as `R`-module). This is a structure, not a class, since the same algebra can have many power bases. For the common case where `S` is defined by adjoining an integral element to `R`, the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`. -/ @[nolint has_nonempty_instance] structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] := (gen : S) (dim : ℕ) (basis : basis (fin dim) R S) (basis_eq_pow : ∀ i, basis i = gen ^ (i : ℕ)) -- this is usually not needed because of `basis_eq_pow` but can be needed in some cases; -- in such circumstances, add it manually using `@[simps dim gen basis]`. initialize_simps_projections power_basis (-basis) namespace power_basis @[simp] lemma coe_basis (pb : power_basis R S) : ⇑pb.basis = λ (i : fin pb.dim), pb.gen ^ (i : ℕ) := funext pb.basis_eq_pow /-- Cannot be an instance because `power_basis` cannot be a class. -/ lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S := finite_dimensional.of_fintype_basis pb.basis lemma finrank [algebra K S] (pb : power_basis K S) : finite_dimensional.finrank K S = pb.dim := by rw [finite_dimensional.finrank_eq_card_basis pb.basis, fintype.card_fin] lemma mem_span_pow' {x y : S} {d : ℕ} : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : R[X], f.degree < d ∧ y = aeval x f := begin have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d), { ext n, simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range], exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ }, simp only [this, finsupp.mem_span_image_iff_total, degree_lt_iff_coeff_zero, exists_iff_exists_finsupp, coeff, aeval, eval₂_ring_hom', eval₂_eq_sum, polynomial.sum, support, finsupp.mem_supported', finsupp.total, finsupp.sum, algebra.smul_def, eval₂_zero, exists_prop, linear_map.id_coe, eval₂_one, id.def, not_lt, finsupp.coe_lsum, linear_map.coe_smul_right, finset.mem_range, alg_hom.coe_mk, finset.mem_coe], simp_rw [@eq_comm _ y], exact iff.rfl end lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : R[X], f.nat_degree < d ∧ y = aeval x f := begin rw mem_span_pow', split; { rintros ⟨f, h, hy⟩, refine ⟨f, _, hy⟩, by_cases hf : f = 0, { simp only [hf, nat_degree_zero, degree_zero] at h ⊢, exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_coe d }, simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h }, end lemma dim_ne_zero [h : nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 := λ h, not_nonempty_iff.mpr (h.symm ▸ fin.is_empty : is_empty (fin pb.dim)) pb.basis.index_nonempty lemma dim_pos [nontrivial S] (pb : power_basis R S) : 0 < pb.dim := nat.pos_of_ne_zero pb.dim_ne_zero lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) : ∃ f : R[X], f.nat_degree < pb.dim ∧ y = aeval pb.gen f := (mem_span_pow pb.dim_ne_zero).mp (by simpa using pb.basis.mem_span y) lemma exists_eq_aeval' (pb : power_basis R S) (y : S) : ∃ f : R[X], y = aeval pb.gen f := begin nontriviality S, obtain ⟨f, _, hf⟩ := exists_eq_aeval pb y, exact ⟨f, hf⟩ end lemma alg_hom_ext {S' : Type*} [semiring S'] [algebra R S'] (pb : power_basis R S) ⦃f g : S →ₐ[R] S'⦄ (h : f pb.gen = g pb.gen) : f = g := begin ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, rw [← polynomial.aeval_alg_hom_apply, ← polynomial.aeval_alg_hom_apply, h] end section minpoly open_locale big_operators variable [algebra A S] /-- `pb.minpoly_gen` is the minimal polynomial for `pb.gen`. -/ noncomputable def minpoly_gen (pb : power_basis A S) : A[X] := X ^ pb.dim - ∑ (i : fin pb.dim), C (pb.basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ) lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 := begin simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow, aeval_C, ← algebra.smul_def, aeval_X], refine sub_eq_zero.mpr ((pb.basis.total_repr (pb.gen ^ pb.dim)).symm.trans _), rw [finsupp.total_apply, finsupp.sum_fintype]; simp only [pb.coe_basis, zero_smul, eq_self_iff_true, implies_true_iff] end lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) := begin nontriviality A, apply (monic_X_pow _).sub_of_left _, rw degree_X_pow, exact degree_sum_fin_lt _ end lemma dim_le_nat_degree_of_root (pb : power_basis A S) {p : A[X]} (ne_zero : p ≠ 0) (root : aeval pb.gen p = 0) : pb.dim ≤ p.nat_degree := begin refine le_of_not_lt (λ hlt, ne_zero _), rw [p.as_sum_range' _ hlt, finset.sum_range], refine fintype.sum_eq_zero _ (λ i, _), simp_rw [aeval_eq_sum_range' hlt, finset.sum_range, ← pb.basis_eq_pow] at root, have := fintype.linear_independent_iff.1 pb.basis.linear_independent _ root, dsimp only at this, rw [this, monomial_zero_right], end lemma dim_le_degree_of_root (h : power_basis A S) {p : A[X]} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : ↑h.dim ≤ p.degree := by { rw [degree_eq_nat_degree ne_zero, with_bot.coe_le_coe], exact h.dim_le_nat_degree_of_root ne_zero root } lemma degree_minpoly_gen [nontrivial A] (pb : power_basis A S) : degree (minpoly_gen pb) = pb.dim := begin unfold minpoly_gen, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, apply degree_sum_fin_lt end lemma nat_degree_minpoly_gen [nontrivial A] (pb : power_basis A S) : nat_degree (minpoly_gen pb) = pb.dim := nat_degree_eq_of_degree_eq_some pb.degree_minpoly_gen @[simp] lemma minpoly_gen_eq (pb : power_basis A S) : pb.minpoly_gen = minpoly A pb.gen := begin nontriviality A, refine minpoly.unique' A _ pb.minpoly_gen_monic pb.aeval_minpoly_gen (λ q hq, or_iff_not_imp_left.2 $ λ hn0 h0, _), exact (pb.dim_le_degree_of_root hn0 h0).not_lt (pb.degree_minpoly_gen ▸ hq), end lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen := ⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩ @[simp] lemma degree_minpoly [nontrivial A] (pb : power_basis A S) : degree (minpoly A pb.gen) = pb.dim := by rw [← minpoly_gen_eq, degree_minpoly_gen] @[simp] lemma nat_degree_minpoly [nontrivial A] (pb : power_basis A S) : (minpoly A pb.gen).nat_degree = pb.dim := by rw [← minpoly_gen_eq, nat_degree_minpoly_gen] protected lemma left_mul_matrix (pb : power_basis A S) : algebra.left_mul_matrix pb.basis pb.gen = matrix.of (λ i j, if ↑j + 1 = pb.dim then -pb.minpoly_gen.coeff ↑i else if ↑i = ↑j + 1 then 1 else 0) := begin casesI subsingleton_or_nontrivial A, { apply subsingleton.elim }, rw [algebra.left_mul_matrix_apply, ← linear_equiv.eq_symm_apply, linear_map.to_matrix_symm], refine pb.basis.ext (λ k, _), simp_rw [matrix.to_lin_self, matrix.of_apply, pb.basis_eq_pow], apply (pow_succ _ _).symm.trans, split_ifs with h h, { simp_rw [h, neg_smul, finset.sum_neg_distrib, eq_neg_iff_add_eq_zero], convert pb.aeval_minpoly_gen, rw [add_comm, aeval_eq_sum_range, finset.sum_range_succ, ← leading_coeff, pb.minpoly_gen_monic.leading_coeff, one_smul, nat_degree_minpoly_gen, finset.sum_range] }, { rw [fintype.sum_eq_single (⟨↑k + 1, lt_of_le_of_ne k.2 h⟩ : fin pb.dim), if_pos, one_smul], { refl }, { refl }, intros x hx, rw [if_neg, zero_smul], apply mt fin.ext hx }, end end minpoly section equiv variables [algebra A S] {S' : Type*} [ring S'] [algebra A S'] lemma constr_pow_aeval (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (f : A[X]) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f := begin casesI subsingleton_or_nontrivial A, { rw [(subsingleton.elim _ _ : f = 0), aeval_zero, map_zero, aeval_zero] }, rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _), ← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy], by_cases hf : f %ₘ minpoly A pb.gen = 0, { simp only [hf, alg_hom.map_zero, linear_map.map_zero] }, have : (f %ₘ minpoly A pb.gen).nat_degree < pb.dim, { rw ← pb.nat_degree_minpoly, apply nat_degree_lt_nat_degree hf, exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen) }, rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum], refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _), rw finset.mem_range at hi, rw linear_map.map_smul, congr, rw [← fin.coe_mk hi, ← pb.basis_eq_pow ⟨i, hi⟩, basis.constr_basis] end lemma constr_pow_gen (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) : pb.basis.constr A (λ i, y ^ (i : ℕ)) pb.gen = y := by { convert pb.constr_pow_aeval hy X; rw aeval_X } lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x : A) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x := by { convert pb.constr_pow_aeval hy (C x); rw aeval_C } lemma constr_pow_mul (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x x' : S) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (x * x') = pb.basis.constr A (λ i, y ^ (i : ℕ)) x * pb.basis.constr A (λ i, y ^ (i : ℕ)) x' := begin obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, obtain ⟨g, rfl⟩ := pb.exists_eq_aeval' x', simp only [← aeval_mul, pb.constr_pow_aeval hy] end /-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`, where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. See `power_basis.lift_equiv` for a bundled equiv sending `⟨y, hy⟩` to the algebra map. -/ noncomputable def lift (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : S →ₐ[A] S' := { map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one }, map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero }, map_mul' := pb.constr_pow_mul hy, commutes' := pb.constr_pow_algebra_map hy, .. pb.basis.constr A (λ i, y ^ (i : ℕ)) } @[simp] lemma lift_gen (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : pb.lift y hy pb.gen = y := pb.constr_pow_gen hy @[simp] lemma lift_aeval (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) (f : A[X]) : pb.lift y hy (aeval pb.gen f) = aeval y f := pb.constr_pow_aeval hy f /-- `pb.lift_equiv` states that roots of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. This is the bundled equiv version of `power_basis.lift`. If the codomain of the `alg_hom`s is an integral domain, then the roots form a multiset, see `lift_equiv'` for the corresponding statement. -/ @[simps] noncomputable def lift_equiv (pb : power_basis A S) : (S →ₐ[A] S') ≃ {y : S' // aeval y (minpoly A pb.gen) = 0} := { to_fun := λ f, ⟨f pb.gen, by rw [aeval_alg_hom_apply, minpoly.aeval, f.map_zero]⟩, inv_fun := λ y, pb.lift y y.2, left_inv := λ f, pb.alg_hom_ext $ lift_gen _ _ _, right_inv := λ y, subtype.ext $ lift_gen _ _ y.prop } /-- `pb.lift_equiv'` states that elements of the root set of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. -/ @[simps {fully_applied := ff}] noncomputable def lift_equiv' (pb : power_basis A S) : (S →ₐ[A] B) ≃ {y : B // y ∈ ((minpoly A pb.gen).map (algebra_map A B)).roots} := pb.lift_equiv.trans ((equiv.refl _).subtype_equiv (λ x, begin rw [mem_roots, is_root.def, equiv.refl_apply, ← eval₂_eq_eval_map, ← aeval_def], exact map_monic_ne_zero (minpoly.monic pb.is_integral_gen) end)) /-- There are finitely many algebra homomorphisms `S →ₐ[A] B` if `S` is of the form `A[x]` and `B` is an integral domain. -/ noncomputable def alg_hom.fintype (pb : power_basis A S) : fintype (S →ₐ[A] B) := by letI := classical.dec_eq B; exact fintype.of_equiv _ pb.lift_equiv'.symm /-- `pb.equiv_of_root pb' h₁ h₂` is an equivalence of algebras with the same power basis, where "the same" means that `pb` is a root of `pb'`s minimal polynomial and vice versa. See also `power_basis.equiv_of_minpoly` which takes the hypothesis that the minimal polynomials are identical. -/ @[simps apply {attrs := []}] noncomputable def equiv_of_root (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : S ≃ₐ[A] S' := alg_equiv.of_alg_hom (pb.lift pb'.gen h₂) (pb'.lift pb.gen h₁) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval' x, simp }) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval' x, simp }) @[simp] lemma equiv_of_root_aeval (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) (f : A[X]) : pb.equiv_of_root pb' h₁ h₂ (aeval pb.gen f) = aeval pb'.gen f := pb.lift_aeval _ h₂ _ @[simp] lemma equiv_of_root_gen (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : pb.equiv_of_root pb' h₁ h₂ pb.gen = pb'.gen := pb.lift_gen _ h₂ @[simp] lemma equiv_of_root_symm (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : (pb.equiv_of_root pb' h₁ h₂).symm = pb'.equiv_of_root pb h₂ h₁ := rfl /-- `pb.equiv_of_minpoly pb' h` is an equivalence of algebras with the same power basis, where "the same" means that they have identical minimal polynomials. See also `power_basis.equiv_of_root` which takes the hypothesis that each generator is a root of the other basis' minimal polynomial; `power_basis.equiv_root` is more general if `A` is not a field. -/ @[simps apply {attrs := []}] noncomputable def equiv_of_minpoly (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : S ≃ₐ[A] S' := pb.equiv_of_root pb' (h ▸ minpoly.aeval _ _) (h.symm ▸ minpoly.aeval _ _) @[simp] lemma equiv_of_minpoly_aeval (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) (f : A[X]) : pb.equiv_of_minpoly pb' h (aeval pb.gen f) = aeval pb'.gen f := pb.equiv_of_root_aeval pb' _ _ _ @[simp] lemma equiv_of_minpoly_gen (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : pb.equiv_of_minpoly pb' h pb.gen = pb'.gen := pb.equiv_of_root_gen pb' _ _ @[simp] lemma equiv_of_minpoly_symm (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : (pb.equiv_of_minpoly pb' h).symm = pb'.equiv_of_minpoly pb h.symm := rfl end equiv end power_basis open power_basis /-- Useful lemma to show `x` generates a power basis: the powers of `x` less than the degree of `x`'s minimal polynomial are linearly independent. -/ lemma linear_independent_pow [algebra K S] (x : S) : linear_independent K (λ (i : fin (minpoly K x).nat_degree), x ^ (i : ℕ)) := begin by_cases is_integral K x, swap, { rw [minpoly.eq_zero h, nat_degree_zero], exact linear_independent_empty_type }, refine fintype.linear_independent_iff.2 (λ g hg i, _), simp only at hg, simp_rw [algebra.smul_def, ← aeval_monomial, ← map_sum] at hg, apply (λ hn0, (minpoly.degree_le_of_ne_zero K x (mt (λ h0, _) hn0) hg).not_lt).mtr, { simp_rw ← C_mul_X_pow_eq_monomial, exact (degree_eq_nat_degree $ minpoly.ne_zero h).symm ▸ degree_sum_fin_lt _ }, { apply_fun lcoeff K i at h0, simp_rw [map_sum, lcoeff_apply, coeff_monomial, fin.coe_eq_coe, finset.sum_ite_eq'] at h0, exact (if_pos $ finset.mem_univ _).symm.trans h0 }, end lemma is_integral.mem_span_pow [nontrivial R] {x y : S} (hx : is_integral R x) (hy : ∃ f : R[X], y = aeval x f) : y ∈ submodule.span R (set.range (λ (i : fin (minpoly R x).nat_degree), x ^ (i : ℕ))) := begin obtain ⟨f, rfl⟩ := hy, apply mem_span_pow'.mpr _, have := minpoly.monic hx, refine ⟨f %ₘ minpoly R x, (degree_mod_by_monic_lt _ this).trans_le degree_le_nat_degree, _⟩, conv_lhs { rw ← mod_by_monic_add_div f this }, simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul] end namespace power_basis section map variables {S' : Type*} [comm_ring S'] [algebra R S'] /-- `power_basis.map pb (e : S ≃ₐ[R] S')` is the power basis for `S'` generated by `e pb.gen`. -/ @[simps dim gen basis] noncomputable def map (pb : power_basis R S) (e : S ≃ₐ[R] S') : power_basis R S' := { dim := pb.dim, basis := pb.basis.map e.to_linear_equiv, gen := e pb.gen, basis_eq_pow := λ i, by rw [basis.map_apply, pb.basis_eq_pow, e.to_linear_equiv_apply, e.map_pow] } variables [algebra A S] [algebra A S'] @[simp] lemma minpoly_gen_map (pb : power_basis A S) (e : S ≃ₐ[A] S') : (pb.map e).minpoly_gen = pb.minpoly_gen := by { dsimp only [minpoly_gen, map_dim], -- Turn `fin (pb.map e).dim` into `fin pb.dim` simp only [linear_equiv.trans_apply, map_basis, basis.map_repr, map_gen, alg_equiv.to_linear_equiv_apply, e.to_linear_equiv_symm, alg_equiv.map_pow, alg_equiv.symm_apply_apply, sub_right_inj] } @[simp] lemma equiv_of_root_map (pb : power_basis A S) (e : S ≃ₐ[A] S') (h₁ h₂) : pb.equiv_of_root (pb.map e) h₁ h₂ = e := by { ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, simp [aeval_alg_equiv] } @[simp] lemma equiv_of_minpoly_map (pb : power_basis A S) (e : S ≃ₐ[A] S') (h : minpoly A pb.gen = minpoly A (pb.map e).gen) : pb.equiv_of_minpoly (pb.map e) h = e := pb.equiv_of_root_map _ _ _ end map section adjoin open algebra lemma adjoin_gen_eq_top (B : power_basis R S) : adjoin R ({B.gen} : set S) = ⊤ := begin rw [← to_submodule_eq_top, _root_.eq_top_iff, ← B.basis.span_eq, submodule.span_le], rintros x ⟨i, rfl⟩, rw [B.basis_eq_pow i], exact subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton _)) _, end lemma adjoin_eq_top_of_gen_mem_adjoin {B : power_basis R S} {x : S} (hx : B.gen ∈ adjoin R ({x} : set S)) : adjoin R ({x} : set S) = ⊤ := begin rw [_root_.eq_top_iff, ← B.adjoin_gen_eq_top], refine adjoin_le _, simp [hx], end end adjoin end power_basis
23bceb6a737c525fe01c10a3bf5f5dba0a53b74e
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/MonadEnv.lean
6b59769fa27221ca10b5bd69af1c2a528a34f379
[ "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
4,378
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.Environment import Lean.Exception namespace Lean section Methods variables {m : Type → Type} [MonadEnv m] def setEnv (env : Environment) : m Unit := modifyEnv fun _ => env @[inline] def withoutModifyingEnv [Monad m] [MonadFinally m] {α : Type} (x : m α) : m α := do env ← getEnv; finally x (setEnv env) @[inline] def matchConst [Monad m] {α : Type} (e : Expr) (failK : Unit → m α) (k : ConstantInfo → List Level → m α) : m α := do match e with | Expr.const constName us _ => do env ← getEnv; match env.find? constName with | some cinfo => k cinfo us | none => failK () | _ => failK () @[inline] def matchConstInduct [Monad m] {α : Type} (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.inductInfo val => k val us | _ => failK () @[inline] def matchConstCtor [Monad m] {α : Type} (e : Expr) (failK : Unit → m α) (k : ConstructorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.ctorInfo val => k val us | _ => failK () @[inline] def matchConstRec [Monad m] {α : Type} (e : Expr) (failK : Unit → m α) (k : RecursorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.recInfo val => k val us | _ => failK () section variables [Monad m] def hasConst (constName : Name) : m Bool := do env ← getEnv; pure $ env.contains constName private partial def mkAuxNameAux (env : Environment) (base : Name) : Nat → Name | i => let candidate := base.appendIndexAfter i; if env.contains candidate then mkAuxNameAux (i+1) else candidate def mkAuxName (baseName : Name) (idx : Nat) : m Name := do env ← getEnv; pure $ mkAuxNameAux env baseName idx variables [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] def getConstInfo (constName : Name) : m ConstantInfo := do env ← getEnv; match env.find? constName with | some info => pure info | none => throwError ("unknown constant '" ++ constName ++ "'") def getConstInfoInduct (constName : Name) : m InductiveVal := do info ← getConstInfo constName; match info with | ConstantInfo.inductInfo v => pure v | _ => throwError ("'" ++ constName ++ "' is not a inductive type") def getConstInfoCtor (constName : Name) : m ConstructorVal := do info ← getConstInfo constName; match info with | ConstantInfo.ctorInfo v => pure v | _ => throwError ("'" ++ constName ++ "' is not a constructor") def getConstInfoRec (constName : Name) : m RecursorVal := do info ← getConstInfo constName; match info with | ConstantInfo.recInfo v => pure v | _ => throwError ("'" ++ constName ++ "' is not a recursor") @[inline] def matchConstStruct {α : Type} (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → ConstructorVal → m α) : m α := matchConstInduct e failK fun ival us => if ival.isRec then failK () else match ival.ctors with | [ctor] => do ctorInfo ← getConstInfo ctor; match ctorInfo with | ConstantInfo.ctorInfo cval => k ival us cval | _ => failK () | _ => failK () def addDecl [MonadOptions m] (decl : Declaration) : m Unit := do env ← getEnv; match env.addDecl decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def compileDecl [MonadOptions m] (decl : Declaration) : m Unit := do env ← getEnv; opts ← getOptions; match env.compileDecl opts decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def addAndCompile [MonadOptions m] (decl : Declaration) : m Unit := do addDecl decl; compileDecl decl variables [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] unsafe def evalConst (α) (constName : Name) : m α := do env ← getEnv; ofExcept $ env.evalConst α constName unsafe def evalConstCheck (α) (typeName : Name) (constName : Name) : m α := do env ← getEnv; ofExcept $ env.evalConstCheck α typeName constName end end Methods end Lean
17a8743cf2e4c061e530d8687a1406d18f795d28
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/disjoint.lean
bdff98cb1479d2100e28702ea853120c8786e8e6
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
18,148
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.bounded_order /-! # Disjointness and complements > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `disjoint`, `codisjoint`, and the `is_compl` predicate. ## Main declarations * `disjoint x y`: two elements of a lattice are disjoint if their `inf` is the bottom element. * `codisjoint x y`: two elements of a lattice are codisjoint if their `join` is the top element. * `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non distributive lattice, an element can have several complements. * `complemented_lattice α`: Typeclass stating that any element of a lattice has a complement. -/ variable {α : Type*} section disjoint section partial_order_bot variables [partial_order α] [order_bot α] {a b c d : α} /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) Note that we define this without reference to `⊓`, as this allows us to talk about orders where the infimum is not unique, or where implementing `has_inf` would require additional `decidable` arguments. -/ def disjoint (a b : α) : Prop := ∀ ⦃x⦄, x ≤ a → x ≤ b → x ≤ ⊥ lemma disjoint.comm : disjoint a b ↔ disjoint b a := forall_congr $ λ _, forall_swap @[symm] lemma disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm @[simp] lemma disjoint_bot_left : disjoint ⊥ a := λ x hbot ha, hbot @[simp] lemma disjoint_bot_right : disjoint a ⊥ := λ x ha hbot, hbot lemma disjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := λ h x ha hc, h (ha.trans h₁) (hc.trans h₂) lemma disjoint.mono_left (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h le_rfl lemma disjoint.mono_right : b ≤ c → disjoint a c → disjoint a b := disjoint.mono le_rfl @[simp] lemma disjoint_self : disjoint a a ↔ a = ⊥ := ⟨λ hd, bot_unique $ hd le_rfl le_rfl, λ h x ha hb, ha.trans_eq h⟩ /- TODO: Rename `disjoint.eq_bot` to `disjoint.inf_eq` and `disjoint.eq_bot_of_self` to `disjoint.eq_bot` -/ alias disjoint_self ↔ disjoint.eq_bot_of_self _ lemma disjoint.ne (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := λ h, ha $ disjoint_self.1 $ by rwa ←h at hab lemma disjoint.eq_bot_of_le (hab : disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 $ hab le_rfl h lemma disjoint.eq_bot_of_ge (hab : disjoint a b) : b ≤ a → b = ⊥ := hab.symm.eq_bot_of_le end partial_order_bot section partial_bounded_order variables [partial_order α] [bounded_order α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := ⟨λ h, bot_unique $ h le_rfl le_top, λ h x ha htop, ha.trans_eq h⟩ @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := ⟨λ h, bot_unique $ h le_top le_rfl, λ h x htop ha, ha.trans_eq h⟩ end partial_bounded_order section semilattice_inf_bot variables [semilattice_inf α] [order_bot α] {a b c d : α} lemma disjoint_iff_inf_le : disjoint a b ↔ a ⊓ b ≤ ⊥ := ⟨λ hd, hd inf_le_left inf_le_right, λ h x ha hb, (le_inf ha hb).trans h⟩ lemma disjoint_iff : disjoint a b ↔ a ⊓ b = ⊥ := disjoint_iff_inf_le.trans le_bot_iff lemma disjoint.le_bot : disjoint a b → a ⊓ b ≤ ⊥ := disjoint_iff_inf_le.mp lemma disjoint.eq_bot : disjoint a b → a ⊓ b = ⊥ := bot_unique ∘ disjoint.le_bot lemma disjoint_assoc : disjoint (a ⊓ b) c ↔ disjoint a (b ⊓ c) := by rw [disjoint_iff_inf_le, disjoint_iff_inf_le, inf_assoc] lemma disjoint_left_comm : disjoint a (b ⊓ c) ↔ disjoint b (a ⊓ c) := by simp_rw [disjoint_iff_inf_le, inf_left_comm] lemma disjoint_right_comm : disjoint (a ⊓ b) c ↔ disjoint (a ⊓ c) b := by simp_rw [disjoint_iff_inf_le, inf_right_comm] variables (c) lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b := h.mono_left inf_le_left lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b := h.mono_left inf_le_right lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) := h.mono_right inf_le_left lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) := h.mono_right inf_le_right variables {c} lemma disjoint.of_disjoint_inf_of_le (h : disjoint (a ⊓ b) c) (hle : a ≤ c) : disjoint a b := disjoint_iff.2 $ h.eq_bot_of_le $ inf_le_of_left_le hle lemma disjoint.of_disjoint_inf_of_le' (h : disjoint (a ⊓ b) c) (hle : b ≤ c) : disjoint a b := disjoint_iff.2 $ h.eq_bot_of_le $ inf_le_of_right_le hle end semilattice_inf_bot section distrib_lattice_bot variables [distrib_lattice α] [order_bot α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := le_of_inf_le_sup_le (le_trans hd.le_bot bot_le) $ sup_le h le_sup_right lemma disjoint.left_le_of_le_sup_left (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := hd.left_le_of_le_sup_right $ by rwa sup_comm end distrib_lattice_bot end disjoint section codisjoint section partial_order_top variables [partial_order α] [order_top α] {a b c d : α} /-- Two elements of a lattice are codisjoint if their sup is the top element. Note that we define this without reference to `⊔`, as this allows us to talk about orders where the supremum is not unique, or where implement `has_sup` would require additional `decidable` arguments. -/ def codisjoint (a b : α) : Prop := ∀ ⦃x⦄, a ≤ x → b ≤ x → ⊤ ≤ x lemma codisjoint.comm : codisjoint a b ↔ codisjoint b a := forall_congr $ λ _, forall_swap @[symm] lemma codisjoint.symm ⦃a b : α⦄ : codisjoint a b → codisjoint b a := codisjoint.comm.1 lemma symmetric_codisjoint : symmetric (codisjoint : α → α → Prop) := codisjoint.symm @[simp] lemma codisjoint_top_left : codisjoint ⊤ a := λ x htop ha, htop @[simp] lemma codisjoint_top_right : codisjoint a ⊤ := λ x ha htop, htop lemma codisjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : codisjoint a c → codisjoint b d := λ h x ha hc, h (h₁.trans ha) (h₂.trans hc) lemma codisjoint.mono_left (h : a ≤ b) : codisjoint a c → codisjoint b c := codisjoint.mono h le_rfl lemma codisjoint.mono_right : b ≤ c → codisjoint a b → codisjoint a c := codisjoint.mono le_rfl @[simp] lemma codisjoint_self : codisjoint a a ↔ a = ⊤ := ⟨λ hd, top_unique $ hd le_rfl le_rfl, λ h x ha hb, h.symm.trans_le ha⟩ /- TODO: Rename `codisjoint.eq_top` to `codisjoint.sup_eq` and `codisjoint.eq_top_of_self` to `codisjoint.eq_top` -/ alias codisjoint_self ↔ codisjoint.eq_top_of_self _ lemma codisjoint.ne (ha : a ≠ ⊤) (hab : codisjoint a b) : a ≠ b := λ h, ha $ codisjoint_self.1 $ by rwa ←h at hab lemma codisjoint.eq_top_of_le (hab : codisjoint a b) (h : b ≤ a) : a = ⊤ := eq_top_iff.2 $ hab le_rfl h lemma codisjoint.eq_top_of_ge (hab : codisjoint a b) : a ≤ b → b = ⊤ := hab.symm.eq_top_of_le end partial_order_top section partial_bounded_order variables [partial_order α] [bounded_order α] {a : α} @[simp] theorem codisjoint_bot : codisjoint a ⊥ ↔ a = ⊤ := ⟨λ h, top_unique $ h le_rfl bot_le, λ h x ha htop, h.symm.trans_le ha⟩ @[simp] theorem bot_codisjoint : codisjoint ⊥ a ↔ a = ⊤ := ⟨λ h, top_unique $ h bot_le le_rfl, λ h x htop ha, h.symm.trans_le ha⟩ end partial_bounded_order section semilattice_sup_top variables [semilattice_sup α] [order_top α] {a b c d : α} lemma codisjoint_iff_le_sup : codisjoint a b ↔ ⊤ ≤ a ⊔ b := @disjoint_iff_inf_le αᵒᵈ _ _ _ _ lemma codisjoint_iff : codisjoint a b ↔ a ⊔ b = ⊤ := @disjoint_iff αᵒᵈ _ _ _ _ lemma codisjoint.top_le : codisjoint a b → ⊤ ≤ a ⊔ b := @disjoint.le_bot αᵒᵈ _ _ _ _ lemma codisjoint.eq_top : codisjoint a b → a ⊔ b = ⊤ := @disjoint.eq_bot αᵒᵈ _ _ _ _ lemma codisjoint_assoc : codisjoint (a ⊔ b) c ↔ codisjoint a (b ⊔ c) := @disjoint_assoc αᵒᵈ _ _ _ _ _ lemma codisjoint_left_comm : codisjoint a (b ⊔ c) ↔ codisjoint b (a ⊔ c) := @disjoint_left_comm αᵒᵈ _ _ _ _ _ lemma codisjoint_right_comm : codisjoint (a ⊔ b) c ↔ codisjoint (a ⊔ c) b := @disjoint_right_comm αᵒᵈ _ _ _ _ _ variables (c) lemma codisjoint.sup_left (h : codisjoint a b) : codisjoint (a ⊔ c) b := h.mono_left le_sup_left lemma codisjoint.sup_left' (h : codisjoint a b) : codisjoint (c ⊔ a) b := h.mono_left le_sup_right lemma codisjoint.sup_right (h : codisjoint a b) : codisjoint a (b ⊔ c) := h.mono_right le_sup_left lemma codisjoint.sup_right' (h : codisjoint a b) : codisjoint a (c ⊔ b) := h.mono_right le_sup_right variables {c} lemma codisjoint.of_codisjoint_sup_of_le (h : codisjoint (a ⊔ b) c) (hle : c ≤ a) : codisjoint a b := @disjoint.of_disjoint_inf_of_le αᵒᵈ _ _ _ _ _ h hle lemma codisjoint.of_codisjoint_sup_of_le' (h : codisjoint (a ⊔ b) c) (hle : c ≤ b) : codisjoint a b := @disjoint.of_disjoint_inf_of_le' αᵒᵈ _ _ _ _ _ h hle end semilattice_sup_top section distrib_lattice_top variables [distrib_lattice α] [order_top α] {a b c : α} @[simp] lemma codisjoint_inf_left : codisjoint (a ⊓ b) c ↔ codisjoint a c ∧ codisjoint b c := by simp only [codisjoint_iff, sup_inf_right, inf_eq_top_iff] @[simp] lemma codisjoint_inf_right : codisjoint a (b ⊓ c) ↔ codisjoint a b ∧ codisjoint a c := by simp only [codisjoint_iff, sup_inf_left, inf_eq_top_iff] lemma codisjoint.inf_left (ha : codisjoint a c) (hb : codisjoint b c) : codisjoint (a ⊓ b) c := codisjoint_inf_left.2 ⟨ha, hb⟩ lemma codisjoint.inf_right (hb : codisjoint a b) (hc : codisjoint a c) : codisjoint a (b ⊓ c) := codisjoint_inf_right.2 ⟨hb, hc⟩ lemma codisjoint.left_le_of_le_inf_right (h : a ⊓ b ≤ c) (hd : codisjoint b c) : a ≤ c := @disjoint.left_le_of_le_sup_right αᵒᵈ _ _ _ _ _ h hd.symm lemma codisjoint.left_le_of_le_inf_left (h : b ⊓ a ≤ c) (hd : codisjoint b c) : a ≤ c := hd.left_le_of_le_inf_right $ by rwa inf_comm end distrib_lattice_top end codisjoint open order_dual lemma disjoint.dual [semilattice_inf α] [order_bot α] {a b : α} : disjoint a b → codisjoint (to_dual a) (to_dual b) := id lemma codisjoint.dual [semilattice_sup α] [order_top α] {a b : α} : codisjoint a b → disjoint (to_dual a) (to_dual b) := id @[simp] lemma disjoint_to_dual_iff [semilattice_sup α] [order_top α] {a b : α} : disjoint (to_dual a) (to_dual b) ↔ codisjoint a b := iff.rfl @[simp] lemma disjoint_of_dual_iff [semilattice_inf α] [order_bot α] {a b : αᵒᵈ} : disjoint (of_dual a) (of_dual b) ↔ codisjoint a b := iff.rfl @[simp] lemma codisjoint_to_dual_iff [semilattice_inf α] [order_bot α] {a b : α} : codisjoint (to_dual a) (to_dual b) ↔ disjoint a b := iff.rfl @[simp] lemma codisjoint_of_dual_iff [semilattice_sup α] [order_top α] {a b : αᵒᵈ} : codisjoint (of_dual a) (of_dual b) ↔ disjoint a b := iff.rfl section distrib_lattice variables [distrib_lattice α] [bounded_order α] {a b c : α} lemma disjoint.le_of_codisjoint (hab : disjoint a b) (hbc : codisjoint b c) : a ≤ c := begin rw [←@inf_top_eq _ _ _ a, ←@bot_sup_eq _ _ _ c, ←hab.eq_bot, ←hbc.eq_top, sup_inf_right], exact inf_le_inf_right _ le_sup_left, end end distrib_lattice section is_compl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ @[protect_proj] structure is_compl [partial_order α] [bounded_order α] (x y : α) : Prop := (disjoint : disjoint x y) (codisjoint : codisjoint x y) lemma is_compl_iff [partial_order α] [bounded_order α] {a b : α} : is_compl a b ↔ disjoint a b ∧ codisjoint a b := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ namespace is_compl section bounded_partial_order variables [partial_order α] [bounded_order α] {x y z : α} @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨h.1.symm, h.2.symm⟩ lemma dual (h : is_compl x y) : is_compl (to_dual x) (to_dual y) := ⟨h.2, h.1⟩ lemma of_dual {a b : αᵒᵈ} (h : is_compl a b) : is_compl (of_dual a) (of_dual b) := ⟨h.2, h.1⟩ end bounded_partial_order section bounded_lattice variables [lattice α] [bounded_order α] {x y z : α} lemma of_le (h₁ : x ⊓ y ≤ ⊥) (h₂ : ⊤ ≤ x ⊔ y) : is_compl x y := ⟨disjoint_iff_inf_le.mpr h₁, codisjoint_iff_le_sup.mpr h₂⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨disjoint_iff.mpr h₁, codisjoint_iff.mpr h₂⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := h.codisjoint.eq_top end bounded_lattice variables [distrib_lattice α] [bounded_order α] {a b x y z : α} lemma inf_left_le_of_le_sup_right (h : is_compl x y) (hle : a ≤ b ⊔ y) : a ⊓ x ≤ b := calc a ⊓ x ≤ (b ⊔ y) ⊓ x : inf_le_inf hle le_rfl ... = (b ⊓ x) ⊔ (y ⊓ x) : inf_sup_right ... = b ⊓ x : by rw [h.symm.inf_eq_bot, sup_bot_eq] ... ≤ b : inf_le_left lemma le_sup_right_iff_inf_left_le {a b} (h : is_compl x y) : a ≤ b ⊔ y ↔ a ⊓ x ≤ b := ⟨h.inf_left_le_of_le_sup_right, h.symm.dual.inf_left_le_of_le_sup_right⟩ lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := by rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq] lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := by { rw disjoint_iff, exact h.inf_left_eq_bot_iff } lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := h.disjoint_right_iff.symm lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ codisjoint z y := h.dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ codisjoint z x := h.symm.left_le_iff protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ h.symm.codisjoint.mono_right hx lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl namespace prod variables {β : Type*} [partial_order α] [partial_order β] protected lemma disjoint_iff [order_bot α] [order_bot β] {x y : α × β} : disjoint x y ↔ disjoint x.1 y.1 ∧ disjoint x.2 y.2 := begin split, { intros h, refine ⟨λ a hx hy, (@h (a, ⊥) ⟨hx, _⟩ ⟨hy, _⟩).1, λ b hx hy, (@h (⊥, b) ⟨_, hx⟩ ⟨_, hy⟩).2⟩, all_goals { exact bot_le }, }, { rintros ⟨ha, hb⟩ z hza hzb, refine ⟨ha hza.1 hzb.1, hb hza.2 hzb.2⟩ }, end protected lemma codisjoint_iff [order_top α] [order_top β] {x y : α × β} : codisjoint x y ↔ codisjoint x.1 y.1 ∧ codisjoint x.2 y.2 := @prod.disjoint_iff αᵒᵈ βᵒᵈ _ _ _ _ _ _ protected lemma is_compl_iff [bounded_order α] [bounded_order β] {x y : α × β} : is_compl x y ↔ is_compl x.1 y.1 ∧ is_compl x.2 y.2 := by simp_rw [is_compl_iff, prod.disjoint_iff, prod.codisjoint_iff, and_and_and_comm] end prod section variables [lattice α] [bounded_order α] {a b x : α} @[simp] lemma is_compl_to_dual_iff : is_compl (to_dual a) (to_dual b) ↔ is_compl a b := ⟨is_compl.of_dual, is_compl.dual⟩ @[simp] lemma is_compl_of_dual_iff {a b : αᵒᵈ} : is_compl (of_dual a) (of_dual b) ↔ is_compl a b := ⟨is_compl.dual, is_compl.of_dual⟩ lemma is_compl_bot_top : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ := sup_bot_eq.symm.trans h.sup_eq_top lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ := eq_top_of_is_compl_bot h.symm lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ := eq_top_of_is_compl_bot h.dual lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ := eq_top_of_bot_is_compl h.dual end /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class complemented_lattice (α) [lattice α] [bounded_order α] : Prop := (exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b) export complemented_lattice (exists_is_compl) namespace complemented_lattice variables [lattice α] [bounded_order α] [complemented_lattice α] instance : complemented_lattice αᵒᵈ := ⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.dual⟩⟩ end complemented_lattice end is_compl
5b8663069c85d34fc069a1a120cc2c2c0f813a70
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/uintCtors.lean
dc4ddf7407eb24ef0273786a0639247ee11fb50a
[ "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,399
lean
def UInt32.ofNatCore' (n : Nat) (h : n < UInt32.size) : UInt32 := { val := { val := n, isLt := h } } #eval UInt32.ofNatCore' 10 (by decide) def UInt64.ofNatCore' (n : Nat) (h : n < UInt64.size) : UInt64 := { val := { val := n, isLt := h } } #eval UInt64.ofNatCore' 3 (by decide) #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt8 } #eval (3 : UInt8).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt16 } #eval (3 : UInt16).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt32 } #eval (3 : UInt32).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt64 } #eval (3 : UInt64).val #eval toString $ { val := { val := 3, isLt := (match USize.size, usize_size_eq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (3 : USize).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt8 } #eval (4 : UInt8).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt16 } #eval (4 : UInt16).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt32 } #eval (4 : UInt32).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt64 } #eval (4 : UInt64).val #eval toString $ { val := { val := 4, isLt := (match USize.size, usize_size_eq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (4 : USize).val
668471f18535e79b31b480ef86cc7f8aff490d25
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/variables.lean
11e8a58c8bf278b744a4fc1c09df3be9e2692978
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
16,019
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, Johan Commelin, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.monad import Mathlib.data.set.disjointed import Mathlib.PostPort universes u u_1 u_2 v u_3 namespace Mathlib /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ namespace mv_polynomial /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : multiset σ := finset.sup (finsupp.support p) fun (s : σ →₀ ℕ) => coe_fn finsupp.to_multiset s theorem degrees_monomial {R : Type u} {σ : Type u_1} [comm_semiring R] (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ coe_fn finsupp.to_multiset s := sorry theorem degrees_monomial_eq {R : Type u} {σ : Type u_1} [comm_semiring R] (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = coe_fn finsupp.to_multiset s := sorry theorem degrees_C {R : Type u} {σ : Type u_1} [comm_semiring R] (a : R) : degrees (coe_fn C a) = 0 := iff.mp multiset.le_zero (degrees_monomial 0 a) theorem degrees_X' {R : Type u} {σ : Type u_1} [comm_semiring R] (n : σ) : degrees (X n) ≤ singleton n := le_trans (degrees_monomial (finsupp.single n 1) 1) (le_of_eq (finsupp.to_multiset_single n 1)) @[simp] theorem degrees_X {R : Type u} {σ : Type u_1} [comm_semiring R] [nontrivial R] (n : σ) : degrees (X n) = singleton n := Eq.trans (degrees_monomial_eq (finsupp.single n 1) 1 one_ne_zero) (finsupp.to_multiset_single n 1) @[simp] theorem degrees_zero {R : Type u} {σ : Type u_1} [comm_semiring R] : degrees 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (degrees 0 = 0)) (Eq.symm C_0))) (degrees_C 0) @[simp] theorem degrees_one {R : Type u} {σ : Type u_1} [comm_semiring R] : degrees 1 = 0 := degrees_C 1 theorem degrees_add {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) : degrees (p + q) ≤ degrees p ⊔ degrees q := sorry theorem degrees_sum {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} (s : finset ι) (f : ι → mv_polynomial σ R) : degrees (finset.sum s fun (i : ι) => f i) ≤ finset.sup s fun (i : ι) => degrees (f i) := sorry theorem degrees_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) : degrees (p * q) ≤ degrees p + degrees q := sorry theorem degrees_prod {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} (s : finset ι) (f : ι → mv_polynomial σ R) : degrees (finset.prod s fun (i : ι) => f i) ≤ finset.sum s fun (i : ι) => degrees (f i) := sorry theorem degrees_pow {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (n : ℕ) : degrees (p ^ n) ≤ n •ℕ degrees p := sorry theorem mem_degrees {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} {i : σ} : i ∈ degrees p ↔ ∃ (d : σ →₀ ℕ), coeff d p ≠ 0 ∧ i ∈ finsupp.support d := sorry theorem le_degrees_add {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} {q : mv_polynomial σ R} (h : multiset.disjoint (degrees p) (degrees q)) : degrees p ≤ degrees (p + q) := sorry theorem degrees_add_of_disjoint {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} {q : mv_polynomial σ R} (h : multiset.disjoint (degrees p) (degrees q)) : degrees (p + q) = degrees p ∪ degrees q := sorry theorem degrees_map {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : degrees (coe_fn (map f) p) ⊆ degrees p := sorry theorem degrees_rename {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → τ) (φ : mv_polynomial σ R) : degrees (coe_fn (rename f) φ) ⊆ multiset.map f (degrees φ) := sorry theorem degrees_map_of_injective {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : function.injective ⇑f) : degrees (coe_fn (map f) p) = degrees p := sorry /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : finset σ := multiset.to_finset (degrees p) @[simp] theorem vars_0 {R : Type u} {σ : Type u_1} [comm_semiring R] : vars 0 = ∅ := eq.mpr (id (Eq._oldrec (Eq.refl (vars 0 = ∅)) (vars.equations._eqn_1 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (multiset.to_finset (degrees 0) = ∅)) degrees_zero)) (eq.mpr (id (Eq._oldrec (Eq.refl (multiset.to_finset 0 = ∅)) multiset.to_finset_zero)) (Eq.refl ∅))) @[simp] theorem vars_monomial {R : Type u} {σ : Type u_1} {r : R} {s : σ →₀ ℕ} [comm_semiring R] (h : r ≠ 0) : vars (monomial s r) = finsupp.support s := sorry @[simp] theorem vars_C {R : Type u} {σ : Type u_1} {r : R} [comm_semiring R] : vars (coe_fn C r) = ∅ := eq.mpr (id (Eq._oldrec (Eq.refl (vars (coe_fn C r) = ∅)) (vars.equations._eqn_1 (coe_fn C r)))) (eq.mpr (id (Eq._oldrec (Eq.refl (multiset.to_finset (degrees (coe_fn C r)) = ∅)) (degrees_C r))) (eq.mpr (id (Eq._oldrec (Eq.refl (multiset.to_finset 0 = ∅)) multiset.to_finset_zero)) (Eq.refl ∅))) @[simp] theorem vars_X {R : Type u} {σ : Type u_1} {n : σ} [comm_semiring R] [nontrivial R] : vars (X n) = singleton n := sorry theorem mem_vars {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} (i : σ) : i ∈ vars p ↔ ∃ (d : σ →₀ ℕ), ∃ (H : d ∈ finsupp.support p), i ∈ finsupp.support d := sorry theorem mem_support_not_mem_vars_zero {R : Type u} {σ : Type u_1} [comm_semiring R] {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ finsupp.support f) {v : σ} (h : ¬v ∈ vars f) : coe_fn x v = 0 := sorry theorem vars_add_subset {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) : vars (p + q) ⊆ vars p ∪ vars q := sorry theorem vars_add_of_disjoint {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} {q : mv_polynomial σ R} (h : disjoint (vars p) (vars q)) : vars (p + q) = vars p ∪ vars q := sorry theorem vars_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (φ : mv_polynomial σ R) (ψ : mv_polynomial σ R) : vars (φ * ψ) ⊆ vars φ ∪ vars ψ := sorry @[simp] theorem vars_one {R : Type u} {σ : Type u_1} [comm_semiring R] : vars 1 = ∅ := vars_C theorem vars_pow {R : Type u} {σ : Type u_1} [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) : vars (φ ^ n) ⊆ vars φ := sorry /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ theorem vars_prod {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} {s : finset ι} (f : ι → mv_polynomial σ R) : vars (finset.prod s fun (i : ι) => f i) ⊆ finset.bUnion s fun (i : ι) => vars (f i) := sorry theorem vars_C_mul {σ : Type u_1} {A : Type u_3} [integral_domain A] (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : vars (coe_fn C a * φ) = vars φ := sorry theorem vars_sum_subset {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_3} (t : finset ι) (φ : ι → mv_polynomial σ R) : vars (finset.sum t fun (i : ι) => φ i) ⊆ finset.bUnion t fun (i : ι) => vars (φ i) := sorry theorem vars_sum_of_disjoint {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_3} (t : finset ι) (φ : ι → mv_polynomial σ R) (h : pairwise (disjoint on fun (i : ι) => vars (φ i))) : vars (finset.sum t fun (i : ι) => φ i) = finset.bUnion t fun (i : ι) => vars (φ i) := sorry theorem vars_map {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) [comm_semiring S] (f : R →+* S) : vars (coe_fn (map f) p) ⊆ vars p := sorry theorem vars_map_of_injective {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) [comm_semiring S] {f : R →+* S} (hf : function.injective ⇑f) : vars (coe_fn (map f) p) = vars p := sorry theorem vars_monomial_single {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : vars (monomial (finsupp.single i e) r) = singleton i := sorry theorem vars_eq_support_bUnion_support {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : vars p = finset.bUnion (finsupp.support p) finsupp.support := sorry /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of {R : Type u} {σ : Type u_1} [comm_semiring R] (n : σ) (p : mv_polynomial σ R) : ℕ := multiset.count n (degrees p) /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : ℕ := finset.sup (finsupp.support p) fun (s : σ →₀ ℕ) => finsupp.sum s fun (n : σ) (e : ℕ) => e theorem total_degree_eq {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : total_degree p = finset.sup (finsupp.support p) fun (m : σ →₀ ℕ) => coe_fn multiset.card (coe_fn finsupp.to_multiset m) := sorry theorem total_degree_le_degrees_card {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : total_degree p ≤ coe_fn multiset.card (degrees p) := eq.mpr (id (Eq._oldrec (Eq.refl (total_degree p ≤ coe_fn multiset.card (degrees p))) (total_degree_eq p))) (finset.sup_le fun (s : σ →₀ ℕ) (hs : s ∈ finsupp.support p) => multiset.card_le_of_le (finset.le_sup hs)) @[simp] theorem total_degree_C {R : Type u} {σ : Type u_1} [comm_semiring R] (a : R) : total_degree (coe_fn C a) = 0 := sorry @[simp] theorem total_degree_zero {R : Type u} {σ : Type u_1} [comm_semiring R] : total_degree 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (total_degree 0 = 0)) (Eq.symm C_0))) (total_degree_C 0) @[simp] theorem total_degree_one {R : Type u} {σ : Type u_1} [comm_semiring R] : total_degree 1 = 0 := total_degree_C 1 @[simp] theorem total_degree_X {σ : Type u_1} {R : Type u_2} [comm_semiring R] [nontrivial R] (s : σ) : total_degree (X s) = 1 := sorry theorem total_degree_add {R : Type u} {σ : Type u_1} [comm_semiring R] (a : mv_polynomial σ R) (b : mv_polynomial σ R) : total_degree (a + b) ≤ max (total_degree a) (total_degree b) := sorry theorem total_degree_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (a : mv_polynomial σ R) (b : mv_polynomial σ R) : total_degree (a * b) ≤ total_degree a + total_degree b := sorry theorem total_degree_pow {R : Type u} {σ : Type u_1} [comm_semiring R] (a : mv_polynomial σ R) (n : ℕ) : total_degree (a ^ n) ≤ n * total_degree a := sorry theorem total_degree_list_prod {R : Type u} {σ : Type u_1} [comm_semiring R] (s : List (mv_polynomial σ R)) : total_degree (list.prod s) ≤ list.sum (list.map total_degree s) := sorry theorem total_degree_multiset_prod {R : Type u} {σ : Type u_1} [comm_semiring R] (s : multiset (mv_polynomial σ R)) : total_degree (multiset.prod s) ≤ multiset.sum (multiset.map total_degree s) := sorry theorem total_degree_finset_prod {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} (s : finset ι) (f : ι → mv_polynomial σ R) : total_degree (finset.prod s f) ≤ finset.sum s fun (i : ι) => total_degree (f i) := sorry theorem exists_degree_lt {R : Type u} {σ : Type u_1} [comm_semiring R] [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : total_degree f < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ finsupp.support f) : ∃ (i : σ), coe_fn d i < n := sorry theorem coeff_eq_zero_of_total_degree_lt {R : Type u} {σ : Type u_1} [comm_semiring R] {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : total_degree f < finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) : coeff d f = 0 := sorry theorem total_degree_rename_le {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → τ) (p : mv_polynomial σ R) : total_degree (coe_fn (rename f) p) ≤ total_degree p := sorry /-! ### `vars` and `eval` -/ theorem eval₂_hom_eq_constant_coeff_of_vars {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S] (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ (i : σ), i ∈ vars p → g i = 0) : coe_fn (eval₂_hom f g) p = coe_fn f (coe_fn constant_coeff p) := sorry theorem aeval_eq_constant_coeff_of_vars {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S] [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ (i : σ), i ∈ vars p → g i = 0) : coe_fn (aeval g) p = coe_fn (algebra_map R S) (coe_fn constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars (algebra_map R S) hp theorem eval₂_hom_congr' {R : Type u} {S : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S] {f₁ : R →+* S} {f₂ : R →+* S} {g₁ : σ → S} {g₂ : σ → S} {p₁ : mv_polynomial σ R} {p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ (i : σ), i ∈ vars p₁ → i ∈ vars p₂ → g₁ i = g₂ i) → p₁ = p₂ → coe_fn (eval₂_hom f₁ g₁) p₁ = coe_fn (eval₂_hom f₂ g₂) p₂ := sorry theorem vars_bind₁ {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : vars (coe_fn (bind₁ f) φ) ⊆ finset.bUnion (vars φ) fun (i : σ) => vars (f i) := sorry theorem mem_vars_bind₁ {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ vars (coe_fn (bind₁ f) φ)) : ∃ (i : σ), i ∈ vars φ ∧ j ∈ vars (f i) := sorry theorem vars_rename {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → τ) (φ : mv_polynomial σ R) : vars (coe_fn (rename f) φ) ⊆ finset.image f (vars φ) := sorry theorem mem_vars_rename {R : Type u} {σ : Type u_1} {τ : Type u_2} [comm_semiring R] (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ vars (coe_fn (rename f) φ)) : ∃ (i : σ), i ∈ vars φ ∧ f i = j := sorry
b29ec9c805e76f3abafa121a4c422e6639fc6cfc
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1968.lean
b4ebd06198a44e31f75fbac515a454430abf12ef
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,399
lean
inductive type | bv : ℕ → type | bit : type open type -- This is a "parameterized list" where `plist f types` contains -- an element of type `f tp` for each corresponding element `tp ∈ types`. inductive plist (f : type → Type) : list type → Type | nil {} : plist [] | cons {h:type} {r:list type} : f h → plist r → plist (h::r) -- Operations on values; the first argument contains the types of -- inputs, and the second for the return type. inductive op : list type → type → Type | neq (tp:type) : op [tp, tp] bit | mul (w:ℕ) : op [bv w, bv w] (bv w) -- Denotes expressions that evaluate to a number given a memory state and register to value map. inductive value : type → Type | const (w:ℕ) : value (bv w) | op {args:list type} {tp:type} : op args tp → plist value args → value tp --- This creates a plist (borrowed from the list notation). notation `[[[` l:(foldr `,` (h t, plist.cons h t) plist.nil) `]]]` := l open value -- This works #eval value.op (op.mul 32) [[[ const 32, const 32 ]]] -- This also works instance bv_has_mul (w:ℕ) : has_mul (value (bv w)) := ⟨λx y, value.op (op.mul w) [[[x, y]]]⟩ #eval const 32 * const 32 -- This works #eval value.op (op.neq (bv 32)) [[[ const 32, const 32 ]]] -- This returns the VM check error def neq {tp:type} (x y : value tp) : value bit := value.op (op.neq tp) [[[x, y]]] #eval neq (const 32) (const 32)
b9a1bd9fa9bfdd831a087329b8ffd9f699e8fe17
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/algebra/order.lean
51c3fd6f681f3bca1a83cd048e60335f50a4ee03
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,033
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad This ports just the min function and theorems from the lean2 library; additional functions will be ported in the future. -/ /- min -/ definition min {α : Type} [has_le α] (a b : α) [decidable (a ≤ b)] : α := if a ≤ b then a else b theorem min_eq_left {α : Type} [has_le α] {a b : α} [decidable (a ≤ b)] (H : a ≤ b) : min a b = a := if_pos H theorem min_eq_right {α : Type} [weak_order α] {x y : α} [p : decidable (x ≤ y)] (H : (y ≤ x)) : min x y = y := let q : decidable (x ≤ y) := p in match q with | is_true h := calc min x y = x : if_pos h ... = y : le_antisymm h H | is_false h := if_neg h end theorem min_self {α : Type} [has_le α] (x : α) [p : decidable (x ≤ x)] : min x x = x := let q : decidable (x ≤ x) := p in match q with | is_true h := if_pos h | is_false h := if_neg h end
f495f6591a83c644a57b55327053b5d08dec994c
9dc8cecdf3c4634764a18254e94d43da07142918
/test/measurability.lean
c7b66ea22e34579e9fc45933ef54b90f0dfd0a3f
[ "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,372
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.tactic import measure_theory.function.special_functions open_locale big_operators ennreal variables {α β : Type*} [measurable_space α] [measurable_space β] {f g : α → β} {s₁ s₂ : set α} {t₁ t₂ : set β} {μ ν : measure_theory.measure α} -- Test the use of assumption example (hf : measurable f) : measurable f := by measurability -- Test that intro does not unfold `measurable` example : measurable f → measurable f := by measurability -- Test the use of apply_assumption to get (h i) from an hypothesis (h : ∀ i, ...). example {F : ℕ → α → β} (hF : ∀ i, measurable (F i)) : measurable (F 0) := by measurability example {ι} [encodable ι] {S₁ S₂ : ι → set α} (hS₁ : ∀ i, measurable_set (S₁ i)) (hS₂ : ∀ i, measurable_set (S₂ i)) : measurable_set (⋃ i, (S₁ i) ∪ (S₂ i)) := by measurability -- Tests on sets example (hs₁ : measurable_set s₁) (hs₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₁) := by measurability example {ι} [encodable ι] {S : ι → set α} (hs : ∀ i, measurable_set (S i)) : measurable_set (⋃ i, S i) := by measurability example (hf : measurable f) (hs₁ : measurable_set s₁) (ht₂ : measurable_set t₂) : measurable_set ((f ⁻¹' t₂) ∩ s₁) := by measurability /-- `ℝ` is a good test case because it verifies many assumptions, hence many lemmas apply and we are more likely to detect a bad lemma. In a previous version of the tactic, `measurability` got stuck trying to apply `set.finite.measurable_set` here. -/ example {a b : ℝ} : measurable_set (set.Icc a b) := by measurability -- Tests on functions example [has_mul β] [has_measurable_mul₂ β] (hf : measurable f) (c : β) : measurable (λ x, c * f x) := by measurability -- uses const_mul, not mul example [has_add β] [has_measurable_add₂ β] (hf : measurable f) (hg : measurable g) : measurable (λ x, f x + g x) := by measurability example [has_add β] [has_measurable_add₂ β] (hf : measurable f) (hg : ae_measurable g μ) : ae_measurable (λ x, f x + g x) μ := by measurability example [has_div β] [has_measurable_div₂ β] (hf : measurable f) (hg : measurable g) (ht : measurable_set t₂): measurable_set ((λ x, f x / g x) ⁻¹' t₂) := by measurability example [add_comm_monoid β] [has_measurable_add₂ β] {s : finset ℕ} {F : ℕ → α → β} (hF : ∀ i, ae_measurable (F i) μ) : ae_measurable (∑ i in s, (λ x, F (i+1) x + F i x)) μ := by measurability -- even with many assumptions, the tactic is not trapped by a bad lemma example [topological_space α] [borel_space α] [normed_add_comm_group β] [borel_space β] [has_measurable_add₂ β] [has_measurable_sub₂ β] {s : finset ℕ} {F : ℕ → α → β} (hF : ∀ i, measurable (F i)) : ae_measurable (∑ i in s, (λ x, F (i+1) x - F i x)) μ := by measurability example : measurable (λ x : ℝ, real.exp (2 * inner x 3)) := by measurability /-- An older version of the tactic failed in the presence of a negated hypothesis due to an internal call to `apply_assumption`. -/ example {ι : Type*} (i k : ι) (hik : i ≠ k) : measurable (id : α → α) := by measurability
e605abbc74230d9678b5c84623b57c1830856f17
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/pp_all2.lean
ecf0ae3f5af4e290965510cccae3f3335cf5ffe6
[ "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
123
lean
-- set_option pp.all true set_option pp.numerals true set_option pp.universes false #check (10 : nat) + (3 : nat)
340a8fadd358f311f0948316082a9242900a2a5e
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/measure_theory/measure_space.lean
74b78656fd11c559441eb1c53b7b13becada5a7a
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
109,541
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import measure_theory.outer_measure import order.filter.countable_Inter import data.set.accumulate /-! # Measure spaces Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ℝ≥0∞`. We introduce the following typeclasses for measures: * `probability_measure μ`: `μ univ = 1`; * `finite_measure μ`: `μ univ < ∞`; * `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ` where `μ` is finite; * `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ∞`; * `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as `∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`. Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are Carathéodory measurable. To prove that two measures are equal, there are multiple options: * `ext`: two measures are equal if they are equal on all measurable sets. * `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating the measurable sets, if the π-system contains a spanning increasing sequence of sets where the measures take finite value (in particular the measures are σ-finite). This is a special case of the more general `ext_of_generate_from_of_cover` * `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using `C ∪ {univ}`, but is easier to work with. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter (hiding map) function measurable_space open_locale classical topological_space big_operators filter ennreal variables {α β γ δ ι : Type*} namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → measure_of (⋃ i, f i) = ∑' i, measure_of (f i)) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ℝ≥0∞, λ m, m.to_outer_measure⟩ section variables [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α} namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable (m : Π (s : set α), measurable_set s → ℝ≥0∞) (m0 : m ∅ measurable_set.empty = 0) (mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)) : measure α := { m_Union := λ f hf hd, show induced_outer_measure m _ m0 (Union f) = ∑' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {m : Π (s : set α), measurable_set s → ℝ≥0∞} {m0 : m ∅ measurable_set.empty = 0} {mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)} (s : set α) (hs : measurable_set s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext (h : ∀ s, measurable_set s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff : μ₁ = μ₂ ↔ ∀ s, measurable_set s → μ₁ s = μ₂ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s : set α) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s : set α) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s : set α) : μ s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl /-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a lemma next that only works for non-empty infima, in which case you can use `nonempty_measurable_superset`. -/ lemma measure_eq_infi' (μ : measure α) (s : set α) : μ s = ⨅ t : { t // s ⊆ t ∧ measurable_set t}, μ t := by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi] lemma measure_eq_induced_outer_measure : μ s = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : μ.to_outer_measure = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty := μ.trimmed.symm lemma measure_eq_extend (hs : measurable_set s) : μ s = extend (λ t (ht : measurable_set t), μ t) s := by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact μ.m_Union } @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := nonpos_iff_eq_zero.1 $ h₂ ▸ measure_mono h lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ∞) : μ s₂ = ∞ := top_unique $ h₁ ▸ measure_mono h lemma exists_measurable_superset (μ : measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = μ s := by simpa only [← measure_eq_trim] using μ.to_outer_measure.exists_measurable_superset_eq_trim s /-- A measurable set `t ⊇ s` such that `μ t = μ s`. -/ def to_measurable (μ : measure α) (s : set α) : set α := classical.some (exists_measurable_superset μ s) lemma subset_to_measurable (μ : measure α) (s : set α) : s ⊆ to_measurable μ s := (classical.some_spec (exists_measurable_superset μ s)).1 @[simp] lemma measurable_set_to_measurable (μ : measure α) (s : set α) : measurable_set (to_measurable μ s) := (classical.some_spec (exists_measurable_superset μ s)).2.1 @[simp] lemma measure_to_measurable (s : set α) : μ (to_measurable μ s) = μ s := (classical.some_spec (exists_measurable_superset μ s)).2.2 lemma exists_measurable_superset_of_null (h : μ s = 0) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 := outer_measure.exists_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_measurable_superset_iff_measure_eq_zero : (∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_measurable_superset_of_null⟩ theorem measure_Union_le [encodable β] (s : β → set α) : μ (⋃ i, s i) ≤ ∑' i, μ (s i) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : finite s) (hfin : ∀ i ∈ s, μ (f i) < ∞) : μ (⋃ i ∈ s, f i) < ∞ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃ i, s i) = 0 := μ.to_outer_measure.Union_null lemma measure_Union_null_iff [encodable ι] {s : ι → set α} : μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 := ⟨λ h i, measure_mono_null (subset_Union _ _) h, measure_Union_null⟩ theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_union_null_iff : μ (s₁ ∪ s₂) = 0 ↔ μ s₁ = 0 ∧ μ s₂ = 0:= ⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩, λ h, measure_union_null h.1 h.2⟩ /-! ### The almost everywhere filter -/ /-- The “almost everywhere” filter of co-null sets. -/ def measure.ae (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := compl_mem_ae_iff.symm lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀ a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall instance ae_is_measurably_generated : is_measurably_generated μ.ae := ⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_measurable_superset_of_null hs in ⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩ instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ lemma ae_imp_iff {p : α → Prop} {q : Prop} : (∀ᵐ x ∂μ, q → p x) ↔ (q → ∀ᵐ x ∂μ, p x) := filter.eventually_imp_distrib_left lemma ae_all_iff [encodable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀ i, p a i) ↔ (∀ i, ∀ᵐ a ∂ μ, p a i) := eventually_countable_forall lemma ae_ball_iff {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → δ) : f =ᵐ[μ] f := eventually_eq.rfl lemma ae_eq_symm {f g : α → δ} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → δ} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ @[simp] lemma ae_eq_empty : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 := eventually_eq_empty.trans $ by simp [ae_iff] lemma ae_le_set : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 := calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl ... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl @[simp] lemma union_ae_eq_right : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma ae_eq_set {s t : set α} : s =ᵐ[μ] t ↔ μ (s \ t) = 0 ∧ μ (t \ s) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set] /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ @[mono] lemma measure_mono_ae (H : s ≤ᵐ[μ] t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [ae_le_set.1 H, add_zero] alias measure_mono_ae ← filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr (H : s =ᵐ[μ] t) : μ s = μ t := le_antisymm H.le.measure_le H.symm.le.measure_le lemma measure_Union [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀ i, measurable_set (f i)) : μ (⋃ i, f i) = ∑' i, μ (f i) := begin rw [measure_eq_extend (measurable_set.Union h), extend_Union measurable_set.empty _ measurable_set.Union _ hn h], { simp [measure_eq_extend, h] }, { exact μ.empty }, { exact μ.m_Union } end lemma measure_union (hd : disjoint s₁ s₂) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := begin rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁] end lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀ b ∈ s, measurable_set (f b)) : μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw bUnion_eq_Union, exact measure_Union (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2) end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀ s ∈ S, measurable_set s) : μ (⋃₀ S) = ∑' s : S, μ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀ b ∈ s, measurable_set (f b)) : μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β} (hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) : ∑' b : s, μ (f ⁻¹' {↑b}) = μ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset β) {f : α → β} (hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) : ∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.set_bUnion_preimage_singleton] lemma measure_diff (h : s₂ ⊆ s₁) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) (h_fin : μ s₂ < ∞) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma measure_compl (h₁ : measurable_set s) (h_fin : μ s < ∞) : μ (sᶜ) = μ univ - μ s := by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) measurable_set.univ h₁ h_fin } lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i)) (H : pairwise_on ↑s (disjoint on t)) : ∑ i in s, μ (t i) ≤ μ (univ : set α) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : pairwise (disjoint on s)) : ∑' i, μ (s i) ≤ μ (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact λ i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- Continuity from below: the measure of the union of a directed sequence of measurable sets is the supremum of the measures. -/ lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, measurable_set (s i)) (hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) := begin by_cases hι : nonempty ι, swap, { simp only [supr_of_empty hι, Union], exact measure_empty }, resetI, refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _), have : ∀ n, measurable_set (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) := measurable_set.disjointed (measurable_set.bUnion_decode2 h), rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this, ennreal.tsum_eq_supr_nat], simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)], refine supr_le (λ n, _), refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _, exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)), simp only [← finset.set_bUnion_option_to_finset, ← finset.set_bUnion_bUnion], generalize : (finset.range n).bUnion (λ k, (encodable.decode2 ι k).to_finset) = t, rcases hd.finset_le t with ⟨i, hi⟩, exact le_supr_of_le i (measure_mono $ bUnion_subset hi) end lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t) (h : ∀ i ∈ t, measurable_set (s i)) (hd : directed_on ((⊆) on s) t) : μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe, supr_subtype'], refl end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the infimum of the measures. -/ lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α} (h : ∀ i, measurable_set (s i)) (hd : directed (⊇) s) (hfin : ∃ i, μ (s i) < ∞) : μ (⋂ i, s i) = (⨅ i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (measurable_set.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr], { congr' 1, refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _), { rcases hd i k with ⟨j, hji, hjk⟩, use j, rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)], exact measure_mono (diff_subset_diff_right hji) }, { rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i), set.union_comm], exact measure_mono (diff_subset_iff.1 $ subset.refl _) } }, { exact λ i, (h k).diff (h i) }, { exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) } end lemma measure_eq_inter_diff (hs : measurable_set s) (ht : measurable_set t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma measure_union_add_inter (hs : measurable_set s) (ht : measurable_set t) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right, union_diff_right, measure_eq_inter_diff hs ht], ac_refl } /-- Continuity from below: the measure of the union of an increasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Union {s : ℕ → set α} (hs : ∀ n, measurable_set (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) := begin rw measure_Union_eq_supr hs (directed_of_sup hm), exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm) end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Inter {s : ℕ → set α} (hs : ∀ n, measurable_set (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃ i, μ (s i) < ∞) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) := begin rw measure_Inter_eq_infi hs (directed_of_sup hm) hf, exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm), end /-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that ∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/ lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, measurable_set (s i)) (hs' : ∑' i, μ (s i) ≠ ∞) : μ (limsup at_top s) = 0 := begin rw limsup_eq_infi_supr_of_nat', -- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))` -- as `n` tends to infinity. For the former, we use continuity from above. refine tendsto_nhds_unique (tendsto_measure_Inter (λ i, measurable_set.Union (λ b, hs (b + i))) _ ⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _, { intros n m hnm x, simp only [set.mem_Union], exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ }, { -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side -- converges to `0` by hypothesis, so does the former and the proof is complete. exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (ennreal.tendsto_sum_nat_add (μ ∘ s) hs') (eventually_of_forall (by simp only [forall_const, zero_le])) (eventually_of_forall (λ i, measure_Union_le _))) } end lemma measure_if {x : β} {t : set β} {s : set α} {μ : measure α} : μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x := by { split_ifs; simp [h] } end section outer_measure variables [ms : measurable_space α] {s t : set α} include ms /-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are Carathéodory measurable. -/ def outer_measure.to_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_induced_outer_measure, refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _), rw [← measure_eq_extend (ht.inter hs), ← measure_eq_extend (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end @[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) {s : set α} (hs : measurable_set s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) : m s ≤ m.to_measure h s := m.le_trim s @[simp] lemma to_outer_measure_to_measure {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq end outer_measure variables [measurable_space α] [measurable_space β] [measurable_space γ] variables {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : measure α} {s s' t : set α} namespace measure protected lemma caratheodory (μ : measure α) (hs : measurable_set s) : μ (t ∩ s) + μ (t \ s) = μ t := (le_to_outer_measure_caratheodory μ s hs t).symm /-! ### The `ℝ≥0∞`-module of measures -/ instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 := ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure α) := ⟨0⟩ instance : has_add (measure α) := ⟨λ μ₁ μ₂, { to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure, m_Union := λ s hs hd, show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, (μ₁ (s i) + μ₂ (s i)), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) : (μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl theorem add_apply (μ₁ μ₂ : measure α) (s : set α) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ℝ≥0∞ (measure α) := ⟨λ c μ, { to_outer_measure := c • μ.to_outer_measure, m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ℝ≥0∞) (μ : measure α) : (c • μ).to_outer_measure = c • μ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ℝ≥0∞) (μ : measure α) : ⇑(c • μ) = c • μ := rfl theorem smul_apply (c : ℝ≥0∞) (μ : measure α) (s : set α) : (c • μ) s = c * μ s := rfl instance : semimodule ℝ≥0∞ (measure α) := injective.semimodule ℝ≥0∞ ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure /-! ### The complete lattice of measures -/ instance : partial_order (measure α) := { le := λ m₁ m₂, ∀ s, measurable_set s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, measurable_set s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, measurable_set s ∧ μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] -- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)` protected lemma add_le_add_left (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ := λ s hs, add_le_add_left (hμ s hs) _ protected lemma add_le_add_right (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν := λ s hs, add_le_add_right (hμ s hs) _ protected lemma add_le_add (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ := λ s hs, add_le_add (hμ s hs) (hν s hs) protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν := λ s hs, le_add_left (h s hs) protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' := λ s hs, le_add_right (h s hs) section Inf variables {m : set (measure α)} lemma Inf_caratheodory (s : set α) (hs : measurable_set s) : (Inf (to_outer_measure '' m)).caratheodory.measurable_set' s := begin rw [outer_measure.Inf_eq_bounded_by_Inf_gen], refine outer_measure.bounded_by_caratheodory (λ t, _), simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], intros μ hμ u htu hu, have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { intros s t hst, rw [outer_measure.Inf_gen_def], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply (hs : measurable_set s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, measure_Inf_le, λ _, measure_le_Inf⟩) } end Inf protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 := μ.zero_le.le_iff_eq @[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 := ⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩ /-! ### Pushforward and pullback -/ /-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β) (hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) : measure α →ₗ[ℝ≥0∞] measure β := { to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ), map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs], map_smul' := λ c μ, ext $ λ s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) {s : set β} (hs : measurable_set s) : lift_linear f hf μ s = f μ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) (s : set β) : f μ.to_outer_measure s ≤ lift_linear f hf μ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : α → β) : measure α →ₗ[ℝ≥0∞] measure β := if hf : measurable f then lift_linear (outer_measure.map f) $ λ μ s hs t, le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t) else 0 /-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see `measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/ @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : map f μ s = μ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id μ = μ := ext $ λ s, map_apply measurable_id lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : map g (map f μ) = map (g ∘ f) μ := ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] lemma map_mono {f : α → β} (hf : measurable f) (h : μ ≤ ν) : map f μ ≤ map f ν := λ s hs, by simp [hf, hs, h _ (hf hs)] /-- Even if `s` is not measurable, we can bound `map f μ s` from below. See also `measurable_equiv.map_apply`. -/ theorem le_map_apply {f : α → β} (hf : measurable f) (s : set β) : μ (f ⁻¹' s) ≤ map f μ s := begin rw [measure_eq_infi' (map f μ)], refine le_infi _, rintro ⟨t, hst, ht⟩, convert measure_mono (preimage_mono hst), exact map_apply hf ht end /-- Even if `s` is not measurable, `map f μ s = 0` implies that `μ (f ⁻¹' s) = 0`. -/ lemma preimage_null_of_map_null {f : α → β} (hf : measurable f) {s : set β} (hs : map f μ s = 0) : μ (f ⁻¹' s) = 0 := nonpos_iff_eq_zero.mp $ (le_map_apply hf s).trans_eq hs /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/ def comap (f : α → β) : measure β →ₗ[ℝ≥0∞] measure α := if hf : injective f ∧ ∀ s, measurable_set s → measurable_set (f '' s) then lift_linear (outer_measure.comap f) $ λ μ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : α → β) (hfi : injective f) (hf : ∀ s, measurable_set s → measurable_set (f '' s)) (μ : measure β) (hs : measurable_set s) : comap f μ s = μ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-! ### Restricting a measure -/ /-- Restrict a measure `μ` to a set `s` as an `ℝ≥0∞`-linear map. -/ def restrictₗ (s : set α) : measure α →ₗ[ℝ≥0∞] measure α := lift_linear (outer_measure.restrict s) $ λ μ s' hs' t, begin suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `μ` to a set `s`. -/ def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ @[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) : restrictₗ s μ = μ.restrict s := rfl /-- If `t` is a measurable set, then the measure of `t` with respect to the restriction of the measure to `s` equals the outer measure of `t ∩ s`. An alternate version requiring that `s` be measurable instead of `t` exists as `measure.restrict_apply'`. -/ @[simp] lemma restrict_apply (ht : measurable_set t) : μ.restrict s t = μ (t ∩ s) := by simp [← restrictₗ_apply, restrictₗ, ht] lemma restrict_eq_self (h_meas_t : measurable_set t) (h : t ⊆ s) : μ.restrict s t = μ t := by rw [restrict_apply h_meas_t, subset_iff_inter_eq_left.1 h] lemma restrict_apply_self (μ:measure α) (h_meas_s : measurable_set s) : (μ.restrict s) s = μ s := (restrict_eq_self h_meas_s (set.subset.refl _)) lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s := by rw [restrict_apply measurable_set.univ, set.univ_inter] lemma le_restrict_apply (s t : set α) : μ (t ∩ s) ≤ μ.restrict s t := by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (μ ν : measure α) (s : set α) : (μ + ν).restrict s = μ.restrict s + ν.restrict s := (restrictₗ s).map_add μ ν @[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 := (restrictₗ s).map_zero @[simp] lemma restrict_smul (c : ℝ≥0∞) (μ : measure α) (s : set α) : (c • μ).restrict s = c • μ.restrict s := (restrictₗ s).map_smul c μ @[simp] lemma restrict_restrict (hs : measurable_set s) : (μ.restrict t).restrict s = μ.restrict (s ∩ t) := ext $ λ u hu, by simp [*, set.inter_assoc] lemma restrict_apply_eq_zero (ht : measurable_set t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 := nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _) lemma restrict_apply_eq_zero' (hs : measurable_set s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := begin refine ⟨measure_inter_eq_zero_of_restrict, λ h, _⟩, rcases exists_measurable_superset_of_null h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 := by rw [← measure_univ_eq_zero, restrict_apply_univ] @[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs] @[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs] lemma restrict_eq_self_of_measurable_subset (ht : measurable_set t) (t_subset : t ⊆ s) : μ.restrict s t = μ t := by rw [measure.restrict_apply ht, set.inter_eq_self_of_subset_left t_subset] lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : measurable_set s) (hs' : measurable_set s') (ht : measurable_set t) : μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union (h : disjoint s t) (hs : measurable_set s) (ht : measurable_set t) : μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_add_inter (hs : measurable_set s) (ht : measurable_set t) : μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := begin ext1 u hu, simp only [add_apply, restrict_apply hu, inter_union_distrib_left], convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3, rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self] end @[simp] lemma restrict_add_restrict_compl (hs : measurable_set s) : μ.restrict s + μ.restrict sᶜ = μ := by rw [← restrict_union disjoint_compl_right hs hs.compl, union_compl_self, restrict_univ] @[simp] lemma restrict_compl_add_restrict (hs : measurable_set s) : μ.restrict sᶜ + μ.restrict s = μ := by rw [add_comm, restrict_add_restrict_compl hs] lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' := begin intros t ht, suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, measurable_set (s i)) {t : set α} (ht : measurable_set t) : μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right) (λ i, ht.inter (hm i)) end lemma restrict_Union_apply_eq_supr [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hd : directed (⊆) s) {t : set α} (ht : measurable_set t) : μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t := begin simp only [restrict_apply ht, inter_Union], rw [measure_Union_eq_supr], exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)] end lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : (map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) := ext $ λ t ht, by simp [*, hf ht] lemma map_comap_subtype_coe (hs : measurable_set s) : (map (coe : s → α)).comp (comap coe) = restrictₗ s := linear_map.ext $ λ μ, ext $ λ t ht, by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s') ... = ν.restrict s' t : (restrict_apply ht).symm lemma restrict_le_self : μ.restrict s ≤ μ := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ t : measure_mono $ inter_subset_left t s lemma restrict_congr_meas (hs : measurable_set s) : μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, measurable_set t → μ t = ν t := ⟨λ H t hts ht, by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], λ H, ext $ λ t ht, by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩ lemma restrict_congr_mono (hs : s ⊆ t) (hm : measurable_set s) (h : μ.restrict t = ν.restrict t) : μ.restrict s = ν.restrict s := by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm] /-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all measurable subsets of `s ∪ t`. -/ lemma restrict_union_congr (hsm : measurable_set s) (htm : measurable_set t) : μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔ μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t := begin refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h, restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩, simp only [restrict_congr_meas, hsm, htm, hsm.union htm], rintros ⟨hs, ht⟩ u hu hum, rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm, hs _ (inter_subset_right _ _) (hum.inter hsm), ht _ (diff_subset_iff.2 hu) (hum.diff hsm)] end lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α} (htm : ∀ i ∈ s, measurable_set (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin induction s using finset.induction_on with i s hi hs, { simp }, simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢, simp only [finset.set_bUnion_insert, ← hs htm.2], exact restrict_union_congr htm.1 (s.measurable_set_bUnion htm.2) end lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) : μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := begin refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩, ext1 t ht, have M : ∀ t : finset ι, measurable_set (⋃ i ∈ t, s i) := λ t, t.measurable_set_bUnion (λ i _, hm i), have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) := directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht), rw [Union_eq_Union_finset], simp only [restrict_Union_apply_eq_supr M D ht, (restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)], end lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s) (htm : ∀ i ∈ s, measurable_set (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢, haveI := hc.to_encodable, exact restrict_Union_congr htm end lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, measurable_set s) : μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm] /-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a restrict on measures and the RHS has a restrict on outer measures. -/ lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : measurable_set s) : (μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure := by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure, outer_measure.restrict_trim h, μ.trimmed] /-- This lemma shows that `Inf` and `restrict` commute for measures. -/ lemma restrict_Inf_eq_Inf_restrict {m : set (measure α)} (hm : m.nonempty) (ht : measurable_set t) : (Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) := begin ext1 s hs, simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (measurable_set.inter hs ht), set.image_image, restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure, ← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _), outer_measure.restrict_apply] end /-- If `s` is a measurable set, then the outer measure of `t` with respect to the restriction of the measure to `s` equals the outer measure of `t ∩ s`. This is an alternate version of `measure.restrict_apply`, requiring that `s` is measurable instead of `t`. -/ lemma restrict_apply' (hs : measurable_set s) : μ.restrict s t = μ (t ∩ s) := by rw [← coe_to_outer_measure, measure.restrict_to_outer_measure_eq_to_outer_measure_restrict hs, outer_measure.restrict_apply s t _, coe_to_outer_measure] lemma restrict_eq_self_of_subset_of_measurable (hs : measurable_set s) (t_subset : t ⊆ s) : μ.restrict s t = μ t := by rw [restrict_apply' hs, set.inter_eq_self_of_subset_left t_subset] /-! ### Extensionality results -/ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `Union`). -/ lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hs : (⋃ i, s i) = univ) : μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `bUnion`). -/ lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S) (hm : ∀ i ∈ S, measurable_set (s i)) (hs : (⋃ i ∈ S, s i) = univ) : μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `sUnion`). -/ lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, measurable_set s) (hs : (⋃₀ S) = univ) : μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ lemma ext_of_generate_from_of_cover {S T : set (set α)} (h_gen : ‹_› = generate_from S) (hc : countable T) (h_inter : is_pi_system S) (hm : ∀ t ∈ T, measurable_set t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ∞) (ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) : μ = ν := begin refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _), ext1 u hu, simp only [restrict_apply hu], refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu, { simp only [set.empty_inter, measure_empty] }, { intros v hv hvt, have := T_eq t ht, rw [set.inter_comm] at hvt ⊢, rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt, ennreal.add_right_inj] at this, exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) }, { intros f hfd hfm h_eq, have : pairwise (disjoint on λ n, f n ∩ t) := λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _), simp only [Union_inter, measure_Union this (λ n, (hfm n).inter (hm t ht)), h_eq] } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `sUnion`. -/ lemma ext_of_generate_from_of_cover_subset {S T : set (set α)} (h_gen : ‹_› = generate_from S) (h_inter : is_pi_system S) (h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ∞) (h_eq : ∀ s ∈ S, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)), { intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) }, { intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H, { simp only [H, measure_empty] }, { exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `Union`. `finite_spanning_sets_in.ext` is a reformulation of this lemma. -/ lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α) (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ) (h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ∞) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq, { rintro _ ⟨i, rfl⟩, apply h2B }, { rintro _ ⟨i, rfl⟩, apply hμB } end /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) lemma le_dirac_apply {a} : s.indicator 1 a ≤ dirac a s := outer_measure.dirac_apply a s ▸ le_to_measure_apply _ _ _ @[simp] lemma dirac_apply' (a : α) (hs : measurable_set s) : dirac a s = s.indicator 1 a := to_measure_apply _ _ hs @[simp] lemma dirac_apply_of_mem {a : α} (h : a ∈ s) : dirac a s = 1 := begin have : ∀ t : set α, a ∈ t → t.indicator (1 : α → ℝ≥0∞) a = 1, from λ t ht, indicator_of_mem ht 1, refine le_antisymm (this univ trivial ▸ _) (this s h ▸ le_dirac_apply), rw [← dirac_apply' a measurable_set.univ], exact measure_mono (subset_univ s) end @[simp] lemma dirac_apply [measurable_singleton_class α] (a : α) (s : set α) : dirac a s = s.indicator 1 a := begin by_cases h : a ∈ s, by rw [dirac_apply_of_mem h, indicator_of_mem h, pi.one_apply], rw [indicator_of_not_mem h, ← nonpos_iff_eq_zero], calc dirac a s ≤ dirac a {a}ᶜ : measure_mono (subset_compl_comm.1 $ singleton_subset_iff.2 h) ... = 0 : by simp [dirac_apply' _ (measurable_set_singleton _).compl] end lemma map_dirac {f : α → β} (hf : measurable f) (a : α) : map f (dirac a) = dirac (f a) := ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply] /-- Sum of an indexed family of measures. -/ def sum (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) lemma le_sum_apply (f : ι → measure α) (s : set α) : (∑' i, f i s) ≤ sum f s := le_to_measure_apply _ _ _ @[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : measurable_set s) : sum f s = ∑' i, f i s := to_measure_apply _ _ hs lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ := λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i] lemma restrict_Union [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, measurable_set (s i)) : μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) := ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le [encodable ι] {s : ι → set α} : μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) := begin intros t ht, suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff := ext $ λ s hs, by simp [hs, tsum_fintype] @[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν := sum_bool _ @[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : measurable_set s) : (sum μ).restrict s = sum (λ i, (μ i).restrict s) := ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac lemma le_count_apply : (∑' i : s, 1 : ℝ≥0∞) ≤ count s := calc (∑' i : s, 1 : ℝ≥0∞) = ∑' i, indicator s 1 i : tsum_subtype s 1 ... ≤ ∑' i, dirac i s : ennreal.tsum_le_tsum $ λ x, le_dirac_apply ... ≤ count s : le_sum_apply _ _ lemma count_apply (hs : measurable_set s) : count s = ∑' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) : count (↑s : set α) = s.card := calc count (↑s : set α) = ∑' i : (↑s : set α), 1 : count_apply s.measurable_set ... = ∑ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) : count s = hs.to_finset.card := by rw [← count_apply_finset, finite.coe_to_finset] /-- `count` measure evaluates to infinity at infinite sets. -/ lemma count_apply_infinite (hs : s.infinite) : count s = ∞ := begin refine top_unique (le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, _), rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩, calc (t.card : ℝ≥0∞) = ∑ i in t, 1 : by simp ... = ∑' i : (t : set α), 1 : (t.tsum_subtype 1).symm ... ≤ count (t : set α) : le_count_apply ... ≤ count s : measure_mono ht end @[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ∞ ↔ s.infinite := begin by_cases hs : s.finite, { simp [set.infinite, hs, count_apply_finite] }, { change s.infinite at hs, simp [hs, count_apply_infinite] } end @[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ∞ ↔ s.finite := calc count s < ∞ ↔ count s ≠ ∞ : lt_top_iff_ne_top ... ↔ ¬s.infinite : not_congr count_apply_eq_top ... ↔ s.finite : not_not /-! ### Absolute continuity -/ /-- We say that `μ` is absolutely continuous with respect to `ν`, or that `μ` is dominated by `ν`, if `ν(A) = 0` implies that `μ(A) = 0`. -/ def absolutely_continuous (μ ν : measure α) : Prop := ∀ ⦃s : set α⦄, ν s = 0 → μ s = 0 infix ` ≪ `:50 := absolutely_continuous lemma absolutely_continuous.mk (h : ∀ ⦃s : set α⦄, measurable_set s → ν s = 0 → μ s = 0) : μ ≪ ν := begin intros s hs, rcases exists_measurable_superset_of_null hs with ⟨t, h1t, h2t, h3t⟩, exact measure_mono_null h1t (h h2t h3t), end @[refl] lemma absolutely_continuous.refl (μ : measure α) : μ ≪ μ := λ s hs, hs lemma absolutely_continuous.rfl : μ ≪ μ := λ s hs, hs lemma absolutely_continuous_of_eq (h : μ = ν) : μ ≪ ν := by rw h alias absolutely_continuous_of_eq ← eq.absolutely_continuous @[trans] lemma absolutely_continuous.trans (h1 : μ₁ ≪ μ₂) (h2 : μ₂ ≪ μ₃) : μ₁ ≪ μ₃ := λ s hs, h1 $ h2 hs /-- The filter of sets `s` such that `sᶜ` has finite measure. -/ def cofinite (μ : measure α) : filter α := { sets := {s | μ sᶜ < ∞}, univ_sets := by simp, inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _ ... < ∞ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ∞ := iff.rfl lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ∞ := by rw [mem_cofinite, compl_compl] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ∞ := iff.rfl end measure open measure @[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 := by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero] @[simp] lemma ae_zero : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl @[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae := λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs lemma mem_ae_map_iff {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : s ∈ (map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae := by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl] lemma ae_map_iff {f : α → β} (hf : measurable f) {p : β → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ y ∂ (map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) := mem_ae_map_iff hf hp lemma ae_restrict_iff {p : α → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl], congr' with x, simp [and_comm] end lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) : ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff] at h ⊢, simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h end lemma ae_restrict_iff' {s : set α} {p : α → Prop} (hp : measurable_set s) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hp], congr' with x, simp [and_comm] end lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ℝ≥0∞) : ∀ᵐ x ∂(c • μ), p x := ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero] lemma ae_smul_measure_iff {p : α → Prop} {c : ℝ≥0∞} (hc : c ≠ 0) : (∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x := by simp [ae_iff, hc] lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x := add_eq_zero_iff lemma ae_eq_comp' {ν : measure β} {f : α → β} {g g' : β → δ} (hf : measurable f) (h : g =ᵐ[ν] g') (h2 : map f μ ≪ ν) : g ∘ f =ᵐ[μ] g' ∘ f := preimage_null_of_map_null hf $ h2 h lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : measurable f) (h : g =ᵐ[measure.map f μ] g') : g ∘ f =ᵐ[μ] g' ∘ f := ae_eq_comp' hf h absolutely_continuous.rfl lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae := λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs) @[simp] lemma ae_restrict_eq (hs : measurable_set s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end @[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 := ae_eq_bot.trans restrict_eq_zero @[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s := ne_bot_iff.trans $ (not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm lemma self_mem_ae_restrict {s} (hs : measurable_set s) : s ∈ (μ.restrict s).ae := by simp only [ae_restrict_eq hs, exists_prop, mem_principal_sets, mem_inf_sets]; exact ⟨_, univ_mem_sets, s, by rw [univ_inter, and_self]⟩ /-- A version of the Borel-Cantelli lemma: if `sᵢ` is a sequence of measurable sets such that `∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `sᵢ`. -/ lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, measurable_set (s i)) (hs' : ∑' i, μ (s i) ≠ ∞) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n := begin refine measure_mono_null _ (measure_limsup_eq_zero hs hs'), rw ←set.le_eq_subset, refine le_Inf (λ t ht x hx, _), simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq, eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht, rcases ht with ⟨i, hi⟩, rcases hx i with ⟨j, ⟨hj, hj'⟩⟩, exact hi j hj hj' end lemma mem_ae_dirac_iff {a : α} (hs : measurable_set s) : s ∈ (dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply', hs.compl, indicator_apply, *] lemma ae_dirac_iff {a : α} {p : α → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ x ∂(dirac a), p x) ↔ p a := mem_ae_dirac_iff hp @[simp] lemma ae_dirac_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a := by { ext s, simp [mem_ae_iff, imp_false] } lemma ae_eq_dirac' [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) : f =ᵐ[dirac a] const α (f a) := (ae_dirac_iff $ show measurable_set (f ⁻¹' {f a}), from hf $ measurable_set_singleton _).2 rfl lemma ae_eq_dirac [measurable_singleton_class α] {a : α} (f : α → δ) : f =ᵐ[dirac a] const α (f a) := by simp [filter.eventually_eq] lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t := begin intros u hu, simp only [restrict_apply hu], exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx) end lemma restrict_congr_set (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t := le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le) /-- A measure `μ` is called a probability measure if `μ univ = 1`. -/ class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1) instance measure.dirac.probability_measure {x : α} : probability_measure (dirac x) := ⟨dirac_apply_of_mem $ mem_univ x⟩ /-- A measure `μ` is called finite if `μ univ < ∞`. -/ class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ∞) instance restrict.finite_measure (μ : measure α) [hs : fact (μ s < ∞)] : finite_measure (μ.restrict s) := ⟨by simp [hs.elim]⟩ /-- Measure `μ` *has no atoms* if the measure of each singleton is zero. NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure, there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`, the converse is not true. -/ class has_no_atoms (μ : measure α) : Prop := (measure_singleton : ∀ x, μ {x} = 0) export probability_measure (measure_univ) has_no_atoms (measure_singleton) attribute [simp] measure_singleton lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ∞ := (measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ∞ := ne_of_lt (measure_lt_top μ s) /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds for measures with the additional assumption that μ is finite. -/ lemma measure.le_of_add_le_add_left {μ ν₁ ν₂ : measure α} [finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ := λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top μ S) (A2 S B1) @[priority 100] instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] : finite_measure μ := ⟨by simp only [measure_univ, ennreal.one_lt_top]⟩ lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 := mt measure_univ_eq_zero.2 $ by simp [measure_univ] section no_atoms variables [has_no_atoms μ] lemma measure_countable (h : countable s) : μ s = 0 := begin rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero], refine le_trans (measure_bUnion_le h _) _, simp end lemma measure_finite (h : s.finite) : μ s = 0 := measure_countable h.countable lemma measure_finset (s : finset α) : μ ↑s = 0 := measure_finite s.finite_to_set lemma insert_ae_eq_self (a : α) (s : set α) : (insert a s : set α) =ᵐ[μ] s := union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _) variables [partial_order α] {a b : α} lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a := by simp only [← Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)] lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a := @Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _ lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b := Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc end no_atoms lemma ite_ae_eq_of_measure_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ s = 0) : (λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] g := begin have h_ss : sᶜ ⊆ {a : α | ite (a ∈ s) (f a) (g a) = g a}, from λ x hx, by simp [(set.mem_compl_iff _ _).mp hx], refine measure_mono_null _ hs_zero, nth_rewrite 0 ←compl_compl s, rwa set.compl_subset_compl, end lemma ite_ae_eq_of_measure_compl_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ sᶜ = 0) : (λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] f := by { filter_upwards [hs_zero], intros, split_ifs, refl } namespace measure /-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`. Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/ def finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ∞ lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) : μ.finite_at_filter f := ⟨univ, univ_mem_sets, measure_lt_top μ univ⟩ lemma finite_at_filter.exists_mem_basis {μ : measure α} {f : filter α} (hμ : finite_at_filter μ f) {p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) : ∃ i (hi : p i), μ (s i) < ∞ := (hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ lemma finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ := ⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩ /-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have finite measures. This structure is a type, which is useful if we want to record extra properties about the sets, such as that they are monotone. `sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of finite spanning sets in the collection of all measurable sets. -/ @[protect_proj, nolint has_inhabited_instance] structure finite_spanning_sets_in (μ : measure α) (C : set (set α)) := (set : ℕ → set α) (set_mem : ∀ i, set i ∈ C) (finite : ∀ i, μ (set i) < ∞) (spanning : (⋃ i, set i) = univ) end measure open measure /-- A measure `μ` is called σ-finite if there is a countable collection of sets `{ A i | i ∈ ℕ }` such that `μ (A i) < ∞` and `⋃ i, A i = s`. -/ class sigma_finite (μ : measure α) : Prop := (out' : nonempty (μ.finite_spanning_sets_in {s | measurable_set s})) theorem sigma_finite_iff {μ : measure α} : sigma_finite μ ↔ nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem sigma_finite.out {μ : measure α} (h : sigma_finite μ) : nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) := h.1 /-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/ def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] : μ.finite_spanning_sets_in {s | measurable_set s} := classical.choice h.out /-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite measure using `classical.some`. This definition satisfies monotonicity in addition to all other properties in `sigma_finite`. -/ def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α := accumulate μ.to_finite_spanning_sets_in.set i lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] : monotone (spanning_sets μ) := monotone_accumulate lemma measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : measurable_set (spanning_sets μ i) := measurable_set.Union $ λ j, measurable_set.Union_Prop $ λ hij, μ.to_finite_spanning_sets_in.set_mem j lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) : μ (spanning_sets μ i) < ∞ := measure_bUnion_lt_top (finite_le_nat i) $ λ j _, μ.to_finite_spanning_sets_in.finite j lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] : (⋃ i : ℕ, spanning_sets μ i) = univ := by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning] lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] : is_countably_spanning (range (spanning_sets μ)) := ⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩ namespace measure lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : measurable_set s) : (⨆ i, μ.restrict (spanning_sets μ i) s) = μ s := begin convert (restrict_Union_apply_eq_supr (measurable_spanning_sets μ) _ hs).symm, { simp [Union_spanning_sets] }, { exact directed_of_sup (monotone_spanning_sets μ) } end namespace finite_spanning_sets_in variables {C D : set (set α)} /-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/ protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D := ⟨h.set, λ i, hC (h.set_mem i), h.finite, h.spanning⟩ /-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite. -/ protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) (hC : ∀ s ∈ C, measurable_set s) : sigma_finite μ := ⟨⟨h.mono hC⟩⟩ /-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of `finite_spanning_sets_in`. -/ protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem h.finite h_eq protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C := ⟨_, h.set_mem, h.spanning⟩ end finite_spanning_sets_in lemma sigma_finite_of_not_nonempty (μ : measure α) (hα : ¬ nonempty α) : sigma_finite μ := ⟨⟨⟨λ _, ∅, λ n, measurable_set.empty, λ n, by simp, by simp [eq_empty_of_not_nonempty hα univ]⟩⟩⟩ lemma sigma_finite_of_countable {S : set (set α)} (hc : countable S) (hμ : ∀ s ∈ S, μ s < ∞) (hU : ⋃₀ S = univ) : sigma_finite μ := begin obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → set α, (∀ n, μ (s n) < ∞) ∧ (⋃ n, s n) = univ, from (exists_seq_cover_iff_countable ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩, refine ⟨⟨⟨λ n, to_measurable μ (s n), λ n, measurable_set_to_measurable _ _, by simpa, _⟩⟩⟩, exact eq_univ_of_subset (Union_subset_Union $ λ n, subset_to_measurable μ (s n)) hs end end measure /-- Every finite measure is σ-finite. -/ @[priority 100] instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ := ⟨⟨⟨λ _, univ, λ _, measurable_set.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩⟩ instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) : sigma_finite (μ.restrict s) := begin refine ⟨⟨⟨spanning_sets μ, measurable_spanning_sets μ, λ i, _, Union_spanning_sets μ⟩⟩⟩, rw [restrict_apply (measurable_spanning_sets μ i)], exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i) end instance sum.sigma_finite {ι} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : sigma_finite (sum μ) := begin haveI : encodable ι := (encodable.trunc_encodable_of_fintype ι).out, have : ∀ n, measurable_set (⋂ (i : ι), spanning_sets (μ i) n) := λ n, measurable_set.Inter (λ i, measurable_spanning_sets (μ i) n), refine ⟨⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, this, λ n, _, _⟩⟩⟩, { rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff], rintro i -, exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) }, { rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ], exact λ i, monotone_spanning_sets (μ i), } end instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : sigma_finite (μ + ν) := by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa } /-- A measure is called locally finite if it is finite in some neighborhood of each point. -/ class locally_finite_measure [topological_space α] (μ : measure α) : Prop := (finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x)) @[priority 100] -- see Note [lower instance priority] instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α) [finite_measure μ] : locally_finite_measure μ := ⟨λ x, finite_at_filter_of_finite _ _⟩ lemma measure.finite_at_nhds [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : μ.finite_at_filter (𝓝 x) := locally_finite_measure.finite_at_nhds x lemma measure.smul_finite {α : Type*} [measurable_space α] (μ : measure α) [finite_measure μ] {c : ℝ≥0∞} (hc : c < ∞) : finite_measure (c • μ) := begin refine ⟨_⟩, rw measure.smul_apply, exact ennreal.mul_lt_top hc (measure_lt_top μ set.univ), end lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : ∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ∞ := by simpa only [exists_prop, and.assoc] using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x) @[priority 100] -- see Note [lower instance priority] instance sigma_finite_of_locally_finite [topological_space α] [topological_space.second_countable_topology α] {μ : measure α} [locally_finite_measure μ] : sigma_finite μ := begin choose s hsx hsμ using μ.finite_at_nhds, rcases topological_space.countable_cover_nhds hsx with ⟨t, htc, htU⟩, refine measure.sigma_finite_of_countable (htc.image s) (ball_image_iff.2 $ λ x hx, hsμ x) _, rwa sUnion_image end /-- If two finite measures give the same mass to the whole space and coincide on a π-system made of measurable sets, then they coincide on all sets in the σ-algebra generated by the π-system. -/ lemma ext_on_measurable_space_of_generate_finite {α} (m₀ : measurable_space α) {μ ν : measure α} [finite_measure μ] (C : set (set α)) (hμν : ∀ s ∈ C, μ s = ν s) {m : measurable_space α} (h : m ≤ m₀) (hA : m = measurable_space.generate_from C) (hC : is_pi_system C) (h_univ : μ set.univ = ν set.univ) {s : set α} (hs : m.measurable_set' s) : μ s = ν s := begin haveI : @finite_measure _ m₀ ν := begin constructor, rw ← h_univ, apply finite_measure.measure_univ_lt_top, end, refine induction_on_inter hA hC (by simp) hμν _ _ hs, { intros t h1t h2t, have h1t_ : @measurable_set α m₀ t, from h _ h1t, rw [@measure_compl α m₀ μ t h1t_ (@measure_lt_top α m₀ μ _ t), @measure_compl α m₀ ν t h1t_ (@measure_lt_top α m₀ ν _ t), h_univ, h2t], }, { intros f h1f h2f h3f, have h2f_ : ∀ (i : ℕ), @measurable_set α m₀ (f i), from (λ i, h _ (h2f i)), have h_Union : @measurable_set α m₀ (⋃ (i : ℕ), f i),from @measurable_set.Union α ℕ m₀ _ f h2f_, simp [measure_Union, h_Union, h1f, h3f, h2f_], }, end /-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra (and `univ`). -/ lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C) (hC : is_pi_system C) {μ ν : measure α} [finite_measure μ] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) : μ = ν := measure.ext (λ s hs, ext_on_measurable_space_of_generate_finite _inst_1 C hμν (le_refl _inst_1) hA hC h_univ hs) namespace measure namespace finite_at_filter variables {f g : filter α} lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f := λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩ lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_left lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_right @[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩, suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩, exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩)) end alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _ lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f := inf_ae_iff.1 (hg.filter_mono h) protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f := λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩ @[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) : ν.finite_at_filter g → μ.finite_at_filter f := λ h, (h.filter_mono hf).measure_mono hμ protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ∞ := (eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) := λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩, ⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩ end finite_at_filter lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) (s : set α) : μ.finite_at_filter (𝓝[s] x) := (finite_at_nhds μ x).inf_of_left @[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ∞ := ⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩ /-! ### Subtraction of measures -/ /-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`. It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures. Compare with `ennreal.has_sub`. Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and `ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and `ν univ ≠ ∞`, then `(μ - ν) + ν = μ`. -/ noncomputable instance has_sub {α : Type*} [measurable_space α] : has_sub (measure α) := ⟨λ μ ν, Inf {τ | μ ≤ τ + ν} ⟩ section measure_sub lemma sub_def : μ - ν = Inf {d | μ ≤ d + ν} := rfl lemma sub_eq_zero_of_le (h : μ ≤ ν) : μ - ν = 0 := begin rw [← nonpos_iff_eq_zero', measure.sub_def], apply @Inf_le (measure α) _ _, simp [h], end /-- This application lemma only works in special circumstances. Given knowledge of when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/ lemma sub_apply [finite_measure ν] (h₁ : measurable_set s) (h₂ : ν ≤ μ) : (μ - ν) s = μ s - ν s := begin -- We begin by defining `measure_sub`, which will be equal to `(μ - ν)`. let measure_sub : measure α := @measure_theory.measure.of_measurable α _ (λ (t : set α) (h_t_measurable_set : measurable_set t), (μ t - ν t)) begin simp end begin intros g h_meas h_disj, simp only, rw ennreal.tsum_sub, repeat { rw ← measure_theory.measure_Union h_disj h_meas }, apply measure_theory.measure_lt_top, intro i, apply h₂, apply h_meas end, -- Now, we demonstrate `μ - ν = measure_sub`, and apply it. begin have h_measure_sub_add : (ν + measure_sub = μ), { ext t h_t_measurable_set, simp only [pi.add_apply, coe_add], rw [measure_theory.measure.of_measurable_apply _ h_t_measurable_set, add_comm, ennreal.sub_add_cancel_of_le (h₂ t h_t_measurable_set)] }, have h_measure_sub_eq : (μ - ν) = measure_sub, { rw measure_theory.measure.sub_def, apply le_antisymm, { apply @Inf_le (measure α) (measure.complete_lattice), simp [le_refl, add_comm, h_measure_sub_add] }, apply @le_Inf (measure α) (measure.complete_lattice), intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d, apply measure.le_of_add_le_add_left h_d }, rw h_measure_sub_eq, apply measure.of_measurable_apply _ h₁, end end lemma sub_add_cancel_of_le [finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ := begin ext s h_s_meas, rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)], end end measure_sub lemma restrict_sub_eq_restrict_sub_restrict (h_meas_s : measurable_set s) : (μ - ν).restrict s = (μ.restrict s) - (ν.restrict s) := begin repeat {rw sub_def}, have h_nonempty : {d | μ ≤ d + ν}.nonempty, { apply @set.nonempty_of_mem _ _ μ, rw mem_set_of_eq, intros t h_meas, apply le_add_right (le_refl (μ t)) }, rw restrict_Inf_eq_Inf_restrict h_nonempty h_meas_s, apply le_antisymm, { apply @Inf_le_Inf_of_forall_exists_le (measure α) _, intros ν' h_ν'_in, rw mem_set_of_eq at h_ν'_in, apply exists.intro (ν'.restrict s), split, { rw mem_image, apply exists.intro (ν' + (⊤ : measure_theory.measure α).restrict sᶜ), rw mem_set_of_eq, split, { rw [add_assoc, add_comm _ ν, ← add_assoc, measure_theory.measure.le_iff], intros t h_meas_t, have h_inter_inter_eq_inter : ∀ t' : set α , t ∩ t' ∩ t' = t ∩ t', { intro t', rw set.inter_eq_self_of_subset_left, apply set.inter_subset_right t t' }, have h_meas_t_inter_s : measurable_set (t ∩ s) := h_meas_t.inter h_meas_s, repeat {rw measure_eq_inter_diff h_meas_t h_meas_s, rw set.diff_eq}, apply add_le_add _ _; rw add_apply, { apply le_add_right _, rw add_apply, rw ← @restrict_eq_self _ _ μ s _ h_meas_t_inter_s (set.inter_subset_right _ _), rw ← @restrict_eq_self _ _ ν s _ h_meas_t_inter_s (set.inter_subset_right _ _), apply h_ν'_in _ h_meas_t_inter_s }, cases (@set.eq_empty_or_nonempty _ (t ∩ sᶜ)) with h_inter_empty h_inter_nonempty, { simp [h_inter_empty] }, { have h_meas_inter_compl := h_meas_t.inter (measurable_set.compl h_meas_s), rw [restrict_apply h_meas_inter_compl, h_inter_inter_eq_inter sᶜ], have h_mu_le_add_top : μ ≤ ν' + ν + ⊤, { rw add_comm, have h_le_top : μ ≤ ⊤ := le_top, apply (λ t₂ h_meas, le_add_right (h_le_top t₂ h_meas)) }, apply h_mu_le_add_top _ h_meas_inter_compl } }, { ext1 t h_meas_t, simp [restrict_apply h_meas_t, restrict_apply (h_meas_t.inter h_meas_s), set.inter_assoc] } }, { apply restrict_le_self } }, { apply @Inf_le_Inf_of_forall_exists_le (measure α) _, intros s h_s_in, cases h_s_in with t h_t, cases h_t with h_t_in h_t_eq, subst s, apply exists.intro (t.restrict s), split, { rw [set.mem_set_of_eq, ← restrict_add], apply restrict_mono (set.subset.refl _) h_t_in }, { apply le_refl _ } }, end lemma sub_apply_eq_zero_of_restrict_le_restrict (h_le : μ.restrict s ≤ ν.restrict s) (h_meas_s : measurable_set s) : (μ - ν) s = 0 := begin rw [← restrict_apply_self _ h_meas_s, restrict_sub_eq_restrict_sub_restrict, sub_eq_zero_of_le], repeat {simp [*]}, end end measure end measure_theory open measure_theory measure_theory.measure namespace measurable_equiv /-! Interactions of measurable equivalences and measures -/ open equiv measure_theory.measure variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β} /-- If we map a measure along a measurable equivalence, we can compute the measure on all sets (not just the measurable ones). -/ protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : map f μ s = μ (f ⁻¹' s) := begin refine le_antisymm _ (le_map_apply f.measurable s), rw [measure_eq_infi' μ], refine le_infi _, rintro ⟨t, hst, ht⟩, rw [subtype.coe_mk], have := f.symm.to_equiv.image_eq_preimage, simp only [←coe_eq, symm_symm, symm_to_equiv] at this, rw [← this, image_subset_iff] at hst, convert measure_mono hst, rw [map_apply, preimage_preimage], { refine congr_arg μ (eq.symm _), convert preimage_id, exact funext f.left_inv }, exacts [f.measurable, f.measurable_inv_fun ht] end @[simp] lemma map_symm_map (e : α ≃ᵐ β) : map e.symm (map e μ) = μ := by simp [map_map e.symm.measurable e.measurable] @[simp] lemma map_map_symm (e : α ≃ᵐ β) : map e (map e.symm ν) = ν := by simp [map_map e.measurable e.symm.measurable] lemma map_measurable_equiv_injective (e : α ≃ᵐ β) : injective (map e) := by { intros μ₁ μ₂ hμ, apply_fun map e.symm at hμ, simpa [map_symm_map e] using hμ } lemma map_apply_eq_iff_map_symm_apply_eq (e : α ≃ᵐ β) : map e μ = ν ↔ map e.symm ν = μ := by rw [← (map_measurable_equiv_injective e).eq_iff, map_map_symm, eq_comm] end measurable_equiv section is_complete /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ class measure_theory.measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop := (out' : ∀ s, μ s = 0 → measurable_set s) theorem measure_theory.measure.is_complete_iff {_ : measurable_space α} {μ : measure α} : μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem measure_theory.measure.is_complete.out {_ : measurable_space α} {μ : measure α} (h : μ.is_complete) : ∀ s, μ s = 0 → measurable_set s := h.1 variables [measurable_space α] {μ : measure α} {s t z : set α} /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def null_measurable_set (μ : measure α) (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ measurable_set t ∧ μ z = 0 theorem null_measurable_set_iff : null_measurable_set μ s ↔ ∃ t, t ⊆ s ∧ measurable_set t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem null_measurable_set_measure_eq (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem measurable_set.null_measurable_set (μ : measure α) (hs : measurable_set s) : null_measurable_set μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem null_measurable_set_of_complete (μ : measure α) [c : μ.is_complete] : null_measurable_set μ s ↔ measurable_set s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact measurable_set.union ht (c.out _ hz), λ h, h.null_measurable_set _⟩ theorem null_measurable_set.union_null (hs : null_measurable_set μ s) (hz : μ z = 0) : null_measurable_set μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_null_measurable_set (hz : μ z = 0) : null_measurable_set μ z := by simpa using (measurable_set.empty.null_measurable_set _).union_null hz theorem null_measurable_set.Union_nat {s : ℕ → set α} (hs : ∀ i, null_measurable_set μ (s i)) : null_measurable_set μ (Union s) := begin choose t ht using assume i, null_measurable_set_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine null_measurable_set_iff.2 ⟨Union t, Union_subset_Union st, measurable_set.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem measurable_set.diff_null (hs : measurable_set s) (hz : μ z = 0) : null_measurable_set μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q : ℚ // q > 0}, ∃ t : set α, z ⊆ t ∧ measurable_set t ∧ μ t < (nnreal.of_real q.1 : ℝ≥0∞), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ℝ≥0∞), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine null_measurable_set_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (measurable_set.Inter (λ i, (hf i).2.1)), measure_mono_null _ (nonpos_iff_eq_zero.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem null_measurable_set.diff_null (hs : null_measurable_set μ s) (hz : μ z = 0) : null_measurable_set μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem null_measurable_set.compl (hs : null_measurable_set μ s) : null_measurable_set μ sᶜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end theorem null_measurable_set_iff_ae {s : set α} : null_measurable_set μ s ↔ ∃ t, measurable_set t ∧ s =ᵐ[μ] t := begin simp only [ae_eq_set], split, { assume h, rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩, refine ⟨t, tmeas, ht, _⟩, rw [diff_eq_empty.2 ts, measure_empty] }, { rintros ⟨t, tmeas, h₁, h₂⟩, have : null_measurable_set μ (t ∪ (s \ t)) := null_measurable_set.union_null (tmeas.null_measurable_set _) h₁, have A : null_measurable_set μ ((t ∪ (s \ t)) \ (t \ s)) := null_measurable_set.diff_null this h₂, have : (t ∪ (s \ t)) \ (t \ s) = s, { apply subset.antisymm, { assume x hx, simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx, cases hx.1, { exact hx.2 h }, { exact h.1 } }, { assume x hx, simp [hx, classical.em (x ∈ t)] } }, rwa this at A } end theorem null_measurable_set_iff_sandwich {s : set α} : null_measurable_set μ s ↔ ∃ (t u : set α), measurable_set t ∧ measurable_set u ∧ t ⊆ s ∧ s ⊆ u ∧ μ (u \ t) = 0 := begin split, { assume h, rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩, rcases null_measurable_set_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩, have A : s ⊆ u'ᶜ := subset_compl_comm.mp u's, refine ⟨t, u'ᶜ, tmeas, u'meas.compl, ts, A, _⟩, have : sᶜ \ u' = u'ᶜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm], rw this at hu', apply le_antisymm _ bot_le, calc μ (u'ᶜ \ t) ≤ μ ((u'ᶜ \ s) ∪ (s \ t)) : begin apply measure_mono, assume x hx, simp at hx, simp [hx, or_comm, classical.em], end ... ≤ μ (u'ᶜ \ s) + μ (s \ t) : measure_union_le _ _ ... = 0 : by rw [ht, hu', zero_add] }, { rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩, refine null_measurable_set_iff.2 ⟨t, ts, tmeas, _⟩, apply le_antisymm _ bot_le, calc μ (s \ t) ≤ μ (u \ t) : measure_mono (diff_subset_diff_left su) ... = 0 : hμ } end lemma restrict_apply_of_null_measurable_set {s t : set α} (ht : null_measurable_set (μ.restrict s) t) : μ.restrict s t = μ (t ∩ s) := begin rcases null_measurable_set_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩, apply le_antisymm _ (le_restrict_apply _ _), calc μ.restrict s t ≤ μ.restrict s v : measure_mono tv ... = μ (v ∩ s) : restrict_apply vmeas ... ≤ μ ((u ∩ s) ∪ ((v \ u) ∩ s)) : measure_mono $ by { assume x hx, simp at hx, simp [hx, classical.em] } ... ≤ μ (u ∩ s) + μ ((v \ u) ∩ s) : measure_union_le _ _ ... = μ (u ∩ s) + μ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas) ... = μ (u ∩ s) : by rw [huv, add_zero] ... ≤ μ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut end /-- The measurable space of all null measurable sets. -/ def null_measurable (μ : measure α) : measurable_space α := { measurable_set' := null_measurable_set μ, measurable_set_empty := measurable_set.empty.null_measurable_set _, measurable_set_compl := λ s hs, hs.compl, measurable_set_Union := λ f, null_measurable_set.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, null_measurable_set_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw null_measurable_set_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (null_measurable_set_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.null_measurable_set _, le_refl _⟩) end } instance completion.is_complete (μ : measure α) : (completion μ).is_complete := ⟨λ z hz, null_null_measurable_set hz⟩ lemma measurable.ae_eq {α β} [measurable_space α] [measurable_space β] {μ : measure α} [hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) : measurable g := begin intros s hs, let t := {x | f x = g x}, have ht_compl : μ tᶜ = 0, by rwa [filter.eventually_eq, ae_iff] at hfg, rw (set.inter_union_compl (g ⁻¹' s) t).symm, refine measurable_set.union _ _, { have h_g_to_f : (g ⁻¹' s) ∩ t = (f ⁻¹' s) ∩ t, { ext, simp only [set.mem_inter_iff, set.mem_preimage, and.congr_left_iff, set.mem_set_of_eq], exact λ hx, by rw hx, }, rw h_g_to_f, exact measurable_set.inter (hf hs) (measurable_set.compl_iff.mp (hμ.out tᶜ ht_compl)), }, { exact hμ.out (g ⁻¹' s ∩ tᶜ) (measure_mono_null (set.inter_subset_right _ _) ht_compl), }, end end is_complete namespace measure_theory /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space variables [measure_space α] {s₁ s₂ : set α} notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end measure_theory /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. We define this property, called `ae_measurable f μ`, and discuss several of its properties that are analogous to properties of measurable functions. -/ section open measure_theory variables [measurable_space α] [measurable_space β] {f g : α → β} {μ ν : measure α} /-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. -/ def ae_measurable (f : α → β) (μ : measure α . measure_theory.volume_tac) : Prop := ∃ g : α → β, measurable g ∧ f =ᵐ[μ] g lemma measurable.ae_measurable (h : measurable f) : ae_measurable f μ := ⟨f, h, ae_eq_refl f⟩ @[nontriviality] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[simp] lemma ae_measurable_zero : ae_measurable f 0 := begin nontriviality α, inhabit α, exact ⟨λ x, f (default α), measurable_const, rfl⟩ end lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := begin split; intro h, { rcases h with ⟨g, hg_meas, hfg⟩, exact hg_meas.ae_eq hfg.symm, }, { exact h.ae_measurable, }, end namespace ae_measurable /-- Given an almost everywhere measurable function `f`, associate to it a measurable function that coincides with it almost everywhere. `f` is explicit in the definition to make sure that it shows in pretty-printing. -/ def mk (f : α → β) (h : ae_measurable f μ) : α → β := classical.some h lemma measurable_mk (h : ae_measurable f μ) : measurable (h.mk f) := (classical.some_spec h).1 lemma ae_eq_mk (h : ae_measurable f μ) : f =ᵐ[μ] (h.mk f) := (classical.some_spec h).2 lemma congr (hf : ae_measurable f μ) (h : f =ᵐ[μ] g) : ae_measurable g μ := ⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩ lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := begin let s := {x | f x ≠ hμ.mk f x}, have : μ s = 0 := hμ.ae_eq_mk, obtain ⟨t, st, t_meas, μt⟩ : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 := exists_measurable_superset_of_null this, let g : α → β := t.piecewise (hν.mk f) (hμ.mk f), refine ⟨g, measurable.piecewise t_meas hν.measurable_mk hμ.measurable_mk, _⟩, change μ {x | f x ≠ g x} + ν {x | f x ≠ g x} = 0, suffices : μ {x | f x ≠ g x} = 0 ∧ ν {x | f x ≠ g x} = 0, by simp [this.1, this.2], have ht : {x | f x ≠ g x} ⊆ t, { assume x hx, by_contra h, simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx, exact h (st hx) }, split, { have : μ {x | f x ≠ g x} ≤ μ t := measure_mono ht, rw μt at this, exact le_antisymm this bot_le }, { have : {x | f x ≠ g x} ⊆ {x | f x ≠ hν.mk f x}, { assume x hx, simpa [ht hx, g] using hx }, apply le_antisymm _ bot_le, calc ν {x | f x ≠ g x} ≤ ν {x | f x ≠ hν.mk f x} : measure_mono this ... = 0 : hν.ae_eq_mk } end lemma smul_measure (h : ae_measurable f μ) (c : ℝ≥0∞) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : ae_measurable g (map f μ)) (hf : measurable f) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩ lemma comp_measurable' {δ} [measurable_space δ] {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : measurable f) (h : map f μ ≪ ν) : ae_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma prod_mk {γ : Type*} [measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma null_measurable_set (h : ae_measurable f μ) {s : set β} (hs : measurable_set s) : null_measurable_set μ (f ⁻¹' s) := begin apply null_measurable_set_iff_ae.2, refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩, filter_upwards [h.ae_eq_mk], assume x hx, change (f x ∈ s) = ((h.mk f) x ∈ s), rwa hx end end ae_measurable lemma ae_measurable_congr (h : f =ᵐ[μ] g) : ae_measurable f μ ↔ ae_measurable g μ := ⟨λ hf, ae_measurable.congr hf h, λ hg, ae_measurable.congr hg h.symm⟩ @[simp] lemma ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ @[simp] lemma ae_measurable_const {b : β} : ae_measurable (λ a : α, b) μ := measurable_const.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma measurable.comp_ae_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : measurable g) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩ lemma ae_measurable_of_zero_measure {f : α → β} : ae_measurable f 0 := begin by_cases h : nonempty α, { exact (@ae_measurable_const _ _ _ _ _ (f h.some)).congr rfl }, { exact (measurable_of_not_nonempty h f).ae_measurable } end end namespace is_compact variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α} lemma finite_measure_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ∞ := by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter] using hs.compl_mem_sets_of_nhds_within lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ∞ := hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _ lemma measure_zero_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 := by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within end is_compact lemma metric.bounded.finite_measure [metric_space α] [proper_space α] [measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : metric.bounded s) : μ s < ∞ := (measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2 ⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
fdf343e3dca924a6de59380c84232a6695218366
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Environment.lean
8aeb8a264199756346e2459bf83a7e0827cc6f6e
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
30,226
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 Std.Data.HashMap import Lean.Data.SMap import Lean.Declaration import Lean.LocalContext import Lean.Util.Path import Lean.Util.FindExpr import Lean.Util.Profile namespace Lean /- Opaque environment extension state. -/ constant EnvExtensionStateSpec : PointedType.{0} def EnvExtensionState : Type := EnvExtensionStateSpec.type instance : Inhabited EnvExtensionState where default := EnvExtensionStateSpec.val def ModuleIdx := Nat instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import where module : Name runtimeOnly : Bool := false instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /-- A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions. -/ def CompactedRegion := USize /-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/ @[extern 2 "lean_compacted_region_free"] unsafe constant CompactedRegion.free : CompactedRegion → IO Unit /- Environment fields that are not used often. -/ structure EnvironmentHeader where trustLevel : UInt32 := 0 quotInit : Bool := false mainModule : Name := arbitrary imports : Array Import := #[] -- direct imports regions : Array CompactedRegion := #[] -- compacted regions of all imported modules moduleNames : Array Name := #[] -- names of all imported modules deriving Inhabited open Std (HashMap) structure Environment where const2ModIdx : HashMap Name ModuleIdx constants : ConstMap extensions : Array EnvExtensionState header : EnvironmentHeader := {} deriving Inhabited namespace Environment def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { env with constants := env.constants.insert cinfo.name cinfo } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports def allImportedModuleNames (env : Environment) : Array Name := env.header.moduleNames @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { env with header := { env.header with mainModule := m } } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { env with header := { env.header with quotInit := true } } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx := env.const2ModIdx.find? c def isConstructor (env : Environment) (c : Name) : Bool := match env.find? c with | ConstantInfo.ctorInfo _ => true | _ => false end Environment inductive KernelException where | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do let env ← addDecl env decl compileDecl env opt decl end Environment /- Interface for managing environment extensions. -/ structure EnvExtensionInterface where ext : Type → Type inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ) registerExt {σ} (mkInitial : IO σ) : IO (ext σ) setState {σ} (e : ext σ) (env : Environment) : σ → Environment modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment getState {σ} (e : ext σ) (env : Environment) : σ mkInitialExtStates : IO (Array EnvExtensionState) instance : Inhabited EnvExtensionInterface where default := { ext := id, inhabitedExt := id, registerExt := fun mk => mk, setState := fun _ env _ => env, modifyState := fun _ env _ => env, getState := fun ext _ => ext, mkInitialExtStates := pure #[] } /- Unsafe implementation of `EnvExtensionInterface` -/ namespace EnvExtensionInterfaceUnsafe structure Ext (σ : Type) where idx : Nat mkInitial : IO σ deriving Inhabited private def mkEnvExtensionsRef : IO (IO.Ref (Array (Ext EnvExtensionState))) := IO.mkRef #[] @[builtinInit mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment := { env with extensions := env.extensions.set! ext.idx (unsafeCast s) } @[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment := { env with extensions := env.extensions.modify ext.idx fun s => let s : σ := unsafeCast s; let s : σ := f s; unsafeCast s } unsafe def getState {σ} (ext : Ext σ) (env : Environment) : σ := let s : EnvExtensionState := env.extensions.get! ext.idx unsafeCast s unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do let initializing ← IO.initializing unless initializing do throw (IO.userError "failed to register environment, extensions can only be registered during initialization") let exts ← envExtensionsRef.get let idx := exts.size let ext : Ext σ := { idx := idx, mkInitial := mkInitial, } envExtensionsRef.modify fun exts => exts.push (unsafeCast ext) pure ext def mkInitialExtStates : IO (Array EnvExtensionState) := do let exts ← envExtensionsRef.get exts.mapM fun ext => ext.mkInitial unsafe def imp : EnvExtensionInterface := { ext := Ext, inhabitedExt := fun _ => ⟨arbitrary⟩, registerExt := registerExt, setState := setState, modifyState := modifyState, getState := getState, mkInitialExtStates := mkInitialExtStates } end EnvExtensionInterfaceUnsafe @[implementedBy EnvExtensionInterfaceUnsafe.imp] constant EnvExtensionInterfaceImp : EnvExtensionInterface def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ namespace EnvExtension instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f def getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env end EnvExtension /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do let initializing ← IO.initializing if initializing then throw (IO.userError "environment objects cannot be created during initialization") let exts ← mkInitialExtensionStates pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) where importedEntries : Array (Array α) -- entries per imported module state : σ structure ImportM.Context where env : Environment opts : Options abbrev ImportM := ReaderT Lean.ImportM.Context IO /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ) name : Name addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format /- Opaque persistent environment extension entry. -/ constant EnvExtensionEntrySpec : PointedType.{0} def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩ instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary }⟩ instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where default := { toEnvExtension := arbitrary, name := arbitrary, addImportedFn := fun _ => arbitrary, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil } namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env fun s => let state := ext.addEntryFn s.state b; { s with state := state } def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) } end PersistentEnvExtension builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] structure PersistentEnvExtensionDescr (α β σ : Type) where name : Name mkInitial : IO σ addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format := fun _ => Format.nil unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do let pExts ← persistentEnvExtensionsRef.get if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used") let ext ← registerEnvExtension do let initial ← descr.mkInitial let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial } pure s let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn } persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt) return pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) where name : Name addEntryFn : σ → α → σ addImportedFn : Array (Array α) → σ toArrayFn : List α → Array α := fun es => es.toArray def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /-- Environment extension for mapping declarations to values. -/ def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α) def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n.1 n.2 , toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } namespace MapDeclarationExtension instance : Inhabited (MapDeclarationExtension α) := inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..)) def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment := ext.addEntry env (declName, val) def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α := match env.getModuleIdxFor? declName with | some modIdx => match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (ext.getState env).find? declName def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool := match env.getModuleIdxFor? declName with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) | none => (ext.getState env).contains declName end MapDeclarationExtension /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData where imports : Array Import constants : Array ConstantInfo entries : Array (Name × Array EnvExtensionEntry) instance : Inhabited ModuleData := ⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩ @[extern 3 "lean_save_module_data"] constant saveModuleData (fname : @& System.FilePath) (m : ModuleData) : IO Unit @[extern 2 "lean_read_module_data"] constant readModuleData (fname : @& System.FilePath) : IO (ModuleData × CompactedRegion) /-- Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, `env` should be the last reference to any `Environment` derived from these imports. -/ @[noinline, export lean_environment_free_regions] unsafe def Environment.freeRegions (env : Environment) : IO Unit := /- NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field. Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in compacted regions, is freed after the regions. In the currently produced IR, we indeed see: ``` def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj := let x_3 : obj := proj[3] x_1; inc x_3; dec x_1; ... ``` TODO: statically check for this. -/ env.header.regions.forM CompactedRegion.free def mkModuleData (env : Environment) : IO ModuleData := do let pExts ← persistentEnvExtensionsRef.get let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env let exportEntriesFn := (pExts.get! i).exportEntriesFn let extName := (pExts.get! i).name result.push (extName, exportEntriesFn state)) #[] pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries } @[export lean_write_module] def writeModule (env : Environment) (fname : System.FilePath) : IO Unit := do let modData ← mkModuleData env; saveModuleData fname modData private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry := if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for mod in mods do for extDescr in pExtDescrs do let entries := getEntriesFor mod extDescr.name 0 env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries } return env private def finalizePersistentExtensions (env : Environment) (opts : Options) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for extDescr in pExtDescrs do let s := extDescr.toEnvExtension.getState env let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts } env ← extDescr.toEnvExtension.setState env { s with state := newState } return env structure ImportState where moduleNameSet : NameSet := {} moduleNames : Array Name := #[] moduleData : Array ModuleData := #[] regions : Array CompactedRegion := #[] @[export lean_import_modules] partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do let (_, s) ← importMods imports |>.run {} -- (moduleNames, mods, regions) let mut modIdx : Nat := 0 let mut const2ModIdx : HashMap Name ModuleIdx := {} let mut constants : ConstMap := SMap.empty for mod in s.moduleData do for cinfo in mod.constants do const2ModIdx := const2ModIdx.insert cinfo.name modIdx if constants.contains cinfo.name then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'") constants := constants.insert cinfo.name cinfo modIdx := modIdx + 1 constants := constants.switch let exts ← mkInitialExtensionStates let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray, regions := s.regions, moduleNames := s.moduleNames } } let env ← setImportedEntries env s.moduleData let env ← finalizePersistentExtensions env opts pure env where importMods : List Import → StateRefT ImportState IO Unit | [] => pure () | i::is => do if i.runtimeOnly || (← get).moduleNameSet.contains i.module then importMods is else do modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module } let mFile ← findOLean i.module unless (← mFile.pathExists) do throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist" let (mod, region) ← readModuleData mFile importMods mod.imports.toList modify fun s => { s with moduleData := s.moduleData.push mod regions := s.regions.push region moduleNames := s.moduleNames.push i.module } importMods is /-- Create environment object from imports and free compacted regions after calling `act`. No live references to the environment object or imported objects may exist after `act` finishes. -/ unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do let env ← importModules imports opts trustLevel try x env finally env.freeRegions builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSet ← registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as, addEntryFn := fun s n => s.insert n } namespace Environment def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSet := namespacesExt.getState env private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do let pExtDescrs ← persistentEnvExtensionsRef.get let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size; IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString numModules); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do IO.println ("extension '" ++ toString extDescr.name ++ "'") let s := extDescr.toEnvExtension.getState env let fmt := extDescr.statsFn s.state unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))) IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)) @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α := throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected") /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/ unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α := match env.find? constName with | none => throw ("unknow constant '" ++ toString constName ++ "'") | some info => match info.type with | Expr.const c _ _ => if c != typeName then throwUnexpectedType typeName constName else env.evalConst α opts constName | _ => throwUnexpectedType typeName constName def hasUnsafe (env : Environment) (e : Expr) : Bool := let c? := e.find? $ fun e => match e with | Expr.const c _ _ => match env.find? c with | some cinfo => cinfo.isUnsafe | none => false | _ => false; c?.isSome end Environment namespace Kernel /- Kernel API -/ /-- Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_is_def_eq"] constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool /-- Kernel WHNF function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_whnf"] constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr end Kernel class MonadEnv (m : Type → Type) where getEnv : m Environment modifyEnv : (Environment → Environment) → m Unit export MonadEnv (getEnv modifyEnv) instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where getEnv := liftM (getEnv : m Environment) modifyEnv := fun f => liftM (modifyEnv f : m Unit) end Lean
23bb90272e14eda0f3744723f47187d5e0f84804
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/discovery/collector/common.lean
1947d42f6ccfcbf3d20aa9c6ecf4d313c6fa0dd7
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
623
lean
import tactic.rewrite_all import ..screening open tactic namespace tactic.rewrite_search.discovery meta def are_promising_rewrites (rws : list (expr × bool)) : list expr → tactic bool | [] := return false | (s :: rest) := do -- TODO alternative (and probably better) condition: -- tt if the rewrite list contains an expression not seen in the rewrite_search -- instance, ff otherwise. Maybe too harsh/coarse? e ← mllist.empty (all_rewrites rws s), return e.down meta def is_promising_rewrite (rw : expr × bool) : list expr → tactic bool := are_promising_rewrites [rw] end tactic.rewrite_search.discovery
49fb19e1de7ca07cc1647e1c47040b280cbaa7d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/solvable.lean
e463807199cc54b9c0856742e0095f4ff3becd44
[ "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
13,934
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.abelian import algebra.lie.ideal_operations import order.hom.basic /-! # Solvable Lie algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Like groups, Lie algebras admit a natural concept of solvability. We define this here via the derived series and prove some related results. We also define the radical of a Lie algebra and prove that it is solvable when the Lie algebra is Noetherian. ## Main definitions * `lie_algebra.derived_series_of_ideal` * `lie_algebra.derived_series` * `lie_algebra.is_solvable` * `lie_algebra.is_solvable_add` * `lie_algebra.radical` * `lie_algebra.radical_is_solvable` * `lie_algebra.derived_length_of_ideal` * `lie_algebra.derived_length` * `lie_algebra.derived_abelian_of_ideal` ## Tags lie algebra, derived series, derived length, solvable, radical -/ universes u v w w₁ w₂ variables (R : Type u) (L : Type v) (M : Type w) {L' : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables (I J : lie_ideal R L) {f : L' →ₗ⁅R⁆ L} namespace lie_algebra /-- A generalisation of the derived series of a Lie algebra, whose zeroth term is a specified ideal. It can be more convenient to work with this generalisation when considering the derived series of an ideal since it provides a type-theoretic expression of the fact that the terms of the ideal's derived series are also ideals of the enclosing algebra. See also `lie_ideal.derived_series_eq_derived_series_of_ideal_comap` and `lie_ideal.derived_series_eq_derived_series_of_ideal_map` below. -/ def derived_series_of_ideal (k : ℕ) : lie_ideal R L → lie_ideal R L := (λ I, ⁅I, I⁆)^[k] @[simp] lemma derived_series_of_ideal_zero : derived_series_of_ideal R L 0 I = I := rfl @[simp] lemma derived_series_of_ideal_succ (k : ℕ) : derived_series_of_ideal R L (k + 1) I = ⁅derived_series_of_ideal R L k I, derived_series_of_ideal R L k I⁆ := function.iterate_succ_apply' (λ I, ⁅I, I⁆) k I /-- The derived series of Lie ideals of a Lie algebra. -/ abbreviation derived_series (k : ℕ) : lie_ideal R L := derived_series_of_ideal R L k ⊤ lemma derived_series_def (k : ℕ) : derived_series R L k = derived_series_of_ideal R L k ⊤ := rfl variables {R L} local notation `D` := derived_series_of_ideal R L lemma derived_series_of_ideal_add (k l : ℕ) : D (k + l) I = D k (D l I) := begin induction k with k ih, { rw [zero_add, derived_series_of_ideal_zero], }, { rw [nat.succ_add k l, derived_series_of_ideal_succ, derived_series_of_ideal_succ, ih], }, end @[mono] lemma derived_series_of_ideal_le {I J : lie_ideal R L} {k l : ℕ} (h₁ : I ≤ J) (h₂ : l ≤ k) : D k I ≤ D l J := begin revert l, induction k with k ih; intros l h₂, { rw le_zero_iff at h₂, rw [h₂, derived_series_of_ideal_zero], exact h₁, }, { have h : l = k.succ ∨ l ≤ k, by rwa [le_iff_eq_or_lt, nat.lt_succ_iff] at h₂, cases h, { rw [h, derived_series_of_ideal_succ, derived_series_of_ideal_succ], exact lie_submodule.mono_lie _ _ _ _ (ih (le_refl k)) (ih (le_refl k)), }, { rw derived_series_of_ideal_succ, exact le_trans (lie_submodule.lie_le_left _ _) (ih h), }, }, end lemma derived_series_of_ideal_succ_le (k : ℕ) : D (k + 1) I ≤ D k I := derived_series_of_ideal_le (le_refl I) k.le_succ lemma derived_series_of_ideal_le_self (k : ℕ) : D k I ≤ I := derived_series_of_ideal_le (le_refl I) (zero_le k) lemma derived_series_of_ideal_mono {I J : lie_ideal R L} (h : I ≤ J) (k : ℕ) : D k I ≤ D k J := derived_series_of_ideal_le h (le_refl k) lemma derived_series_of_ideal_antitone {k l : ℕ} (h : l ≤ k) : D k I ≤ D l I := derived_series_of_ideal_le (le_refl I) h lemma derived_series_of_ideal_add_le_add (J : lie_ideal R L) (k l : ℕ) : D (k + l) (I + J) ≤ (D k I) + (D l J) := begin let D₁ : lie_ideal R L →o lie_ideal R L := { to_fun := λ I, ⁅I, I⁆, monotone' := λ I J h, lie_submodule.mono_lie I J I J h h, }, have h₁ : ∀ (I J : lie_ideal R L), D₁ (I ⊔ J) ≤ (D₁ I) ⊔ J, { simp [lie_submodule.lie_le_right, lie_submodule.lie_le_left, le_sup_of_le_right], }, rw ← D₁.iterate_sup_le_sup_iff at h₁, exact h₁ k l I J, end lemma derived_series_of_bot_eq_bot (k : ℕ) : derived_series_of_ideal R L k ⊥ = ⊥ := by { rw eq_bot_iff, exact derived_series_of_ideal_le_self ⊥ k, } lemma abelian_iff_derived_one_eq_bot : is_lie_abelian I ↔ derived_series_of_ideal R L 1 I = ⊥ := by rw [derived_series_of_ideal_succ, derived_series_of_ideal_zero, lie_submodule.lie_abelian_iff_lie_self_eq_bot] lemma abelian_iff_derived_succ_eq_bot (I : lie_ideal R L) (k : ℕ) : is_lie_abelian (derived_series_of_ideal R L k I) ↔ derived_series_of_ideal R L (k + 1) I = ⊥ := by rw [add_comm, derived_series_of_ideal_add I 1 k, abelian_iff_derived_one_eq_bot] end lie_algebra namespace lie_ideal open lie_algebra variables {R L} lemma derived_series_eq_derived_series_of_ideal_comap (k : ℕ) : derived_series R I k = (derived_series_of_ideal R L k I).comap I.incl := begin induction k with k ih, { simp only [derived_series_def, comap_incl_self, derived_series_of_ideal_zero], }, { simp only [derived_series_def, derived_series_of_ideal_succ] at ⊢ ih, rw ih, exact comap_bracket_incl_of_le I (derived_series_of_ideal_le_self I k) (derived_series_of_ideal_le_self I k), }, end lemma derived_series_eq_derived_series_of_ideal_map (k : ℕ) : (derived_series R I k).map I.incl = derived_series_of_ideal R L k I := by { rw [derived_series_eq_derived_series_of_ideal_comap, map_comap_incl, inf_eq_right], apply derived_series_of_ideal_le_self, } lemma derived_series_eq_bot_iff (k : ℕ) : derived_series R I k = ⊥ ↔ derived_series_of_ideal R L k I = ⊥ := by rw [← derived_series_eq_derived_series_of_ideal_map, map_eq_bot_iff, ker_incl, eq_bot_iff] lemma derived_series_add_eq_bot {k l : ℕ} {I J : lie_ideal R L} (hI : derived_series R I k = ⊥) (hJ : derived_series R J l = ⊥) : derived_series R ↥(I + J) (k + l) = ⊥ := begin rw lie_ideal.derived_series_eq_bot_iff at hI hJ ⊢, rw ← le_bot_iff, let D := derived_series_of_ideal R L, change D k I = ⊥ at hI, change D l J = ⊥ at hJ, calc D (k + l) (I + J) ≤ (D k I) + (D l J) : derived_series_of_ideal_add_le_add I J k l ... ≤ ⊥ : by { rw [hI, hJ], simp, }, end lemma derived_series_map_le (k : ℕ) : (derived_series R L' k).map f ≤ derived_series R L k := begin induction k with k ih, { simp only [derived_series_def, derived_series_of_ideal_zero, le_top], }, { simp only [derived_series_def, derived_series_of_ideal_succ] at ih ⊢, exact le_trans (map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ ih ih), }, end lemma derived_series_map_eq (k : ℕ) (h : function.surjective f) : (derived_series R L' k).map f = derived_series R L k := begin induction k with k ih, { change (⊤ : lie_ideal R L').map f = ⊤, rw ←f.ideal_range_eq_map, exact f.ideal_range_eq_top_of_surjective h, }, { simp only [derived_series_def, map_bracket_eq f h, ih, derived_series_of_ideal_succ], }, end end lie_ideal namespace lie_algebra /-- A Lie algebra is solvable if its derived series reaches 0 (in a finite number of steps). -/ class is_solvable : Prop := (solvable : ∃ k, derived_series R L k = ⊥) instance is_solvable_bot : is_solvable R ↥(⊥ : lie_ideal R L) := ⟨⟨0, subsingleton.elim _ ⊥⟩⟩ instance is_solvable_add {I J : lie_ideal R L} [hI : is_solvable R I] [hJ : is_solvable R J] : is_solvable R ↥(I + J) := begin obtain ⟨k, hk⟩ := id hI, obtain ⟨l, hl⟩ := id hJ, exact ⟨⟨k+l, lie_ideal.derived_series_add_eq_bot hk hl⟩⟩, end end lie_algebra variables {R L} namespace function open lie_algebra lemma injective.lie_algebra_is_solvable [h₁ : is_solvable R L] (h₂ : injective f) : is_solvable R L' := begin obtain ⟨k, hk⟩ := id h₁, use k, apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk], apply lie_ideal.derived_series_map_le, end lemma surjective.lie_algebra_is_solvable [h₁ : is_solvable R L'] (h₂ : surjective f) : is_solvable R L := begin obtain ⟨k, hk⟩ := id h₁, use k, rw [← lie_ideal.derived_series_map_eq k h₂, hk], simp only [lie_ideal.map_eq_bot_iff, bot_le], end end function lemma lie_hom.is_solvable_range (f : L' →ₗ⁅R⁆ L) [h : lie_algebra.is_solvable R L'] : lie_algebra.is_solvable R f.range := f.surjective_range_restrict.lie_algebra_is_solvable namespace lie_algebra lemma solvable_iff_equiv_solvable (e : L' ≃ₗ⁅R⁆ L) : is_solvable R L' ↔ is_solvable R L := begin split; introsI h, { exact e.symm.injective.lie_algebra_is_solvable, }, { exact e.injective.lie_algebra_is_solvable, }, end lemma le_solvable_ideal_solvable {I J : lie_ideal R L} (h₁ : I ≤ J) (h₂ : is_solvable R J) : is_solvable R I := (lie_ideal.hom_of_le_injective h₁).lie_algebra_is_solvable variables (R L) @[priority 100] instance of_abelian_is_solvable [is_lie_abelian L] : is_solvable R L := begin use 1, rw [← abelian_iff_derived_one_eq_bot, lie_abelian_iff_equiv_lie_abelian lie_ideal.top_equiv], apply_instance, end /-- The (solvable) radical of Lie algebra is the `Sup` of all solvable ideals. -/ def radical := Sup { I : lie_ideal R L | is_solvable R I } /-- The radical of a Noetherian Lie algebra is solvable. -/ instance radical_is_solvable [is_noetherian R L] : is_solvable R (radical R L) := begin have hwf := lie_submodule.well_founded_of_noetherian R L L, rw ← complete_lattice.is_sup_closed_compact_iff_well_founded at hwf, refine hwf { I : lie_ideal R L | is_solvable R I } ⟨⊥, _⟩ (λ I hI J hJ, _), { exact lie_algebra.is_solvable_bot R L, }, { apply lie_algebra.is_solvable_add R L, exacts [hI, hJ] }, end /-- The `→` direction of this lemma is actually true without the `is_noetherian` assumption. -/ lemma lie_ideal.solvable_iff_le_radical [is_noetherian R L] (I : lie_ideal R L) : is_solvable R I ↔ I ≤ radical R L := ⟨λ h, le_Sup h, λ h, le_solvable_ideal_solvable h infer_instance⟩ lemma center_le_radical : center R L ≤ radical R L := have h : is_solvable R (center R L), { apply_instance, }, le_Sup h /-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the natural number `k` (the number of inclusions). For a non-solvable ideal, the value is 0. -/ noncomputable def derived_length_of_ideal (I : lie_ideal R L) : ℕ := Inf {k | derived_series_of_ideal R L k I = ⊥} /-- The derived length of a Lie algebra is the derived length of its 'top' Lie ideal. See also `lie_algebra.derived_length_eq_derived_length_of_ideal`. -/ noncomputable abbreviation derived_length : ℕ := derived_length_of_ideal R L ⊤ lemma derived_series_of_derived_length_succ (I : lie_ideal R L) (k : ℕ) : derived_length_of_ideal R L I = k + 1 ↔ is_lie_abelian (derived_series_of_ideal R L k I) ∧ derived_series_of_ideal R L k I ≠ ⊥ := begin rw abelian_iff_derived_succ_eq_bot, let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s, have hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s, { intros k₁ k₂ h₁₂ h₁, suffices : derived_series_of_ideal R L k₂ I ≤ ⊥, { exact eq_bot_iff.mpr this, }, change derived_series_of_ideal R L k₁ I = ⊥ at h₁, rw ← h₁, exact derived_series_of_ideal_antitone I h₁₂, }, exact nat.Inf_upward_closed_eq_succ_iff hs k, end lemma derived_length_eq_derived_length_of_ideal (I : lie_ideal R L) : derived_length R I = derived_length_of_ideal R L I := begin let s₁ := {k | derived_series R I k = ⊥}, let s₂ := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s₁ = Inf s₂, congr, ext k, exact I.derived_series_eq_bot_iff k, end variables {R L} /-- Given a solvable Lie ideal `I` with derived series `I = D₀ ≥ D₁ ≥ ⋯ ≥ Dₖ = ⊥`, this is the `k-1`th term in the derived series (and is therefore an Abelian ideal contained in `I`). For a non-solvable ideal, this is the zero ideal, `⊥`. -/ noncomputable def derived_abelian_of_ideal (I : lie_ideal R L) : lie_ideal R L := match derived_length_of_ideal R L I with | 0 := ⊥ | k + 1 := derived_series_of_ideal R L k I end lemma abelian_derived_abelian_of_ideal (I : lie_ideal R L) : is_lie_abelian (derived_abelian_of_ideal I) := begin dunfold derived_abelian_of_ideal, cases h : derived_length_of_ideal R L I with k, { exact is_lie_abelian_bot R L, }, { rw derived_series_of_derived_length_succ at h, exact h.1, }, end lemma derived_length_zero (I : lie_ideal R L) [hI : is_solvable R I] : derived_length_of_ideal R L I = 0 ↔ I = ⊥ := begin let s := {k | derived_series_of_ideal R L k I = ⊥}, change Inf s = 0 ↔ _, have hne : s ≠ ∅, { obtain ⟨k, hk⟩ := id hI, refine set.nonempty.ne_empty ⟨k, _⟩, rw [derived_series_def, lie_ideal.derived_series_eq_bot_iff] at hk, exact hk, }, simp [hne], end lemma abelian_of_solvable_ideal_eq_bot_iff (I : lie_ideal R L) [h : is_solvable R I] : derived_abelian_of_ideal I = ⊥ ↔ I = ⊥ := begin dunfold derived_abelian_of_ideal, cases h : derived_length_of_ideal R L I with k, { rw derived_length_zero at h, rw h, refl, }, { obtain ⟨h₁, h₂⟩ := (derived_series_of_derived_length_succ R L I k).mp h, have h₃ : I ≠ ⊥, { intros contra, apply h₂, rw contra, apply derived_series_of_bot_eq_bot, }, change derived_series_of_ideal R L k I = ⊥ ↔ I = ⊥, split; contradiction, }, end end lie_algebra
d975189c99d8d3ef8aade52eb1a8a0889c4fe2c8
ccb7cdf8ebc2d015a000e8e7904952a36b910425
/src/spec.lean
3e800bc94017b288ba7f2c75028ead5f2d13b83f
[]
no_license
cipher1024/lean-pl
f7258bda55606b75e3e39deaf7ce8928ed177d66
829680605ac17e91038d793c0188e9614353ca25
refs/heads/master
1,592,558,951,987
1,565,043,356,000
1,565,043,531,000
196,661,367
1
0
null
null
null
null
UTF-8
Lean
false
false
47,316
lean
import program prop misc -- import tactic.tidy import tactic.monotonicity universes u declare_trace separation.failed_spec open memory separation.hProp finmap list variables {value : Type} {s s' α : Type} include value local notation `ST` := separation.ST value local notation `heap` := memory.heap value local notation `hProp` := separation.hProp value local notation `tptr` := separation.tptr value namespace separation def spec (p : hProp) (m : ST α) (q : α → hProp) : Prop := ∀ ⦃h h' frame x⦄, (x,h') ∈ m.run h → holds h frame p → holds h' frame (q x) def spec' (p : hProp) (m : ST α) (q : hProp) : Prop := spec p m (λ _, q) lemma frame_rule (m : ST α) (p frame : hProp) (q : α → hProp) (hm : spec p m q) : spec (p ⊛ frame) m (λ r, q r ⊛ frame) := begin intros h h' frame' r Hrun, dsimp, rw [holds_of_holds_and,holds_of_holds_and], apply exists_imp_exists, intro h₁, apply and.imp_right, intro Hp, apply hm Hrun Hp, end lemma frame_rule' (m : ST α) (p frame : hProp) (q : α → hProp) (hm : spec p m q) : spec (frame ⊛ p) m (λ r, frame ⊛ q r) := begin simp [and_comm frame], apply frame_rule _ _ _ _ hm, end lemma pure_spec (p : hProp) (q : α → hProp) (x : α) (h : p =*> q x) : spec p (pure x) q := begin introv _, simp, rintro ⟨ ⟩ ⟨ ⟩, apply exists_imp_exists, intro, apply and_implies id (h.elim _), end lemma pure_spec' {α} (p : α → hProp) (x : α) : spec (p x) (pure x) p := pure_spec _ _ _ (impl.intro $ λ h, id) lemma bind_spec {β} {p : hProp} (q : α → hProp) {r : β → hProp} {m : ST α} {f : α → ST β} (h₀ : spec p m q) (h₁ : ∀ x, spec (q x) (f x) r) : spec p (m >>= f) r := begin dsimp [spec], introv, simp [], intros y h'' hm hf hp, apply h₁ _ hf, apply h₀ hm hp, end lemma and_then_spec {β} {p : hProp} (q : α → hProp) {r : β → hProp} (m : ST α) (f : ST β) (h₀ : spec p m q) (h₁ : ∀ x, spec (q x) f r) : spec p (m >> f) r := bind_spec q h₀ h₁ lemma p_exists_intro {α β} {p : hProp} {m : ST α} {q : α → β → hProp} (x : β) (H : spec p m (λ y, q y x)) : spec p m (λ x, p_exists (q x)) := begin intros h h' frame r hm hp, dsimp, rw holds_p_exists (q r), existsi x, apply H hm hp, end lemma p_exists_intro_left {β} {p : β → hProp} {m : ST α} {q : α → hProp} (H : ∀ x, spec (p x) m q) : spec (p_exists p) m q := by simp [spec,holds_p_exists]; introv hm; apply H _ hm lemma lift_intro {p : Prop} {p' : hProp} {m : ST α} {q : α → hProp} (h : p → spec p' m q) : spec ([|p|] ⊛ p') m q := by rw lift_and_iff_p_exists; apply p_exists_intro_left h lemma or_intro {p p' : hProp} {m : ST α} {q : α → hProp} (H : spec p m q) (H' : spec p' m q) : spec (p ⋁ p') m q := λ h h' frame r hm hpp', or.elim (holds_or_iff.mp hpp') (H hm) (H' hm) lemma or_intro_left {p : hProp} {m : ST α} {q q' : α → hProp} (H' : spec p m q) : spec p m (λ r, q r ⋁ q' r) := λ h h' frame r hm hp, holds_imp_holds_of_impl (impl.intro $ λ h, or.intro_left _) (H' hm hp) lemma or_intro_right {p : hProp} {m : ST α} {q q' : α → hProp} (H' : spec p m q') : spec p m (λ r, q r ⋁ q' r) := λ h h' frame r hm hp, holds_imp_holds_of_impl (impl.intro $ λ h, or.intro_right _) (H' hm hp) lemma or_left_right_spec {p p' : hProp} {m : ST α} {q q' : α → hProp} (H : spec p m q) (H' : spec p' m q') : spec (p ⋁ p') m (λ r, q r ⋁ q' r) := or_intro (or_intro_left H) (or_intro_right H') lemma precondition_impl {α} {p : hProp} (q : hProp) {r : α → hProp} {m : ST α} (hpq : p =*> q) (H : spec q m r) : spec p m r := by dsimp [spec]; introv hm hp; apply H hm (holds_imp_holds_of_impl hpq hp) lemma postcondition_impl {α} {p : hProp} (q : α → hProp) {r : α → hProp} {m : ST α} (hqr : ∀ x, q x =*> r x) (H : spec p m q) : spec p m r := by dsimp [spec]; introv hm hp; apply holds_imp_holds_of_impl (hqr _) (H hm hp) end separation namespace tactic omit value section spec_attribute open separation meta def bound_var : expr → name | (expr.lam n _ _ _) := n | _ := `_ meta def get_spec : expr → tactic (expr × expr × expr × expr × expr) | `(@spec %%val %%α %%p %%m %%q) := do { v ← mk_local_def (bound_var q) α, q ← head_beta (q v), pure (val, p, m, v, q) } | `(@spec' %%val %%α %%p %%m %%q) := do { v ← mk_local_def `v α, pure (val, p, m, v, q) } -- | `(%%p =*> %%q) := _ | t := (pformat!"not a specification: {t}" : pformat) >>= fail meta def get_spec' : tactic (expr × expr × expr × expr × expr) := target >>= instantiate_mvars >>= get_spec open tactic meta def spec_target (n : name) : tactic name := do t ← mk_const n >>= infer_type, (vs,t) ← mk_local_pis t, (_,_,m,_,_) ← get_spec t, return $ m.get_app_fn.const_name @[user_attribute] meta def spec_attr : user_attribute (name_map (list name)) := { name := `spec, descr := "specification lemma", cache_cfg := { mk_cache := mfoldl (λ m n, do proc ← spec_target n, pure $ m.insert_cons proc n) (name_map.mk _), dependencies := [] }, after_set := some $ λ n _ _, () <$ spec_target n <|> fail "ill-formed specification" } meta def abstr_rewrite (n : name) : tactic name := do t ← mk_const n >>= infer_type, (vs,`(%%l = _)) ← mk_local_pis t, if l.get_app_fn.const_name = ``repr then pure l.app_arg.get_app_fn.const_name else pure l.get_app_fn.const_name @[user_attribute] meta def data_abstr_attr : user_attribute (name_map (list name)) := { name := `data_abstr, descr := "specification lemma", cache_cfg := { mk_cache := mfoldl (λ m n, do proc ← abstr_rewrite n, pure $ m.insert_cons proc n) (name_map.mk _), dependencies := [] }, after_set := some $ λ n _ _, () <$ abstr_rewrite n <|> fail "ill-formed abstraction lemma" } end spec_attribute setup_tactic_parser meta def vec_cases_end (h : expr) : tactic unit := do rule ← mk_const ``list.length_eq_zero, h ← rewrite_hyp rule h, subst h meta def vec_cases_aux : expr → expr → list name → tactic unit | h `(list.length %%xs = %%n) ns := do `(nat.succ %%n) ← whnf n | vec_cases_end h, rule ← mk_const ``list.length_eq_succ, -- [xs,n], h ← rewrite_hyp rule h, d ← get_unused_name `h, let (n,ns) := (option.get_or_else ns.head' d,ns.tail), [(_,[y,h],_)] ← cases_core h [n], [(_,[ys,h],_)] ← cases_core h [`ys], [(_,[h,h'],_)] ← cases_core h [`h₀,`h₁], subst h, t ← infer_type h', vec_cases_aux h' t ns, pure () | h _ ns := fail "expecting assumption of the form `list.length xs = n`" meta def vec_cases (h : parse ident) (ids : parse with_ident_list) : tactic unit := do h ← get_local h, t ← infer_type h, vec_cases_aux h t ids run_cmd add_interactive [``vec_cases] setup_tactic_parser open tactic open separation lemma spec_congr {α} {p p' : hProp} {q q' : α → hProp} {m : ST α} (hp : p = p') (hq : ∀ x, q x = q' x) (hm : spec p m q) : spec p' m q' := have hq' : q = q', from _root_.funext hq, hq' ▸ (hp ▸ hm) meta def first_match : list expr → list expr → tactic (expr × list expr × list expr) | [] ys := fail "no match found" | (x::xs) ys := if x ∈ ys then pure (x,xs,ys.erase x) else do (a,as,bs) ← first_match xs ys, pure (a,x::as,bs) -- meta inductive fragment -- | refl : expr → fragment -- | drop (n : expr) : fragment → fragment -- | take (n : expr) : fragment → fragment -- meta def is_fragment : expr → expr → option fragment -- | e e' := -- if e = e' then fragment.refl e -- else match e with -- | `(drop %%n %%e₀) := do fr ← is_fragment e₀ e', -- fragment.drop n fr -- | `(take %%n %%e₀) := do fr ← is_fragment e₀ e', -- fragment.take n fr -- | _ := none -- end -- meta def fragment.complement' (val p ls q : expr) : expr → fragment → (expr → tactic expr) → tactic (list expr) -- | n (fragment.refl e) f := pure [] -- | n (fragment.take n' e) f := -- do p' ← mk_app ``tptr.add [p,n], -- let f' := λ e, f e >>= λ e, mk_app ``take [n',e], -- ls' ← mk_app ``drop [n',ls], -- ls' ← f ls', -- e' ← mk_app ``list_repr' [p',ls',q], -- cons e' <$> fragment.complement' n e f -- | n (fragment.drop n' e) f := -- do p' ← mk_app ``tptr.add [p,n], -- let f' := λ e, mk_app ``drop [n',e] >>= λ e, f e, -- ls' ← mk_app ``take [n',ls], -- ls' ← f ls', -- e' ← mk_app ``list_repr' [p',ls',q], -- n'' ← mk_app ``add [n,n'], -- cons e' <$> fragment.complement' n'' e f -- meta def fragment.complement (val p ls q : expr) (fr : fragment) : tactic (list expr) := -- fragment.complement' val p ls q `(0) fr pure -- meta def check_fragments (val p ls q x : expr) (xs : list expr) : list expr → tactic (expr × list expr × list expr) -- | (y@`(list_repr' _ %%p' %%ls' %%q') :: ys) := -- match is_fragment ls' ls with -- | (some fr) := -- do trace "fragment", -- cs ← fr.complement val p ls q, -- pure (y,cs ++ xs,ys) -- | none := do (a,as,bs) ← check_fragments ys, -- pure (a,as,y::bs) -- end -- | (y :: ys) := do (a,as,bs) ← check_fragments ys, -- pure (a,as,y::bs) -- | [] := fail "A no match found" -- meta def match_fragments : list expr → list expr → tactic (expr × list expr × list expr) -- | (x@`(list_repr' %%val %%p %%ls %%q) :: xs) ys := -- check_fragments val p ls q x xs ys <|> -- do trace x, -- (a,as,bs) ← match_fragments xs ys, -- pure (a,x::as,bs) -- -- | (`(list_repr %%val %%p %%ls) :: xs) ys := _ -- | (x :: xs) ys := do (a,as,bs) ← match_fragments xs ys, -- pure (a,x::as,bs) -- | [] ys := fail "B no match found" @[interactive] meta def frame : tactic unit := focus1 $ do (val,p,m,v,q) ← tactic.get_spec', ps ← parse_assert p, qs ← parse_assert q, (a,ps,qs) ← first_match ps qs, -- val ← mk_mvar, let b := mk_assert val ps, let c := mk_assert val qs, t ← mk_mapp ``frame_rule' [val,none,none,m,b,a,expr.lambdas [v] c], args ← infer_type t, g₀ ← mk_mvar, g₁ ← mk_mvar, g₂ ← mk_meta_var args.binding_domain, refine ``(spec_congr %%g₀ %%g₁ %%(t g₂)), set_goals [g₀], ac_refl, set_goals [g₁], intro1, ac_refl, g₂ ← instantiate_mvars g₂, set_goals [g₂] -- meta def frame' : tactic unit := -- focus1 $ -- do (p,m,v,q) ← get_spec, -- `(hProp %%val) ← infer_type p, -- ps ← parse_assert p, -- qs ← parse_assert q, -- (a,ps,qs) ← match_fragments ps qs, -- trace "•", -- trace a, trace ps, trace qs -- meta def find_lift : list expr → tactic (option (expr × list expr)) -- | [] := pure none -- | (x@`(separation.hProp.lift _) :: xs) := pure (some (x, xs)) -- | (x :: xs) := -- do some (y, ys) ← find_lift xs | pure none, -- pure (some (y, x::ys)) open tactic @[tactic.s_intro] meta def s_intro_spec (n : parse (ident_ <|> pure (name.mk_string "_" name.anonymous))) (tac : tactic unit) : tactic unit := do `[simp only [and_p_exists_distrib_left,and_p_exists_distrib_right] { fail_if_unchanged := ff }], some (val,p,_,_,_) ← try_core $ get_spec' | tac, match p with | `(p_exists _) := do applyc ``p_exists_intro_left, intro n >> pure () | _ := do xs ← parse_assert p, some (x, xs) ← find_lift xs | failed, let p' := mk_assert val (x :: xs), g ← mk_app `eq [p,p'] >>= mk_meta_var, gs ← get_goals, set_goals [g], `[simp only [and_emp,emp_and] { fail_if_unchanged := ff } ], done <|> ac_refl, set_goals gs, get_assignment g >>= rewrite_target, applyc ``lift_intro, intro n, pure () end -- meta def ac_refl_aux : tactic unit := -- do `[dsimp { fail_if_unchanged := ff }], -- (lhs, rhs) ← target >>= match_eq, -- xs ← parse_assert lhs, -- xs.mmap' $ λ x, generalize x >> intro1, -- cc <|> fail "ac_refl_aux" -- meta def ac_refl' : tactic unit := -- do try (applyc ``impl_of_eq), -- -- target >>= instantiate_mvars >>= change, -- -- `[dsimp], -- cc <|> -- ac_refl_aux -- -- <|> -- -- fail!"ac_refl': {target}\nmeta vars: {expr.list_meta_vars <$> target}" -- @[interactive] -- meta def s_intro (n : parse $ ident_ <|> pure `_) : tactic unit := -- do `[simp only [and_p_exists_distrib_left,and_p_exists_distrib_right] -- { fail_if_unchanged := ff }], -- `(@impl %%val %%p %%q) ← target | s_intro_spec n, -- match p with -- | `(p_exists _) := -- do applyc ``exists_impl, -- intro n >> pure () -- | _ := -- do xs ← parse_assert p, -- some (x, xs) ← find_lift xs | failed, -- let p' := mk_assert val (x :: xs), -- g ← mk_app `eq [p,p'] >>= mk_meta_var, -- gs ← get_goals, set_goals [g], -- `[simp only [and_emp,emp_and] { fail_if_unchanged := ff } ], -- done <|> ac_refl', -- set_goals gs, -- get_assignment g >>= rewrite_target, -- applyc ``lift_and_impl, -- intro n, pure () -- end -- @[interactive] -- meta def s_intros : parse ident_* → tactic unit -- | [] := repeat (s_intro `_) -- | ns := ns.mmap' s_intro -- meta def find_frame' (e : expr) : list expr → tactic (list expr) -- | [] := fail "frame not found" -- | (x :: xs) := -- xs <$ unify e x <|> -- cons x <$> find_frame' xs -- meta def find_frame_aux : list expr → list expr → tactic (list expr) -- | [] xs := pure xs -- | (x::xs) ys := -- do ys' ← find_frame' x ys, -- find_frame_aux xs ys' -- meta def find_diff : list expr → list expr → tactic (list expr × list expr × list expr) -- | [] xs := pure ([], [], xs) -- | (x::xs) ys := -- do (b,ys') ← prod.mk tt <$> find_frame' x ys <|> pure (ff,ys), -- (l,m,r) ← find_diff xs ys', -- if b -- then pure (l,x::m,r) -- else pure (x::l,m,r) -- /-- -- `find_frame e e'` returns `r` and `pr` such that `pr : e ⊛ r = e'` -- -/ -- meta def find_frame (e e' : expr) : tactic (expr × expr) := -- do `(hProp %%val) ← infer_type e, -- le ← parse_assert e, -- le' ← parse_assert e', -- lr ← find_frame_aux le le', -- let r := mk_assert val lr, -- t ← to_expr ``(%%e ⊛ %%r = %%e') >>= instantiate_mvars, -- (_,pr) ← solve_aux t -- (`[simp only [emp_and,and_emp] { fail_if_unchanged := ff } ]; ac_refl'), -- pure (r,pr) @[replaceable] meta def unify_args' (e e' : expr) : tactic unit := do guard (e.get_app_fn.const_name = e'.get_app_fn.const_name) <|> fail format!"different calls: {e.get_app_fn} {e'.get_app_fn}", s ← cc_state.mk_using_hs, let args := e.get_app_args, let args' := e'.get_app_args, guard (args.length = args'.length) <|> fail "argument list mismatch", mzip_with' (λ a a', try (unify a a') <|> fail!"arguments `{a}` and `{a'}` do not unify\n`{e}`, `{e'}`") args args', -- s.eqv_proof e e' skip meta def selected_goals (p : tactic bool) (tac : tactic unit) : tactic unit := all_goals (mcond p tac skip) meta def is_spec (t : expr) : tactic bool := do (_,t) ← mk_local_pis t, pure (t.is_app_of ``spec ∨ t.is_app_of ``spec') meta def all_spec_goals : tactic unit → tactic unit := selected_goals $ target >>= is_spec meta def all_entails_goals : tactic unit → tactic unit := selected_goals $ do (_,t) ← target >>= mk_local_pis, pure (t.is_app_of ``impl) meta def all_side_conditions : tactic unit → tactic unit := selected_goals $ do (_,t) ← target >>= mk_local_pis, pure $ ¬ (t.is_app_of ``spec ∨ t.is_app_of ``spec' ∨ t.is_app_of ``impl) meta def cc_prove_eq (e e' : expr) : tactic expr := do s ← cc_state.mk_using_hs, e ← instantiate_mvars e, e' ← instantiate_mvars e', s ← s.internalize e, s ← s.internalize e', s.eqv_proof e e' @[replaceable] meta def specialize_spec'' (spec p call : expr) : tactic unit := do when_tracing `separation.failed_spec trace!"try {spec}", (args,spec') ← infer_type spec >>= mk_meta_pis, (val,p',m,v,q) ← get_spec spec', unify_args call m, ps ← parse_assert p, ps' ← parse_assert p', let (vs,ps'') := ps'.partition $ λ e : expr, e.is_meta_var, fr ← find_frame_aux ps'' ps <|> fail!"framing {ps'} {ps}", let fr' := mk_assert val fr, q' ← head_beta q >>= lambdas [v], cc_prove_eq call m >>= rewrite_target <|> fail!"spec: {spec}\ncannot prove that {call} and {m} are equal", e ← if vs.empty then mk_mapp ``frame_rule [none, none, m, p', fr', q', spec.mk_app args] else do { [v] ← pure vs | fail "only one abstract predicate can be supported", unify v fr', return $ spec.mk_app args }, to_expr ``(precondition_impl _ _ %%e) >>= apply, pure () -- lemma shrink_impl (l m r : hProp) {p q : hProp} -- (h₀ : l ⊛ m = p) (h₁ : r ⊛ m = q) (h₂ : l =*> r) : -- p =*> q := -- h₀ ▸ (h₁ ▸ and_impl_and h₂ $ impl_refl _) -- lemma split_impl (p₀ p₁ q₀ q₁ : hProp) {p q : hProp} -- (h₀ : p₀ ⊛ p₁ = p) (h₁ : q₀ ⊛ q₁ = q) (h₂ : p₀ =*> q₀) (h₃ : p₁ =*> q₁) : -- p =*> q := -- h₀ ▸ (h₁ ▸ and_impl_and h₂ h₃) @[replaceable] meta def try_unfold' (attr_names : list name) (hs : list simp_arg_type) (tac : tactic unit) (cfg : simp_config) : tactic unit := tac <|> do (lmms, ids) ← mk_simp_set tt (`separation_logic :: attr_names) hs, simp_target lmms ids { fail_if_unchanged := ff, .. cfg }, tac meta def combine (tac_a tac_b : tactic (list α)) : tactic (list α) := do a ← try_core tac_a, b ← try_core tac_b, match a, b with | none, none := failed | some a, none := pure a | none, some b := pure b | some a, some b := pure $ a ++ b end meta def clear_specs (local_specs : expr_map (list expr)) : tactic unit := local_specs.to_list.mmap' $ λ ⟨_,x⟩, x.mmap clear @[replaceable] meta def verify_step' (ids : list simp_arg_type) (rule : option expr) (local_specs : expr_map (list expr)) : tactic unit := focus1 $ do ls ← spec_attr.get_cache, (val,p,m,v,q) ← tactic.get_spec', let proc_e := m.get_app_fn, let proc_n := proc_e.const_name, specs ← ↑(list.ret <$> rule) <|> combine (↑(local_specs.find proc_e)) (↑(ls.find proc_n) >>= list.mmap mk_const) <|> fail!"no such procedure: {proc_n}", ps ← parse_assert p, when (is_trace_enabled_for `separation.failed_spec = tt) (trace!"• verify step" >> trace_state), when (is_trace_enabled_for `separation.failed_spec = tt) (trace!"candidate specs: {specs}"), -- sl ← ids.mmap (resolve_name >=> pure ∘ simp_arg_type.expr), specs.any_of (λ e, if is_trace_enabled_for `separation.failed_spec = tt then trace_error "msg" (specialize_spec e p m) else specialize_spec e p m) <|> fail!"no specification found. \nCandidates: {specs}", when (is_trace_enabled_for `separation.failed_spec = tt) (trace "• prove side conditions" >> trace_state), all_entails_goals (try $ do clear_specs local_specs, if is_trace_enabled_for `separation.failed_spec = tt then trace_error "msg" entailment else entailment), when (is_trace_enabled_for `separation.failed_spec = tt) (trace "• propositional" >> trace_state), all_side_conditions (try $ do clear_specs local_specs, assumption <|> cc <|> linarith' none none none ), when (is_trace_enabled_for `separation.failed_spec = tt) (trace "• next" >> trace_state) open interactive meta def with_simp_arg_list := (tk "with" *> simp_arg_list) <|> pure [] @[interactive] meta def apply_spec (rule : parse texpr?) (ids : parse with_simp_arg_list) (local_specs : option (expr_map (list expr)) := none) (cfg : simp_config := {}) : tactic unit := focus1 $ try_unfold [] ids (do intros, s_intros [], subst_vars, when_tracing `separation.failed_spec $ do { trace "\nBEGIN - apply_spec", trace_state, trace "END - apply_spec\n" }, let local_specs := local_specs.get_or_else (expr_map.mk _), (val,p,m,v,q) ← get_spec', match m with | `(%%m >>= %%f) := do applyc ``bind_spec, g::gs ← get_goals, set_goals [g], rule ← traverse to_expr rule, verify_step ids rule local_specs, gs' ← get_goals, set_goals (gs ++ gs'), x ← intro (bound_var f), t ← infer_type x, when (t.const_name ∈ [``punit,``unit]) $ () <$ cases x, all_entails_goals $ try entailment, skip | `(%%m >> %%f) := do applyc ``and_then_spec, g::gs ← get_goals, set_goals [g], rule ← traverse to_expr rule, verify_step ids rule local_specs, gs' ← get_goals, set_goals (gs ++ gs'), x ← intro (bound_var f), t ← infer_type x, when (t.const_name ∈ [``punit,``unit]) $ () <$ cases x, all_entails_goals $ try entailment, skip | `(pure _) := applyc ``pure_spec; try entailment | m := do g₀ ← mk_mvar, g₁ ← mk_mvar, g₂ ← mk_mvar, refine ``(postcondition_impl %%g₀ %%g₁ %%g₂), set_goals [g₂], rule ← traverse to_expr rule, verify_step ids rule local_specs, gs ← get_goals, set_goals $ g₁ :: gs, -- trace "\n• Z", trace_state, all_entails_goals $ try entailment end, try `[dsimp only { fail_if_unchanged := ff }]) cfg open native @[interactive] meta def verify_proc (unfold : parse (tk "!")?) (ids : parse simp_arg_list) (cfg : simp_config := {}) : tactic unit := do intros, cxt ← local_context, local_specs ← cxt.mfoldl (λ (m : rb_map expr (list expr)) l, do { (_,t) ← infer_type l >>= mk_local_pis, (val,p,cmd,_) ← get_spec t, pure $ m.insert_cons cmd.get_app_fn l } <|> pure m ) (expr_map.mk (list expr)), when unfold.is_some $ do { (val,p,m,v,q) ← tactic.get_spec', let proc_n := m.get_app_fn.const_name, ns ← get_eqn_lemmas_for ff proc_n, let S := simp_lemmas.mk, S ← ns.mmap mk_const >>= S.append, simp_target S [``function.comp] }, repeat1 ( fail_if_unchanged $ all_spec_goals ( do -- trace "begin", apply_spec none ids (some local_specs) cfg)) -- trace "end")) -- @[interactive] -- meta def s_existsi (wit : parse pexpr_list_or_texpr) : tactic unit := -- wit.mmap' $ λ w, -- do `(%%p =*> %%q) ← target, -- `[simp only [and_p_exists_distrib_left,and_p_exists_distrib_right] { fail_if_unchanged := ff }], -- refine ``(impl_exists %%w _) <|> -- do `[simp only [lift_and_iff_p_exists] { single_pass := tt } ], -- `[simp only [and_p_exists_distrib_left,and_p_exists_distrib_right] -- { fail_if_unchanged := ff } ], -- refine ``(impl_exists %%w _) -- lemma lin_assert {p q : hProp} (pp : Prop) (h : p =*> [| pp |] ⊛ p) (h' : pp → p =*> q) : p =*> q := -- impl_trans h -- (by s_intro h; exact h' h) -- lemma lin_assert' {p q : hProp} (pp : Prop) (h : p =*> [| pp |] ⊛ True) (h' : pp → p =*> q) : p =*> q := -- begin -- transitivity [| pp |] ⊛ p, -- { rw lift_p_and_and, apply impl_and h (impl_refl _) }, -- { s_intro h, exact h' h } -- end -- @[interactive] -- meta def s_assert (h : parse $ ident? <* tk ":") (e : parse texpr) : tactic unit := -- let h := h.get_or_else `this in -- refine ``(lin_assert' %%e _ _); [skip, ()<$intro h] -- meta def s_apply' (e : expr) : tactic unit := -- do t ← infer_type e, -- (args,`(%%p =*> %%q)) ← mk_meta_pis t, -- let e := e.mk_app args, -- `(%%p' =*> %%q') ← target, -- frp ← some <$> find_frame p p' <|> pure none, -- frq ← some <$> find_frame q q' <|> pure none, -- match frp, frq with -- | some (pr,pp), some (qr,qp) := refine ``(split_impl %%p %%pr %%q %%qr %%pp %%qp %%e _) -- | some (pr,pp), none := refine ``(impl_trans (shrink_impl %%p %%pr %%q %%pp rfl %%e) _) -- | none, some (qr,qp) := refine ``(impl_trans _ (shrink_impl %%p %%qr %%q rfl %%qp %%e)) -- | none, none := fail!"No match found for `{e} : {t}`" -- end, -- try (reflexivity <|> applyc ``impl_True) -- @[interactive] -- meta def s_apply : parse types.pexpr_list_or_texpr → tactic unit := -- mmap' $ to_expr >=> s_apply' -- @[interactive] -- meta def s_assumptions : tactic unit := -- do cxt ← local_context, -- focus1 $ cxt.for_each $ λ l, try $ s_apply' l -- @[interactive] -- meta def s_assumption : tactic unit := -- do cxt ← local_context, -- focus1 $ cxt.any_of $ λ l, try $ s_apply' l -- @[interactive] -- meta def s_show (p : parse texpr) : tactic unit := -- do g ← to_expr p >>= mk_meta_var, -- s_apply' g -- lemma prop_proof {p : Prop} {q : hProp} (h : p) : q =*> [| p |] ⊛ True := -- impl_lift_and h impl_True -- lemma prop_proof' {p : Prop} {q : hProp} (h : p) : q =*> True ⊛ [| p |] := -- impl_trans (prop_proof h) (impl_of_eq $ hProp.and_comm _ _) -- @[interactive] -- meta def prop (ls : parse ident_*) : tactic unit := -- do s_intros ls, -- applyc ``prop_proof -- <|> applyc ``prop_proof' -- example {p q : hProp} : p =*> q := -- begin -- s_assert h : 1 ≤ 2, -- -- check_hyp -- end -- meta def fetch_abstr_lemma (ls : name_map (list name)) : simp_lemmas → list name → tactic simp_lemmas -- | s [] := pure s -- | s (x::xs) := _ -- run_cmd add_interactive [``frame,``s_intro,``s_intros, ``apply_spec, ``verify_proc, ``entailment] end tactic namespace separation attribute [spec] pure_spec' @[spec] lemma assign_spec (p : tptr value) (v v' : value) : spec' (p ⤇ v) (assign p.get v') (p ⤇ v') := begin cases p, simp [spec',spec,assign,mem_run_modify], introv hh hh', simp only [hh', holds, maplets, add, disjoint_maplet, pure, add_zero, option.some_bind, exists_eq_right, and_emp], split_ifs, exact id, intro hh'', simp only [hh'', insert_union, insert_maplet], end lemma holds_maplet {h frame : heap} {p : ptr} {v : value} : holds h frame (p ↦ v) → h.lookup p = some v := begin simp [holds,maplets], intros Hh', rw [eq_union_of_eq_add Hh',maplet,singleton_union,lookup_insert], end @[spec] lemma read_spec (p : ptr) (v : value) : spec (p ↦ v) (read p) (λ r, [|r = v|] ⊛ p ↦ v) := begin simp [spec], introv Hrun, rintro ⟨ ⟩ H, rw [holds_maplet H,option.some_inj] at Hrun, exact ⟨ Hrun.symm, H ⟩, end @[spec] lemma read_spec' (p : tptr value) (v : value) : spec (p ⤇ v) (read p.get) (λ r, [|r = v|] ⊛ p ⤇ v) := by cases p; simp [read_spec] @[spec] lemma assign_array_spec (p : tptr (list value)) (vs : list value) (v' : value) (i : ℕ) (hi : i < length vs) : spec' (p+.i ⤇ nth' i vs) (assign (p+.i).get v') (p+.i ⤇ [v']) := begin have := exists_nth'_eq_of_lt vs _ hi, cases this with _ h, simp [h], apply assign_spec end @[spec] lemma read_array_spec' (p : tptr (list value)) (i : ℕ) (vs : list value) (H : i < length vs) : spec (p+.i ⤇ nth' i vs) (read (p +. i).get) (λ r, [| [r] = nth' i vs |] ⊛ p+.i ⤇ nth' i vs) := begin have := exists_nth'_eq_of_lt vs _ H, cases this with _ h, rw h, simp [value_repr], apply read_spec end -- set_option pp.implicit true -- set_option pp.notation false -- set_option trace.separation.failed_spec true section tactic open tactic -- @[interactive] -- meta def with_tracing (tac : interactive.itactic) : tactic unit := -- save_options $ do -- o ← get_options, -- trace $ o.fold [] (::), -- set_options $ o.set_bool `trace.separation.failed_spec tt, -- tac -- `separation.failed_spec -- @[tactic.try_unfold] -- meta def try_unfold' (attr_names : list name) (hs : list simp_arg_type) (tac : tactic unit) (cfg : simp_config) : tactic unit := -- tac <|> do -- -- trace "• A", -- (lmms, ids) ← mk_simp_set tt (`separation_logic :: attr_names) hs, -- -- let _ := _, -- -- trace!"• C: {hs}", -- simp_target lmms ids { fail_if_unchanged := ff, .. cfg }, -- -- trace!"• B: {hs}", -- tac -- @[tactic.unify_args] -- meta def unify_args' (e e' : expr) : tactic unit := -- do guard (e.get_app_fn.const_name = e'.get_app_fn.const_name) <|> fail format!"different calls: {e.get_app_fn} {e'.get_app_fn}", -- s ← cc_state.mk_using_hs, -- let args := e.get_app_args, -- let args' := e'.get_app_args, -- guard (args.length = args'.length) <|> fail "argument list mismatch", -- mzip_with' (λ a a', (unify a a') <|> fail!"arguments `{a}` and `{a'}` do not unify\n`{e}`, `{e'}`") args args', -- -- s.eqv_proof e e' -- skip -- @[tactic.specialize_spec] -- meta def specialize_spec'' (spec p call : expr) : tactic unit := -- do (args,spec') ← infer_type spec >>= mk_meta_pis, -- (val,p',m,v,q) ← get_spec spec', -- trace m, -- unify_args call m, -- trace!"{m}, {call}, \np: {p}, \np': {p'}, \nq: {q}", -- ps ← parse_assert p, -- ps' ← parse_assert p', -- let (vs,ps'') := ps'.partition $ λ e : expr, e.is_meta_var, -- fr ← find_frame_aux ps'' ps <|> fail!"framing {ps''} {ps}", -- let fr' := mk_assert val fr, -- q' ← head_beta q >>= lambdas [v], -- cc_prove_eq call m >>= rewrite_target <|> fail!"spec: {spec}\ncannot prove that {call} and {m} are equal", -- e ← if vs.empty then -- mk_mapp ``frame_rule [none, none, none, m, p', fr', q', spec.mk_app args] -- else do -- { [v] ← pure vs | fail "only one abstract predicate can be supported", -- unify v fr', -- return $ spec.mk_app args }, -- to_expr ``(precondition_impl _ _ %%e) >>= apply, -- pure () end tactic lemma offset_succ {α} (p : tptr α) (n : ℕ) : p +. n.succ = p +. 1 +. n := by cases p; simp [(+.),nat.succ_eq_add_one] -- set_option trace.separation.failed_spec true -- set_option pp.implicit true -- -- set_option pp.universes true -- set_option trace.app_builder true @[spec] lemma read_array_spec (p : tptr (list value)) (i : ℕ) (vs : list value) (H : i < length vs) : spec (p ⤇ vs) (read (p +. i).get) (λ r, [| [r] = nth' i vs |] ⊛ (p ⤇ vs)) := begin induction vs generalizing p i, cases H, cases i; verify_proc [offset_succ] { single_pass := tt }, end lemma and_then_spec' {β} {p : hProp} (q : hProp) {r : β → hProp} (m : ST α) (f : ST β) (h₀ : spec p m (λ _, q)) (h₁ : spec q f r) : spec p (m >> f) r := bind_spec (λ _, q) h₀ (λ _, h₁) @[spec] lemma map_spec {β} {p : hProp} {q : β → hProp} {m : ST α} {f : α → β} (h₀ : spec p m (q ∘ f)) : spec p (f <$> m) q := by rw map_eq_bind_pure; apply bind_spec _ h₀ (λ x, _); apply pure_spec' @[spec] lemma choice_spec (p : α → Prop) : spec emp (@choice value _ p) (λ r, [| p r |]) := by simp [spec]; introv h₀ h₁ h₂; exact ⟨h₀,h₁.symm ▸ h₂⟩ lemma choice_spec' {β} (pp : α → Prop) (f : α → ST β) (p : hProp) (q : β → hProp) (h : ∀ x, pp x → spec p (f x) q) : spec p (choice pp >>= f) q := by { dsimp [spec]; intros; simp only [exists_prop, set.mem_Union, set.bind_def, mem_choice_run, state_t.run_bind, prod.exists] at a, casesm* [_ ∧ _, Exists _], subst h_1, apply h _ ‹ _ › ‹ _ › ‹ _ › } lemma get_spec (p : hProp) (q : heap → hProp) (h : ∀ x, p =*> q x) : spec p get q := by { dsimp [get,monad_state.lift]; introv _ Hrun; apply exists_imp_exists, intro hh, simp [pure] at Hrun, casesm* _ ∧ _, subst h', apply and.imp id, apply (h _).elim } @[spec] lemma get_spec' (p : hProp) : spec p get (λ _, p) := get_spec _ _ $ λ _, impl.intro $ λ σ, id open list @[spec] lemma alloc_spec (vs : list value) : spec emp (alloc vs) (λ p, tptr.mk _ _ p ⤇ vs) := begin simp [spec], intros h h' frame p, -- simp only [mem_choice_run,mem_bind_run,assign_vals,mem_run_get,exists_imp_distrib,id,and_imp], intros H₀ H₁, -- simp only [alloc,exists_imp_distrib,id,and_imp,mem_run_pure,enum,mem_choice_run,mem_bind_run,mem_run_get,mem_run_modify,assign_vals] at ⊢, -- intros, subst_vars, simp, rw [← emp_and ({get := p} ⤇ vs)], -- conv in (x ↦ vs) { rw ← nat.add_zero x }, rw eq_union_of_eq_add H₀, apply holds_union_and H₁ _ _, { simp!, clear H₀, induction vs generalizing p; simp [enum_from,maplets,emp,to_finmap_cons], apply and_applied_union, exact rfl, apply vs_ih, simp [disjoint_maplet], }, prove_disjoint, end @[spec] lemma alloc'_spec (n : ℕ) : spec emp (alloc' value n) (λ p, ∃∃ vs : list value, [|vs.length = n|] ⊛ (tptr.mk _ _ p ⤇ vs)) := by { verify_proc! } open nat @[spec] lemma dealloc_spec (p : ptr) (vs : list value) : spec' (tptr.mk _ _ p ⤇ vs) (dealloc value p vs.length) emp := begin dsimp [dealloc], intros h h' frame _, simp only [mem_choice_run,mem_bind_run,assign_vals,mem_run_get,exists_imp_distrib,id,and_imp,mem_run_modify], introv H₀ H₁ H₂ H₃, subst x_1, subst x_2, subst h', cases x with p, -- simp only [dealloc,exists_imp_distrib,id,and_imp,mem_run_pure,enum,mem_choice_run,mem_bind_run,mem_run_get,mem_run_modify,assign_vals] at ⊢, -- intros, subst_vars, have : h = (erase_all p (length vs) h) ∪ heap.mk (vs.enum_from p), { rw erase_all_union_mk_self, apply le_of_add_eq_some frame, rcases H₃ with ⟨w,hw₀,hw₁⟩, simp [maplets_eq] at hw₁, subst w, exact hw₀ }, rw [this,← emp_and (tptr.mk _ _ p ⤇ vs)] at H₃, clear this, rw holds_of_holds_union_iff at H₃, exact H₃, rw maplets_eq, { intros p', simp, clear H₃, intros, induction vs; dsimp [length] at H, { exact a }, rw [erase_all_succ] at H, simp at H, replace vs_ih := vs_ih H.2, simp [mem_erase_all] at H, rw [length,← nat.add_assoc], apply succ_le_of_lt, apply lt_of_le_of_ne (H.2.1 _) (ne.symm H.1), apply le_trans _ vs_ih, apply nat.le_add_right }, { introv, simp [maplets_eq] }, end -- set_option trace.separation.failed_spec true -- section tactic -- open tactic -- #check @tactic.entailment -- -- @[tactic.entailment] -- -- meta def entailment' (tac : tactic unit) : tactic unit := -- -- focus1 $ -- -- assumption <|> -- -- do intros, -- -- target >>= instantiate_mvars >>= change, -- -- when_tracing `separation.failed_spec (trace "A"), -- -- with_context!"• A: {target}" $ do -- -- `[simp [hProp.and_p_exists_distrib_left,hProp.and_p_exists_distrib_right] with separation_logic -- -- { fail_if_unchanged := ff } ], -- -- with_context!"• B: {try_core target}" $ do -- -- iterate_at_most 10 $ do -- -- { `(_ =*> p_exists _) ← target, -- -- applyc ``impl_exists }, -- -- with_context!"• C: {try_core target}" $ do -- -- done <|> -- -- assumption <|> -- -- ac_refl' -- end tactic -- #check tactic.verify_step' -- #check tactic.specialize_spec -- #check tactic.entailment @[spec] lemma for_spec (n : ℕ) (f : ℕ → ST punit) (p : ℕ → hProp) (h : ∀ i, i < n → spec' (p i) (f i) (p i.succ)) : spec' (p 0) (for n f) (p n) := begin induction n, { verify_proc! }, { verify_proc! }, end @[spec] lemma for_spec' {n : ℕ} {f : ℕ → ST punit} {p q : ℕ → hProp} (b : hProp) (h : ∀ i, i < n → spec' (b ⊛ p i) (f i) (b ⊛ q i)) : spec' (b ⊛ And p (range n)) (for n f) (b ⊛ And q (range n)) := begin let P := λ i, b ⊛ And q (range i) ⊛ And p (range' i (n - i)), let P' := λ i, And q (range i) ⊛ And p (range' i.succ (n - i.succ)), have h := for_spec n f P _, { simp only [P] at h, rw [nat.sub_zero,range_zero,And,emp_and,← range_eq_range',nat.sub_self,range'_zero,And,and_emp] at h, exact h }, { intros i hn, have : spec' (P' i ⊛ b ⊛ p i) (f i) (P' i ⊛ b ⊛ q i), { apply frame_rule', apply h _ hn }, convert this; dsimp [P,P'], { rw [hProp.and_assoc], transitivity b ⊛ And q (range i) ⊛ And p (i :: range' (succ i) (n - succ i)), rw [cons_range',nat.sub_succ,succ_pred_eq_of_pos _], apply nat.lt_sub_right_of_add_lt, rw zero_add, exact hn, rw And, ac_refl }, { rw [range_concat,And_append,And,And,and_emp], ac_refl } } end -- @[spec] -- lemma clone_spec (p : tptr (list value)) (vs : list value) : -- spec (p ⤇ vs) -- (clone p vs.length) -- (λ q, (p ⤇ vs) ⊛ (q ⤇ vs) ) := -- begin -- verify_proc!, -- s_intros trash H, -- simp [hProp.maplets_eq_And q,H], -- verify_proc, rw ← hProp.maplets_eq_And, -- entailment, -- end -- #exit open function local notation `fixed_storable` := fixed_storable value -- @[spec] -- lemma map_spec' (p : ptr) (f : ℕ → value → value) (vs : list value) : -- spec' (tptr.mk _ _ p ⤇ vs) -- (map p f vs.length) -- (tptr.mk _ _ p ⤇ vs.enum.map (uncurry f)) := -- begin -- rw hProp.maplets_eq_And, -- verify_proc!, -- { rw hProp.maplets_eq_And, simp }, -- { rw ← a_1, simp [enum_from,uncurry] }, -- end variables (value) class is_object (α : Type) extends fixed_storable α := (delete : tptr α → ST punit) (move : tptr α → tptr α → ST punit) (delete_spec : ∀ (p : tptr α) (x : α), spec' (p ⤇ x) (delete p) (trashed p)) (move_spec : ∀ (p p' : tptr α) (x : α), spec' (trashed p ⊛ p' ⤇ x) (move p p') (trashed p' ⊛ p ⤇ x)) attribute [spec] is_object.delete_spec is_object.move_spec local notation `is_object` := is_object value class copyable (α : Type) extends is_object α := (copy : tptr α → tptr α → ST punit) (copy_spec : ∀ (p p' : tptr α) (x : α), spec' (trashed p ⊛ p' ⤇ x) (copy p p') (p ⤇ x ⊛ p' ⤇ x)) local notation `copyable` := copyable value attribute [spec] copyable.copy_spec variables {value} open «copyable» omit value lemma sizeof_eq {α} {ls : list α} : sizeof ls = length ls + 1 := by { dsimp [sizeof,has_sizeof.sizeof], induction ls; simp [list.sizeof,*,sizeof,has_sizeof.sizeof,default.sizeof] } lemma sizeof_drop {α} {n : ℕ} {ls : list α} (h : n ≤ length ls) : sizeof (drop n ls) = sizeof ls - n := by simp [sizeof_eq,nat.add_sub_assoc h] include value section chunks variables (α) [fixed_storable α] def mk_chunk (vs : list value) (h : length vs ≥ fixed_size value α) : word value α := ⟨take (fixed_size value α) vs,by rw [length_take,min_eq_left h]⟩ def chunks : list value → list (word value α) | xs := if h : length xs ≥ fixed_size value α then have sizeof (drop (fixed_size value α) xs) < sizeof xs, by { rw sizeof_drop h, apply nat.sub_lt _ (fixed_storable.pos_size _ _), rw sizeof_eq, apply lt_of_le_of_lt (nat.zero_le _), apply lt_add_one, }, mk_chunk α xs h :: chunks (drop (fixed_size value α) xs) else [] variables {α} lemma chunks_nil : chunks α (@nil value) = @nil (word value α) := by rw [chunks,dif_neg]; apply not_le_of_gt; apply fixed_storable.pos_size lemma chunks_eq_of_length_ge {xs : list value} (h : length xs ≥ fixed_size value α) : chunks α xs = mk_chunk α xs h :: chunks α (drop (fixed_size value α) xs) := by rw [chunks,dif_pos h] variables {n : ℕ} lemma repr_chunks (p : tptr (list (word value α))) {mem : list value} (Hmem : length mem = n * fixed_storable.fixed_size value α) : p ⤇ chunks α mem = p.recast _ ⤇ mem := begin induction n generalizing mem p; simp [nat.succ_mul,length_eq_zero] at Hmem, { rw [Hmem,chunks_nil], refl }, { have : length mem ≥ fixed_size value α, { rw Hmem, apply nat.le_add_right, }, rw [chunks_eq_of_length_ge this,repr_cons], conv { to_rhs, rw ← take_append_drop (fixed_size value α) mem, }, rw [maplets_append], congr' 1, { transitivity, swap, apply @n_ih (drop (fixed_size value α) mem) (p +. length (take (fixed_size value α) mem)), rw [length_drop,Hmem,nat.add_sub_cancel_left], congr, dsimp [storable.size], simp [min_eq_left this] } }, end lemma length_chunks {mem : list value} (Hmem : length mem = n * fixed_size value α) : length (chunks α mem) = n := begin induction n generalizing mem; simp [nat.succ_mul] at Hmem, { rw length_eq_zero at Hmem ⊢, subst Hmem, rw [chunks,dif_neg], apply not_le_of_gt, apply fixed_storable.pos_size }, { rw [chunks,dif_pos,length,← nat.succ_eq_add_one], congr, apply n_ih, rw [length_drop,Hmem,nat.add_sub_cancel_left], rw Hmem, apply nat.le_add_right } end end chunks section talloc variables [fixed_storable α] (n : ℕ) open list @[spec] lemma malloc_spec : spec emp (malloc value n) (λ p, ∃∃ val : list value, [| length val = n |] ⊛ p ⤇ val) := by { verify_proc! } @[spec] lemma ralloc1_spec : spec emp (ralloc1 value α) (λ p, trashed p) := by verify_proc!; intro; simp [trashed] end talloc section talloc open list «is_object» variables [is_object α] variables (value) -- include S def rfree (p : tptr α) : ST unit := do delete p, dealloc value p.get (fixed_size value α) variables {value} section tactic open tactic -- @[tactic.verify_step] -- meta def verify_step'' (ids : list simp_arg_type) (rule : option expr) (local_specs : expr_map (list expr)) : tactic unit := -- focus1 $ -- do ls ← spec_attr.get_cache, -- trace_state, -- (val,p,m,v,q) ← tactic.get_spec', -- let proc_e := m.get_app_fn, -- let proc_n := proc_e.const_name, -- specs ← ↑(list.ret <$> rule) <|> -- local_specs.find proc_e <|> -- (↑(ls.find proc_n) >>= list.mmap mk_const) <|> -- fail!"no such procedure: {proc_n}", -- trace "foo bar", -- ps ← parse_assert p, -- -- sl ← ids.mmap (resolve_name >=> to_expr) >>= simp_lemmas.append simp_lemmas.mk, -- trace!"foo {specs}", -- specs.any_of (λ e, -- try_unfold [] ids $ -- do trace e, -- if is_trace_enabled_for `separation.failed_spec = tt -- then trace_error "msg" (specialize_spec e p m) >> trace "bar" -- else specialize_spec e p m >> trace "bar") -- <|> fail!"no specification found. \nCandidates: {specs}", -- all_entails_goals (try entailment), -- all_side_conditions (try cc) -- @[tactic.try_unfold] -- meta def try_unfold'' (attr_names : list name) (hs : list simp_arg_type) (tac : tactic unit) : tactic unit := -- -- do trace "foo", -- tac <|> do -- trace!"A - {hs}", -- (lmms, ids) ← mk_simp_set tt (`separation_logic :: attr_names) hs, -- simp_target lmms ids { fail_if_unchanged := ff }, -- trace_state, -- tac -- @[tactic.unify_args] -- meta def unify_args' (e e' : expr) : tactic unit := -- do guard (e.get_app_fn.const_name = e'.get_app_fn.const_name) <|> fail format!"different calls: {e.get_app_fn} {e'.get_app_fn}", -- let args := e.get_app_args, -- let args' := e'.get_app_args, -- guard (args.length = args'.length) <|> fail "argument list mismatch", -- mzip_with' (λ a a', (unify a a') <|> trace!"arguments `{a}` and `{a'}` do not unify\n`{e}`, `{e'}`") args args', -- -- e ← instantiate_mvars e, -- -- e' ← instantiate_mvars e', -- -- trace (to_fmt e), trace (to_fmt e'), -- -- -- s.is_eqv -- -- s ← s.internalize e, -- -- s ← s.internalize e', -- -- s.is_eqv e e' >>= trace, -- -- s.eqv_proof e e', -- skip -- @[tactic.specialize_spec] -- meta def specialize_spec'' (spec p call : expr) : tactic unit := -- do (args,spec') ← infer_type spec >>= mk_meta_pis, -- (val,p',m,v,q) ← tactic.get_spec spec', -- pr ← unify_args call m, -- ps ← parse_assert p, -- ps' ← parse_assert p', -- let (vs,ps'') := ps'.partition $ λ e : expr, e.is_meta_var, -- fr ← find_frame_aux ps'' ps <|> fail!"framing {ps'} {ps}", -- let fr' := mk_assert val fr, -- q' ← head_beta q >>= lambdas [v], -- s ← cc_state.mk_using_hs, -- call ← instantiate_mvars call, -- m ← instantiate_mvars m, -- s ← s.internalize m, -- s ← s.internalize call, -- trace! "{to_fmt call}\n{to_fmt m}", -- pr ← s.eqv_proof call m, -- rewrite_target pr, -- trace!"{infer_type pr}", -- e ← if vs.empty then -- mk_mapp ``frame_rule [none, none, none, m, p', fr', q', spec.mk_app args] -- else do -- { [v] ← pure vs | fail "only one abstract predicate can be supported", -- unify v fr', -- return $ spec.mk_app args }, -- to_expr ``(precondition_impl _ _ %%e) >>= apply, -- pure () end tactic -- set_option trace.separation.failed_spec true @[spec] lemma rfree_spec (p : tptr α) (x : α) : spec' (p ⤇ x) (rfree value p) emp := -- precondition_impl (trashed value p) -- (impl_of_eq (raw_bytes_conversion _ _ _)) -- (by dsimp [rfree]; rw ← length_bytes' _ x; apply dealloc_spec) by { verify_proc! [trashed] } end talloc section talloc_isrecord variables [is_record value α] (n : ℕ) open list @[spec] lemma ralloc_spec : spec emp (ralloc value α n) (λ p, ∃∃ val : list α, [| length val = n |] ⊛ p ⤇ val) := (by { verify_proc!, intro, simp [], apply exists_impl, intro mem, apply lift_and_impl, intro Hmem, apply impl_exists ((chunks α mem).map abstr), rw [length_map,repr_map_abstr,tptr.recast_mk], apply impl_lift_and, { rw length_chunks Hmem, }, { simp [repr_chunks _ Hmem], } }) @[spec] lemma ralloc1_spec' : spec emp (ralloc1 value α) (λ p, ∃∃ val, p ⤇ val) := by { verify_proc, intro, simp [(∘),uninitialized',trashed] } #check lattice.has_sup @[spec] lemma free_spec (p : tptr (list α)) (xs : list α) : spec' (p ⤇ xs) (free p (length xs) ) emp := begin refine precondition_impl (p.recast (list value) ⤇ rec_bytes xs) _ _, -- (dealloc_spec _ _) -- (by simp [val_repr]) (dealloc_spec _ xs) { apply impl_of_eq, induction xs generalizing p, refl, -- have := maplets_append, rw [rec_bytes_cons,maplets_append',repr_cons,raw_bytes_conversion,xs_ih], simp [fixed_storable.is_fixed,length_bytes'], refl }, { dsimp [free], rw ← length_rec_bytes, apply dealloc_spec } end end talloc_isrecord namespace «copyable» variables [copyable α] def clone (p : tptr α) : ST (tptr α) := do p' ← ralloc1 _ α, copy p' p, pure p' open separation.is_object lemma clone_spec (p : tptr α) (x : α) : spec (p ⤇ x) (clone p) (λ r, r ⤇ x ⊛ p ⤇ x) := by verify_proc! def replace (p p' : tptr α) : ST unit := do delete p, copy p p' lemma replace_spec (p p' : tptr α) (x y : α) : spec' (p ⤇ x ⊛ p' ⤇ y) (replace p p') (p ⤇ y ⊛ p' ⤇ y) := by verify_proc! end «copyable» end separation
5bdb0b45b20ffbf942f5901654f127f3f483350a
e0b0b1648286e442507eb62344760d5cd8d13f2d
/tests/lean/StxQuot.lean
a8aadadcd70e21f991cf92e8ef3397ffabafad79
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,640
lean
import Lean open Lean open Lean.Elab def run {α} [ToString α] : Unhygienic α → String := toString ∘ Unhygienic.run #eval run `() #eval run `(Nat.one) #eval run `($Syntax.missing) namespace Lean.Syntax #eval run `($missing) #eval run `($(missing)) #eval run `($(id Syntax.missing) + 1) #eval run $ let id := Syntax.missing; `($id + 1) end Lean.Syntax #eval run `(1 + 1) #eval run `([x,]) #eval run $ `(fun a => a) >>= pure #eval run $ `(def foo := 1) #eval run $ `(def foo := 1 def bar := 2) #eval run $ do let a ← `(Nat.one); `($a) #eval run $ do `($(← `(Nat.one))) #eval run $ do let a ← `(Nat.one); `(f $a $a) #eval run $ do let a ← `(Nat.one); `(f $ f $a 1) #eval run $ do let a ← `(Nat.one); `(f $(id a)) #eval run $ do let a ← `(Nat.one); `($(a).b) #eval run $ do let a ← `(1 + 2); match a with | `($a + $b) => `($b + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(1 + 2); match a with | stx@`($a + $b) => `($stx + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1); match a with | `($f:command) => pure f | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1 def bar := 2); match a with | `($f:command $g:command) => `($g:command $f:command) | _ => pure Syntax.missing #eval run $ do let a ← `(aa); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval match mkIdent `aa with | `(aa) => 0 | _ => 1 #eval match mkIdent `aa with | `(ab) => 0 | _ => 1 #eval run $ do let a ← `(1 + 2); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let params ← #[`(a), `((b : Nat))].mapM id; `(fun $params* => 1) #eval run $ do let a ← `(fun (a : Nat) b => c); match a with | `(fun $aa* => $e) => pure aa | _ => pure #[] #eval run $ do let a ← `(∀ a, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a -- this one should NOT check the kind of the matched node #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $a, $e) => pure a | _ => pure a #eval run $ do let a ← `(a); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(a.{0}); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(match a with | a => 1 | _ => 2); match a with | `(match $e:term with $eqns:matchAlt*) => pure eqns | _ => pure #[] def f (stx : Syntax) : Unhygienic Syntax := match stx with | `({ $f:ident := $e $[: $a]?}) => `({ $f:ident := $e $[: $(id a)]?}) | _ => unreachable! #eval run do f (← `({ a := a : a })) #eval run do f (← `({ a := a })) def f' (stx : Syntax) : Unhygienic Syntax := match stx with | `(section $(id?)?) => `(section $(id?)?) | _ => unreachable! #eval run do f' (← `(section)) #eval run do f' (← `(section foo)) #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $[| $pats =>%$arr $rhss]*) => `(match $e:term with $[| $pats =>%$arr $rhss]*) | _ => unreachable! #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $alts:matchAlt*) => `(match $e:term with $alts:matchAlt*) | _ => unreachable! open Parser.Term #eval run do match ← `(structInstField|a := b) with | `(Parser.Term.structInstField| $lhs:ident := $rhs) => #[lhs, rhs] | _ => unreachable! #eval run do match ← `({ a := a : a }) with | `({ $f:ident := $e : 0 }) => "0" | `({ $f:ident := $e $[: $a?]?}) => "1" | stx => "2" #eval run `(sufficesDecl|x from x) #eval run do match ← `([1, 2, 3, 4]) with | `([$x, $ys,*, $z]) => #[x, mkNullNode ys, z] | _ => unreachable! #eval run do match ← `([1, 2]) with | `([$x, $y, $zs,*]) => zs.getElems | `([$x, $ys,*]) => ys.getElems | _ => unreachable! #check (match · with | `([1, $ys,*, 2, $zs,*, 3]) => _) #eval run do match Syntax.setHeadInfo (← `(fun x =>%$(Syntax.atom (SourceInfo.synthetic 2 2) "") x)) (SourceInfo.synthetic 1 1) with | `(fun%$i1 $x =>%$i2 $y) => pure #[i1.getPos?, i2.getPos?] | _ => unreachable! #eval run ``(x) #eval run ``(id) #eval run ``(pure) syntax "foo" term : term #eval run ``(foo $(Syntax.missing)) -- syntax with no quoted identifiers should be ignored #eval run ``(fun x => x) #eval run ``(fun x => y) #eval run ``(fun x y => x y) #eval run ``(fun ⟨x, y⟩ => x) #eval run do match ← `(have x := y; z) with | `(have $[$x :]? $type from $val $[;]? $body) => pure 0 | `(have $pattern:term := $val:term $[;]? $body) => pure 1 | _ => pure 2
699fb069c3ef470230010deda02e45fa3a07f665
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/normed_space/linear_isometry.lean
26c2da28cc460c236f7b749277cc7a5b1358cf9a
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,464
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import topology.metric_space.isometry /-! # Linear isometries In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear isometric equivalence between `E` and `F`. We also prove some trivial lemmas and provide convenience constructors. -/ open function set variables {R E F G G' : Type*} [semiring R] [normed_group E] [normed_group F] [normed_group G] [normed_group G'] [semimodule R E] [semimodule R F] [semimodule R G] [semimodule R G'] /-- An `R`-linear isometric embedding of one normed `R`-module into another. -/ structure linear_isometry (R E F : Type*) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] extends E →ₗ[R] F := (norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥) notation E ` →ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry R E F namespace linear_isometry variables (f : E →ₗᵢ[R] F) instance : has_coe_to_fun (E →ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl lemma to_linear_map_injective : injective (to_linear_map : (E →ₗᵢ[R] F) → (E →ₗ[R] F)) | ⟨f, _⟩ ⟨g, _⟩ rfl := rfl lemma coe_fn_injective : injective (λ (f : E →ₗᵢ[R] F) (x : E), f x) := linear_map.coe_injective.comp to_linear_map_injective @[ext] lemma ext {f g : E →ₗᵢ[R] F} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h @[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero @[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y @[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y @[simp] lemma map_smul (c : R) (x : E) : f (c • x) = c • f x := f.to_linear_map.map_smul c x @[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x @[simp] lemma nnnorm_map (x : E) : nnnorm (f x) = nnnorm x := nnreal.eq $ f.norm_map x protected lemma isometry : isometry f := f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map @[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y @[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y protected lemma injective : injective f := f.isometry.injective lemma map_eq_iff {x y : E} : f x = f y ↔ x = y := f.injective.eq_iff lemma map_ne {x y : E} (h : x ≠ y) : f x ≠ f y := f.injective.ne h protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz @[continuity] protected lemma continuous : continuous f := f.isometry.continuous lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s := f.isometry.ediam_image s lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) := f.isometry.ediam_range lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s := f.isometry.diam_image s lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) := f.isometry.diam_range /-- Interpret a linear isometry as a continuous linear map. -/ def to_continuous_linear_map : E →L[R] F := ⟨f.to_linear_map, f.continuous⟩ @[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} : continuous (f ∘ g) ↔ continuous g := f.isometry.uniform_embedding.to_uniform_inducing.inducing.continuous_iff.symm /-- The identity linear isometry. -/ def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩ @[simp] lemma coe_id : ⇑(id : E →ₗᵢ[R] E) = id := rfl instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩ /-- Composition of linear isometries. -/ def comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : E →ₗᵢ[R] G := ⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩ @[simp] lemma coe_comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : ⇑(g.comp f) = g ∘ f := rfl @[simp] lemma id_comp : (id : F →ₗᵢ[R] F).comp f = f := ext $ λ x, rfl @[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl lemma comp_assoc (f : G →ₗᵢ[R] G') (g : F →ₗᵢ[R] G) (h : E →ₗᵢ[R] F) : (f.comp g).comp h = f.comp (g.comp h) := rfl instance : monoid (E →ₗᵢ[R] E) := { one := id, mul := comp, mul_assoc := comp_assoc, one_mul := id_comp, mul_one := comp_id } @[simp] lemma coe_one : ⇑(1 : E →ₗᵢ[R] E) = id := rfl @[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl end linear_isometry /-- A linear isometric equivalence between two normed vector spaces. -/ structure linear_isometry_equiv (R E F : Type*) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] extends E ≃ₗ[R] F := (norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥) notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry_equiv R E F namespace linear_isometry_equiv variables (e : E ≃ₗᵢ[R] F) instance : has_coe_to_fun (E ≃ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk (e : E ≃ₗ[R] F) (he : ∀ x, ∥e x∥ = ∥x∥) : ⇑(mk e he) = e := rfl @[simp] lemma coe_to_linear_equiv (e : E ≃ₗᵢ[R] F) : ⇑e.to_linear_equiv = e := rfl lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₗᵢ[R] F) → (E ≃ₗ[R] F)) | ⟨e, _⟩ ⟨_, _⟩ rfl := rfl @[ext] lemma ext {e e' : E ≃ₗᵢ[R] F} (h : ∀ x, e x = e' x) : e = e' := to_linear_equiv_injective $ linear_equiv.ext h /-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities: `∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/ def of_bounds (e : E ≃ₗ[R] F) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) : E ≃ₗᵢ[R] F := ⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩ @[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x /-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/ def to_linear_isometry : E →ₗᵢ[R] F := ⟨e.1, e.2⟩ protected lemma isometry : isometry e := e.to_linear_isometry.isometry /-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/ def to_isometric : E ≃ᵢ F := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩ protected lemma continuous : continuous e := e.isometry.continuous variables (R E) /-- Identity map as a `linear_isometry_equiv`. -/ def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩ variables {R E} instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩ @[simp] lemma coe_refl : ⇑(refl R E) = id := rfl /-- The inverse `linear_isometry_equiv`. -/ def symm : F ≃ₗᵢ[R] E := ⟨e.to_linear_equiv.symm, λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩ @[simp] lemma apply_symm_apply (x : F) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x @[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff @[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl @[simp] lemma coe_symm_to_linear_equiv : ⇑e.to_linear_equiv.symm = e.symm := rfl /-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/ def trans (e' : F ≃ₗᵢ[R] G) : E ≃ₗᵢ[R] G := ⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩ @[simp] lemma coe_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp] lemma trans_refl : e.trans (refl R F) = e := ext $ λ x, rfl @[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl @[simp] lemma trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply @[simp] lemma symm_trans : e.symm.trans e = refl R F := ext e.apply_symm_apply @[simp] lemma coe_symm_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm := rfl lemma trans_assoc (eEF : E ≃ₗᵢ[R] F) (eFG : F ≃ₗᵢ[R] G) (eGG' : G ≃ₗᵢ[R] G') : eEF.trans (eFG.trans eGG') = (eEF.trans eFG).trans eGG' := rfl instance : group (E ≃ₗᵢ[R] E) := { mul := λ e₁ e₂, e₂.trans e₁, one := refl _ _, inv := symm, one_mul := trans_refl, mul_one := refl_trans, mul_assoc := λ _ _ _, trans_assoc _ _ _, mul_left_inv := trans_symm } @[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl @[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl @[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl /-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/ def to_continuous_linear_equiv : E ≃L[R] F := ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩ @[simp] lemma map_zero : e 0 = 0 := e.1.map_zero @[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y @[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y @[simp] lemma map_smul (c : R) (x : E) : e (c • x) = c • e x := e.1.map_smul c x @[simp] lemma nnnorm_map (x : E) : nnnorm (e x) = nnnorm x := e.to_linear_isometry.nnnorm_map x @[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y := e.to_linear_isometry.dist_map x y @[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y := e.to_linear_isometry.edist_map x y protected lemma bijective : bijective e := e.1.bijective protected lemma injective : injective e := e.1.injective protected lemma surjective : surjective e := e.1.surjective lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s := e.isometry.ediam_image s lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s := e.isometry.diam_image s end linear_isometry_equiv
1f235ac494d43794e48ac0335dfb215463541119
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2011/IMO_2011_P6.lean
17f3d6fce113de9cfec538c6a342707e36307f0d
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
388
lean
import Geo.Geo.Core namespace Geo open Triangle def IMO_2011_P6 : Prop := ∀ (A B C : Point), acute ⟨A, B, C⟩ → let Γ := Triangle.circumcircle ⟨A, B, C⟩; ∀ (l : Line), tangent l Γ → let la := reflect l (Line.mk B C); let lb := reflect l (Line.mk C A); let lc := reflect l (Line.mk A B); tangent Γ $ Triangle.circumcircle (Triangle.buildLLL ⟨la, lb, lc⟩) end Geo
dad90aeca86819b5676b85a2902cfee8142b70f9
74a02dffce22907d2b61b8e226f1d9aa8384c7c0
/Cli/Extensions.lean
e1ed1c4726e207a38f2a784fa8b29b0fa1b8d496
[ "MIT" ]
permissive
mhuisi/lean4-cli-docker-test
7e0566c7397746701162e2e22fbad38afcf1e9c4
6b3881eaa22596f6f430654f61fc03719ee18c62
refs/heads/main
1,680,104,973,886
1,616,975,353,000
1,616,975,353,000
352,411,347
0
0
null
null
null
null
UTF-8
Lean
false
false
4,542
lean
import Cli.Basic section Utils namespace Array /-- Appends those elements of `right` to `left` whose `key` is not already contained in `left`. -/ def leftUnionBy [HasLess α] [DecidableRel ((· < ·) : α → α → Prop)] (key : β → α) (left : Array β) (right : Array β) : Array β := do let leftMap := left.map (fun v => (key v, v)) |>.toList |> Std.RBMap.ofList (lt := (· < ·)) let mut result := left for v in right do if ¬ leftMap.contains (key v) then result := result.push v return result /-- Prepends those elements of `left` to `right` whose `key` is not already contained in `right`. -/ def rightUnionBy [HasLess α] [DecidableRel ((· < ·) : α → α → Prop)] (key : β → α) (left : Array β) (right : Array β) : Array β := do let rightMap := right.map (fun v => (key v, v)) |>.toList |> Std.RBMap.ofList (lt := (· < ·)) let mut result := right for v in left.reverse do if ¬ rightMap.contains (key v) then result := #[v] ++ result return result /-- Deletes all elements from `left` whose `key` is in `right`. -/ def diffBy [HasLess α] [DecidableRel ((· < ·) : α → α → Prop)] (key : β → α) (left : Array β) (right : Array α) : Array β := let rightMap := Std.RBTree.ofList (lt := (· < ·)) right.toList left.filter fun v => ¬ (rightMap.contains <| key v) end Array end Utils namespace Cli section Extensions /-- Prepends an author name to the description of the command. -/ def author (author : String) : Extension := { extendMeta := fun meta => { meta with description := s!"{author}\n{meta.description}" } } /-- Appends a longer description to the end of the help. -/ def longDescription (description : String) : Extension := { extendMeta := fun meta => { meta with furtherInformation? := some <| meta.furtherInformation?.optStr ++ lines #[ meta.furtherInformation?.optStr, (if meta.furtherInformation?.isSome then "\n" else "") ++ renderSection "DESCRIPTION" description ] } } /-- Sets default values for flags that were not set by the user according to `defaults := #[(long flag name, default value), ...]` and denotes the default value in the flag description of the help. Panics if one of the designated long flag names cannot be found in the command. -/ def defaultValues! (defaults : Array (String × String)) : Extension := let findDefaultFlags meta := defaults.map <| fun (longName, defaultValue) => ⟨meta.flag! longName, defaultValue⟩ { extendMeta := fun meta => let defaultFlags := findDefaultFlags meta let newMetaFlags := meta.flags.map fun flag => if let some defaultFlag := defaultFlags.find? (·.flag.longName = flag.longName) then { flag with description := flag.description ++ s!" [Default: `{defaultFlag.value}`]" } else flag { meta with flags := newMetaFlags } postprocess := fun meta parsed => let defaultFlags := findDefaultFlags meta return { parsed with flags := parsed.flags.leftUnionBy (·.flag.longName) defaultFlags } } /-- Errors if one of `requiredFlags := #[long flag name, ...]` were not passed by the user. Denotes that the flag is required in the flag description of the help. Panics if one of the designated long flag names cannot be found in the command. -/ def require! (requiredFlags : Array String) : Extension := let findRequiredFlags meta := requiredFlags.map (meta.flag! ·) { extendMeta := fun meta => let requiredFlags := findRequiredFlags meta let newMetaFlags := meta.flags.map fun flag => if let some requiredFlag := requiredFlags.find? (·.longName = flag.longName) then { flag with description := "[Required] " ++ flag.description } else flag { meta with flags := newMetaFlags } postprocess := fun meta parsed => do if parsed.hasFlag "help" ∨ parsed.hasFlag "version" then return parsed let requiredFlags := findRequiredFlags meta let missingFlags := requiredFlags.diffBy (·.longName) <| parsed.flags.map (·.flag.longName) if let some missingFlag ← pure <| missingFlags.get? 0 then throw s!"Missing required flag `--{missingFlag.longName}`." return parsed } end Extensions end Cli
358303d987757d6fccfb5f0fcf4a5a4158776849
1a61aba1b67cddccce19532a9596efe44be4285f
/tests/lean/640a.hlean
224a7629a2e72143c84d233006bcf47856791404
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
919
hlean
section parameter {A : Type} definition relation : A → A → Type := λa b, a = b local abbreviation R := relation local abbreviation S [parsing-only] := relation variable {a : A} check relation a a check R a a check S a a end section parameter {A : Type} definition relation' : A → A → Type := λa b, a = b local infix `~1`:50 := relation' local infix [parsing-only] `~2`:50 := relation' variable {a : A} check relation' a a check a ~1 a check a ~2 a end section parameter {A : Type} definition relation'' : A → A → Type := λa b, a = b local infix [parsing-only] `~2`:50 := relation'' variable {a : A} check relation'' a a check a ~2 a check a ~2 a end section parameter {A : Type} definition relation''' : A → A → Type := λa b, a = b local abbreviation S [parsing-only] := relation''' variable {a : A} check relation''' a a check S a a end
cac64e68e2b7af987e5e83de97c454d97ed7e322
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/box_integral/partition/filter.lean
d797111834b4a2e24056f7e756efc8342103cc7c
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
28,146
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.subbox_induction import analysis.box_integral.partition.split /-! # Filters used in box-based integrals First we define a structure `box_integral.integration_params`. This structure will be used as an argument in the definition of `box_integral.integral` in order to use the same definition for a few well-known definitions of integrals based on partitions of a rectangular box into subboxes (Riemann integral, Henstock-Kurzweil integral, and McShane integral). This structure holds three boolean values (see below), and encodes eight different sets of parameters; only four of these values are used somewhere in `mathlib`. Three of them correspond to the integration theories listed above, and one is a generalization of the one-dimensional Henstock-Kurzweil integral such that the divergence theorem works without additional integrability assumptions. Finally, for each set of parameters `l : box_integral.integration_params` and a rectangular box `I : box_integral.box ι`, we define several `filter`s that will be used either in the definition of the corresponding integral, or in the proofs of its properties. We equip `box_integral.integration_params` with a `bounded_order` structure such that larger `integration_params` produce larger filters. ## Main definitions ### Integration parameters The structure `box_integral.integration_params` has 3 boolean fields with the following meaning: * `bRiemann`: the value `tt` means that the filter corresponds to a Riemann-style integral, i.e. in the definition of integrability we require a constant upper estimate `r` on the size of boxes of a tagged partition; the value `ff` means that the estimate may depend on the position of the tag. * `bHenstock`: the value `tt` means that we require that each tag belongs to its own closed box; the value `ff` means that we only require that tags belong to the ambient box. * `bDistortion`: the value `tt` means that `r` can depend on the maximal ratio of sides of the same box of a partition. Presence of this case make quite a few proofs harder but we can prove the divergence theorem only for the filter `box_integral.integration_params.GP = ⊥ = {bRiemann := ff, bHenstock := tt, bDistortion := tt}`. ### Well-known sets of parameters Out of eight possible values of `box_integral.integration_params`, the following four are used in the library. * `box_integral.integration_params.Riemann` (`bRiemann = tt`, `bHenstock = tt`, `bDistortion = ff`): this value corresponds to the Riemann integral; in the corresponding filter, we require that the diameters of all boxes `J` of a tagged partition are bounded from above by a constant upper estimate that may not depend on the geometry of `J`, and each tag belongs to the corresponding closed box. * `box_integral.integration_params.Henstock` (`bRiemann = ff`, `bHenstock = tt`, `bDistortion = ff`): this value corresponds to the most natural generalization of Henstock-Kurzweil integral to higher dimension; the only (but important!) difference between this theory and Riemann integral is that instead of a constant upper estimate on the size of all boxes of a partition, we require that the partition is *subordinate* to a possibly discontinuous function `r : (ι → ℝ) → {x : ℝ | 0 < x}`, i.e. each box `J` is included in a closed ball with center `π.tag J` and radius `r J`. * `box_integral.integration_params.McShane` (`bRiemann = ff`, `bHenstock = ff`, `bDistortion = ff`): this value corresponds to the McShane integral; the only difference with the Henstock integral is that we allow tags to be outside of their boxes; the tags still have to be in the ambient closed box, and the partition still has to be subordinate to a function. * `box_integral.integration_params.GP = ⊥` (`bRiemann = ff`, `bHenstock = tt`, `bDistortion = tt`): this is the least integration theory in our list, i.e., all functions integrable in any other theory is integrable in this one as well. This is a non-standard generalization of the Henstock-Kurzweil integral to higher dimension. In dimension one, it generates the same filter as `Henstock`. In higher dimension, this generalization defines an integration theory such that the divergence of any Fréchet differentiable function `f` is integrable, and its integral is equal to the sum of integrals of `f` over the faces of the box, taken with appropriate signs. A function `f` is `GP`-integrable if for any `ε > 0` and `c : ℝ≥0` there exists `r : (ι → ℝ) → {x : ℝ | 0 < x}` such that for any tagged partition `π` subordinate to `r`, if each tag belongs to the corresponding closed box and for each box `J ∈ π`, the maximal ratio of its sides is less than or equal to `c`, then the integral sum of `f` over `π` is `ε`-close to the integral. ### Filters and predicates on `tagged_prepartition I` For each value of `integration_params` and a rectangular box `I`, we define a few filters on `tagged_prepartition I`. First, we define a predicate ``` structure box_integral.integration_params.mem_base_set (l : box_integral.integration_params) (I : box_integral.box ι) (c : ℝ≥0) (r : (ι → ℝ) → Ioi (0 : ℝ)) (π : box_integral.tagged_prepartition I) : Prop := ``` This predicate says that * if `l.bHenstock`, then `π` is a Henstock prepartition, i.e. each tag belongs to the corresponding closed box; * `π` is subordinate to `r`; * if `l.bDistortion`, then the distortion of each box in `π` is less than or equal to `c`; * if `l.bDistortion`, then there exists a prepartition `π'` with distortion `≤ c` that covers exactly `I \ π.Union`. The last condition is always true for `c > 1`, see TODO section for more details. Then we define a predicate `box_integral.integration_params.r_cond` on functions `r : (ι → ℝ) → {x : ℝ | 0 < x}`. If `l.bRiemann`, then this predicate requires `r` to be a constant function, otherwise it imposes no restrictions on `r`. We introduce this definition to prove a few dot-notation lemmas: e.g., `box_integral.integration_params.r_cond.min` says that the pointwise minimum of two functions that satisfy this condition satisfies this condition as well. Then we define four filters on `box_integral.tagged_prepartition I`. * `box_integral.integration_params.to_filter_distortion`: an auxiliary filter that takes parameters `(l : box_integral.integration_params) (I : box_integral.box ι) (c : ℝ≥0)` and returns the filter generated by all sets `{π | mem_base_set l I c r π}`, where `r` is a function satisfying the predicate `box_integral.integration_params.r_cond l`; * `box_integral.integration_params.to_filter l I`: the supremum of `l.to_filter_distortion I c` over all `c : ℝ≥0`; * `box_integral.integration_params.to_filter_distortion_Union l I c π₀`, where `π₀` is a prepartition of `I`: the infimum of `l.to_filter_distortion I c` and the principal filter generated by `{π | π.Union = π₀.Union}`; * `box_integral.integration_params.to_filter_Union l I π₀`: the supremum of `l.to_filter_distortion_Union l I c π₀` over all `c : ℝ≥0`. This is the filter (in the case `π₀ = ⊤` is the one-box partition of `I`) used in the definition of the integral of a function over a box. ## Implementation details * Later we define the integral of a function over a rectangular box as the limit (if it exists) of the integral sums along `box_integral.integration_params.to_filter_Union l I ⊤`. While it is possible to define the integral with a general filter on `box_integral.tagged_prepartition I` as a parameter, many lemmas (e.g., Sacks-Henstock lemma and most results about integrability of functions) require the filter to have a predictable structure. So, instead of adding assumptions about the filter here and there, we define this auxiliary type that can encode all integration theories we need in practice. * While the definition of the integral only uses the filter `box_integral.integration_params.to_filter_Union l I ⊤` and partitions of a box, some lemmas (e.g., the Henstock-Sacks lemmas) are best formulated in terms of the predicate `mem_base_set` and other filters defined above. * We use `bool` instead of `Prop` for the fields of `integration_params` in order to have decidable equality and inequalities. ## TODO Currently, `box_integral.integration_params.mem_base_set` explicitly requires that there exists a partition of the complement `I \ π.Union` with distortion `≤ c`. For `c > 1`, this condition is always true but the proof of this fact requires more API about `box_integral.prepartition.split_many`. We should formalize this fact, then either require `c > 1` everywhere, or replace `≤ c` with `< c` so that we automatically get `c > 1` for a non-trivial prepartition (and consider the special case `π = ⊥` separately if needed). ## Tags integral, rectangular box, partition, filter -/ open set function filter metric finset bool open_locale classical topology filter nnreal noncomputable theory namespace box_integral variables {ι : Type*} [fintype ι] {I J : box ι} {c c₁ c₂ : ℝ≥0} {r r₁ r₂ : (ι → ℝ) → Ioi (0 : ℝ)} {π π₁ π₂ : tagged_prepartition I} open tagged_prepartition /-- An `integration_params` is a structure holding 3 boolean values used to define a filter to be used in the definition of a box-integrable function. * `bRiemann`: the value `tt` means that the filter corresponds to a Riemann-style integral, i.e. in the definition of integrability we require a constant upper estimate `r` on the size of boxes of a tagged partition; the value `ff` means that the estimate may depend on the position of the tag. * `bHenstock`: the value `tt` means that we require that each tag belongs to its own closed box; the value `ff` means that we only require that tags belong to the ambient box. * `bDistortion`: the value `tt` means that `r` can depend on the maximal ratio of sides of the same box of a partition. Presence of this case makes quite a few proofs harder but we can prove the divergence theorem only for the filter `box_integral.integration_params.GP = ⊥ = {bRiemann := ff, bHenstock := tt, bDistortion := tt}`. -/ @[ext] structure integration_params : Type := (bRiemann bHenstock bDistortion : bool) variables {l l₁ l₂ : integration_params} namespace integration_params /-- Auxiliary equivalence with a product type used to lift an order. -/ def equiv_prod : integration_params ≃ bool × boolᵒᵈ × boolᵒᵈ := { to_fun := λ l, ⟨l.1, order_dual.to_dual l.2, order_dual.to_dual l.3⟩, inv_fun := λ l, ⟨l.1, order_dual.of_dual l.2.1, order_dual.of_dual l.2.2⟩, left_inv := λ ⟨a, b, c⟩, rfl, right_inv := λ ⟨a, b, c⟩, rfl } instance : partial_order integration_params := partial_order.lift equiv_prod equiv_prod.injective /-- Auxiliary `order_iso` with a product type used to lift a `bounded_order` structure. -/ def iso_prod : integration_params ≃o bool × boolᵒᵈ × boolᵒᵈ := ⟨equiv_prod, λ ⟨x, y, z⟩, iff.rfl⟩ instance : bounded_order integration_params := iso_prod.symm.to_galois_insertion.lift_bounded_order /-- The value `box_integral.integration_params.GP = ⊥` (`bRiemann = ff`, `bHenstock = tt`, `bDistortion = tt`) corresponds to a generalization of the Henstock integral such that the Divergence theorem holds true without additional integrability assumptions, see the module docstring for details. -/ instance : inhabited integration_params := ⟨⊥⟩ instance : decidable_rel ((≤) : integration_params → integration_params → Prop) := λ _ _, and.decidable instance : decidable_eq integration_params := λ x y, decidable_of_iff _ (ext_iff x y).symm /-- The `box_integral.integration_params` corresponding to the Riemann integral. In the corresponding filter, we require that the diameters of all boxes `J` of a tagged partition are bounded from above by a constant upper estimate that may not depend on the geometry of `J`, and each tag belongs to the corresponding closed box. -/ def Riemann : integration_params := { bRiemann := tt, bHenstock := tt, bDistortion := ff } /-- The `box_integral.integration_params` corresponding to the Henstock-Kurzweil integral. In the corresponding filter, we require that the tagged partition is subordinate to a (possibly, discontinuous) positive function `r` and each tag belongs to the corresponding closed box. -/ def Henstock : integration_params := ⟨ff, tt, ff⟩ /-- The `box_integral.integration_params` corresponding to the McShane integral. In the corresponding filter, we require that the tagged partition is subordinate to a (possibly, discontinuous) positive function `r`; the tags may be outside of the corresponding closed box (but still inside the ambient closed box `I.Icc`). -/ def McShane : integration_params := ⟨ff, ff, ff⟩ /-- The `box_integral.integration_params` corresponding to the generalized Perron integral. In the corresponding filter, we require that the tagged partition is subordinate to a (possibly, discontinuous) positive function `r` and each tag belongs to the corresponding closed box. We also require an upper estimate on the distortion of all boxes of the partition. -/ def GP : integration_params := ⊥ lemma Henstock_le_Riemann : Henstock ≤ Riemann := dec_trivial lemma Henstock_le_McShane : Henstock ≤ McShane := dec_trivial lemma GP_le : GP ≤ l := bot_le /-- The predicate corresponding to a base set of the filter defined by an `integration_params`. It says that * if `l.bHenstock`, then `π` is a Henstock prepartition, i.e. each tag belongs to the corresponding closed box; * `π` is subordinate to `r`; * if `l.bDistortion`, then the distortion of each box in `π` is less than or equal to `c`; * if `l.bDistortion`, then there exists a prepartition `π'` with distortion `≤ c` that covers exactly `I \ π.Union`. The last condition is automatically verified for partitions, and is used in the proof of the Sacks-Henstock inequality to compare two prepartitions covering the same part of the box. It is also automatically satisfied for any `c > 1`, see TODO section of the module docstring for details. -/ @[protect_proj] structure mem_base_set (l : integration_params) (I : box ι) (c : ℝ≥0) (r : (ι → ℝ) → Ioi (0 : ℝ)) (π : tagged_prepartition I) : Prop := (is_subordinate : π.is_subordinate r) (is_Henstock : l.bHenstock → π.is_Henstock) (distortion_le : l.bDistortion → π.distortion ≤ c) (exists_compl : l.bDistortion → ∃ π' : prepartition I, π'.Union = I \ π.Union ∧ π'.distortion ≤ c) /-- A predicate saying that in case `l.bRiemann = tt`, the function `r` is a constant. -/ def r_cond {ι : Type*} (l : integration_params) (r : (ι → ℝ) → Ioi (0 : ℝ)) : Prop := l.bRiemann → ∀ x, r x = r 0 /-- A set `s : set (tagged_prepartition I)` belongs to `l.to_filter_distortion I c` if there exists a function `r : ℝⁿ → (0, ∞)` (or a constant `r` if `l.bRiemann = tt`) such that `s` contains each prepartition `π` such that `l.mem_base_set I c r π`. -/ def to_filter_distortion (l : integration_params) (I : box ι) (c : ℝ≥0) : filter (tagged_prepartition I) := ⨅ (r : (ι → ℝ) → Ioi (0 : ℝ)) (hr : l.r_cond r), 𝓟 {π | l.mem_base_set I c r π} /-- A set `s : set (tagged_prepartition I)` belongs to `l.to_filter I` if for any `c : ℝ≥0` there exists a function `r : ℝⁿ → (0, ∞)` (or a constant `r` if `l.bRiemann = tt`) such that `s` contains each prepartition `π` such that `l.mem_base_set I c r π`. -/ def to_filter (l : integration_params) (I : box ι) : filter (tagged_prepartition I) := ⨆ c : ℝ≥0, l.to_filter_distortion I c /-- A set `s : set (tagged_prepartition I)` belongs to `l.to_filter_distortion_Union I c π₀` if there exists a function `r : ℝⁿ → (0, ∞)` (or a constant `r` if `l.bRiemann = tt`) such that `s` contains each prepartition `π` such that `l.mem_base_set I c r π` and `π.Union = π₀.Union`. -/ def to_filter_distortion_Union (l : integration_params) (I : box ι) (c : ℝ≥0) (π₀ : prepartition I) := l.to_filter_distortion I c ⊓ 𝓟 {π | π.Union = π₀.Union} /-- A set `s : set (tagged_prepartition I)` belongs to `l.to_filter_Union I π₀` if for any `c : ℝ≥0` there exists a function `r : ℝⁿ → (0, ∞)` (or a constant `r` if `l.bRiemann = tt`) such that `s` contains each prepartition `π` such that `l.mem_base_set I c r π` and `π.Union = π₀.Union`. -/ def to_filter_Union (l : integration_params) (I : box ι) (π₀ : prepartition I) := ⨆ c : ℝ≥0, l.to_filter_distortion_Union I c π₀ lemma r_cond_of_bRiemann_eq_ff {ι} (l : integration_params) (hl : l.bRiemann = ff) {r : (ι → ℝ) → Ioi (0 : ℝ)} : l.r_cond r := by simp [r_cond, hl] lemma to_filter_inf_Union_eq (l : integration_params) (I : box ι) (π₀ : prepartition I) : l.to_filter I ⊓ 𝓟 {π | π.Union = π₀.Union} = l.to_filter_Union I π₀ := (supr_inf_principal _ _).symm lemma mem_base_set.mono' (I : box ι) (h : l₁ ≤ l₂) (hc : c₁ ≤ c₂) {π : tagged_prepartition I} (hr : ∀ J ∈ π, r₁ (π.tag J) ≤ r₂ (π.tag J)) (hπ : l₁.mem_base_set I c₁ r₁ π) : l₂.mem_base_set I c₂ r₂ π := ⟨hπ.1.mono' hr, λ h₂, hπ.2 (le_iff_imp.1 h.2.1 h₂), λ hD, (hπ.3 (le_iff_imp.1 h.2.2 hD)).trans hc, λ hD, (hπ.4 (le_iff_imp.1 h.2.2 hD)).imp $ λ π hπ, ⟨hπ.1, hπ.2.trans hc⟩⟩ @[mono] lemma mem_base_set.mono (I : box ι) (h : l₁ ≤ l₂) (hc : c₁ ≤ c₂) {π : tagged_prepartition I} (hr : ∀ x ∈ I.Icc, r₁ x ≤ r₂ x) (hπ : l₁.mem_base_set I c₁ r₁ π) : l₂.mem_base_set I c₂ r₂ π := hπ.mono' I h hc $ λ J hJ, hr _ $ π.tag_mem_Icc J lemma mem_base_set.exists_common_compl (h₁ : l.mem_base_set I c₁ r₁ π₁) (h₂ : l.mem_base_set I c₂ r₂ π₂) (hU : π₁.Union = π₂.Union) : ∃ π : prepartition I, π.Union = I \ π₁.Union ∧ (l.bDistortion → π.distortion ≤ c₁) ∧ (l.bDistortion → π.distortion ≤ c₂) := begin wlog hc : c₁ ≤ c₂, { simpa [hU, and_comm] using this h₂ h₁ hU.symm (le_of_not_le hc) }, by_cases hD : (l.bDistortion : Prop), { rcases h₁.4 hD with ⟨π, hπU, hπc⟩, exact ⟨π, hπU, λ _, hπc, λ _, hπc.trans hc⟩ }, { exact ⟨π₁.to_prepartition.compl, π₁.to_prepartition.Union_compl, λ h, (hD h).elim, λ h, (hD h).elim⟩ } end protected lemma mem_base_set.union_compl_to_subordinate (hπ₁ : l.mem_base_set I c r₁ π₁) (hle : ∀ x ∈ I.Icc, r₂ x ≤ r₁ x) {π₂ : prepartition I} (hU : π₂.Union = I \ π₁.Union) (hc : l.bDistortion → π₂.distortion ≤ c) : l.mem_base_set I c r₁ (π₁.union_compl_to_subordinate π₂ hU r₂) := ⟨hπ₁.1.disj_union ((π₂.is_subordinate_to_subordinate r₂).mono hle) _, λ h, ((hπ₁.2 h).disj_union (π₂.is_Henstock_to_subordinate _) _), λ h, (distortion_union_compl_to_subordinate _ _ _ _).trans_le (max_le (hπ₁.3 h) (hc h)), λ _, ⟨⊥, by simp⟩⟩ protected lemma mem_base_set.filter (hπ : l.mem_base_set I c r π) (p : box ι → Prop) : l.mem_base_set I c r (π.filter p) := begin refine ⟨λ J hJ, hπ.1 J (π.mem_filter.1 hJ).1, λ hH J hJ, hπ.2 hH J (π.mem_filter.1 hJ).1, λ hD, (distortion_filter_le _ _).trans (hπ.3 hD), λ hD, _⟩, rcases hπ.4 hD with ⟨π₁, hπ₁U, hc⟩, set π₂ := π.filter (λ J, ¬p J), have : disjoint π₁.Union π₂.Union, by simpa [π₂, hπ₁U] using disjoint_sdiff_self_left.mono_right sdiff_le, refine ⟨π₁.disj_union π₂.to_prepartition this, _, _⟩, { suffices : ↑I \ π.Union ∪ π.Union \ (π.filter p).Union = ↑I \ (π.filter p).Union, by simpa *, have : (π.filter p).Union ⊆ π.Union, from bUnion_subset_bUnion_left (finset.filter_subset _ _), ext x, fsplit, { rintro (⟨hxI, hxπ⟩|⟨hxπ, hxp⟩), exacts [⟨hxI, mt (@this x) hxπ⟩, ⟨π.Union_subset hxπ, hxp⟩] }, { rintro ⟨hxI, hxp⟩, by_cases hxπ : x ∈ π.Union, exacts [or.inr ⟨hxπ, hxp⟩, or.inl ⟨hxI, hxπ⟩] } }, { have : (π.filter (λ J, ¬p J)).distortion ≤ c, from (distortion_filter_le _ _).trans (hπ.3 hD), simpa [hc] } end lemma bUnion_tagged_mem_base_set {π : prepartition I} {πi : Π J, tagged_prepartition J} (h : ∀ J ∈ π, l.mem_base_set J c r (πi J)) (hp : ∀ J ∈ π, (πi J).is_partition) (hc : l.bDistortion → π.compl.distortion ≤ c) : l.mem_base_set I c r (π.bUnion_tagged πi) := begin refine ⟨tagged_prepartition.is_subordinate_bUnion_tagged.2 $ λ J hJ, (h J hJ).1, λ hH, tagged_prepartition.is_Henstock_bUnion_tagged.2 $ λ J hJ, (h J hJ).2 hH, λ hD, _, λ hD, _⟩, { rw [prepartition.distortion_bUnion_tagged, finset.sup_le_iff], exact λ J hJ, (h J hJ).3 hD }, { refine ⟨_, _, hc hD⟩, rw [π.Union_compl, ← π.Union_bUnion_partition hp], refl } end @[mono] lemma r_cond.mono {ι : Type*} {r : (ι → ℝ) → Ioi (0 : ℝ)} (h : l₁ ≤ l₂) (hr : l₂.r_cond r) : l₁.r_cond r := λ hR, hr (le_iff_imp.1 h.1 hR) lemma r_cond.min {ι : Type*} {r₁ r₂ : (ι → ℝ) → Ioi (0 : ℝ)} (h₁ : l.r_cond r₁) (h₂ : l.r_cond r₂) : l.r_cond (λ x, min (r₁ x) (r₂ x)) := λ hR x, congr_arg2 min (h₁ hR x) (h₂ hR x) @[mono] lemma to_filter_distortion_mono (I : box ι) (h : l₁ ≤ l₂) (hc : c₁ ≤ c₂) : l₁.to_filter_distortion I c₁ ≤ l₂.to_filter_distortion I c₂ := infi_mono $ λ r, infi_mono' $ λ hr, ⟨hr.mono h, principal_mono.2 $ λ _, mem_base_set.mono I h hc (λ _ _, le_rfl)⟩ @[mono] lemma to_filter_mono (I : box ι) {l₁ l₂ : integration_params} (h : l₁ ≤ l₂) : l₁.to_filter I ≤ l₂.to_filter I := supr_mono $ λ c, to_filter_distortion_mono I h le_rfl @[mono] lemma to_filter_Union_mono (I : box ι) {l₁ l₂ : integration_params} (h : l₁ ≤ l₂) (π₀ : prepartition I) : l₁.to_filter_Union I π₀ ≤ l₂.to_filter_Union I π₀ := supr_mono $ λ c, inf_le_inf_right _ $ to_filter_distortion_mono _ h le_rfl lemma to_filter_Union_congr (I : box ι) (l : integration_params) {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) : l.to_filter_Union I π₁ = l.to_filter_Union I π₂ := by simp only [to_filter_Union, to_filter_distortion_Union, h] lemma has_basis_to_filter_distortion (l : integration_params) (I : box ι) (c : ℝ≥0) : (l.to_filter_distortion I c).has_basis l.r_cond (λ r, {π | l.mem_base_set I c r π}) := has_basis_binfi_principal' (λ r₁ hr₁ r₂ hr₂, ⟨_, hr₁.min hr₂, λ _, mem_base_set.mono _ le_rfl le_rfl (λ x hx, min_le_left _ _), λ _, mem_base_set.mono _ le_rfl le_rfl (λ x hx, min_le_right _ _)⟩) ⟨λ _, ⟨1, zero_lt_one⟩, λ _ _, rfl⟩ lemma has_basis_to_filter_distortion_Union (l : integration_params) (I : box ι) (c : ℝ≥0) (π₀ : prepartition I) : (l.to_filter_distortion_Union I c π₀).has_basis l.r_cond (λ r, {π | l.mem_base_set I c r π ∧ π.Union = π₀.Union}) := (l.has_basis_to_filter_distortion I c).inf_principal _ lemma has_basis_to_filter_Union (l : integration_params) (I : box ι) (π₀ : prepartition I) : (l.to_filter_Union I π₀).has_basis (λ r : ℝ≥0 → (ι → ℝ) → Ioi (0 : ℝ), ∀ c, l.r_cond (r c)) (λ r, {π | ∃ c, l.mem_base_set I c (r c) π ∧ π.Union = π₀.Union}) := have _ := λ c, l.has_basis_to_filter_distortion_Union I c π₀, by simpa only [set_of_and, set_of_exists] using has_basis_supr this lemma has_basis_to_filter_Union_top (l : integration_params) (I : box ι) : (l.to_filter_Union I ⊤).has_basis (λ r : ℝ≥0 → (ι → ℝ) → Ioi (0 : ℝ), ∀ c, l.r_cond (r c)) (λ r, {π | ∃ c, l.mem_base_set I c (r c) π ∧ π.is_partition}) := by simpa only [tagged_prepartition.is_partition_iff_Union_eq, prepartition.Union_top] using l.has_basis_to_filter_Union I ⊤ lemma has_basis_to_filter (l : integration_params) (I : box ι) : (l.to_filter I).has_basis (λ r : ℝ≥0 → (ι → ℝ) → Ioi (0 : ℝ), ∀ c, l.r_cond (r c)) (λ r, {π | ∃ c, l.mem_base_set I c (r c) π}) := by simpa only [set_of_exists] using has_basis_supr (l.has_basis_to_filter_distortion I) lemma tendsto_embed_box_to_filter_Union_top (l : integration_params) (h : I ≤ J) : tendsto (tagged_prepartition.embed_box I J h) (l.to_filter_Union I ⊤) (l.to_filter_Union J (prepartition.single J I h)) := begin simp only [to_filter_Union, tendsto_supr], intro c, set π₀ := (prepartition.single J I h), refine le_supr_of_le (max c π₀.compl.distortion) _, refine ((l.has_basis_to_filter_distortion_Union I c ⊤).tendsto_iff (l.has_basis_to_filter_distortion_Union J _ _)).2 (λ r hr, _), refine ⟨r, hr, λ π hπ, _⟩, rw [mem_set_of_eq, prepartition.Union_top] at hπ, refine ⟨⟨hπ.1.1, hπ.1.2, λ hD, le_trans (hπ.1.3 hD) (le_max_left _ _), λ hD, _⟩, _⟩, { refine ⟨_, π₀.Union_compl.trans _, le_max_right _ _⟩, congr' 1, exact (prepartition.Union_single h).trans hπ.2.symm }, { exact hπ.2.trans (prepartition.Union_single _).symm } end lemma exists_mem_base_set_le_Union_eq (l : integration_params) (π₀ : prepartition I) (hc₁ : π₀.distortion ≤ c) (hc₂ : π₀.compl.distortion ≤ c) (r : (ι → ℝ) → Ioi (0 : ℝ)) : ∃ π, l.mem_base_set I c r π ∧ π.to_prepartition ≤ π₀ ∧ π.Union = π₀.Union := begin rcases π₀.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r with ⟨π, hle, hH, hr, hd, hU⟩, refine ⟨π, ⟨hr, λ _, hH, λ _, hd.trans_le hc₁, λ hD, ⟨π₀.compl, _, hc₂⟩⟩, ⟨hle, hU⟩⟩, exact prepartition.compl_congr hU ▸ π.to_prepartition.Union_compl end lemma exists_mem_base_set_is_partition (l : integration_params) (I : box ι) (hc : I.distortion ≤ c) (r : (ι → ℝ) → Ioi (0 : ℝ)) : ∃ π, l.mem_base_set I c r π ∧ π.is_partition := begin rw ← prepartition.distortion_top at hc, have hc' : (⊤ : prepartition I).compl.distortion ≤ c, by simp, simpa [is_partition_iff_Union_eq] using l.exists_mem_base_set_le_Union_eq ⊤ hc hc' r end lemma to_filter_distortion_Union_ne_bot (l : integration_params) (I : box ι) (π₀ : prepartition I) (hc₁ : π₀.distortion ≤ c) (hc₂ : π₀.compl.distortion ≤ c) : (l.to_filter_distortion_Union I c π₀).ne_bot := ((l.has_basis_to_filter_distortion I _).inf_principal _).ne_bot_iff.2 $ λ r hr, (l.exists_mem_base_set_le_Union_eq π₀ hc₁ hc₂ r).imp $ λ π hπ, ⟨hπ.1, hπ.2.2⟩ instance to_filter_distortion_Union_ne_bot' (l : integration_params) (I : box ι) (π₀ : prepartition I) : (l.to_filter_distortion_Union I (max π₀.distortion π₀.compl.distortion) π₀).ne_bot := l.to_filter_distortion_Union_ne_bot I π₀ (le_max_left _ _) (le_max_right _ _) instance to_filter_distortion_ne_bot (l : integration_params) (I : box ι) : (l.to_filter_distortion I I.distortion).ne_bot := by simpa using (l.to_filter_distortion_Union_ne_bot' I ⊤).mono inf_le_left instance to_filter_ne_bot (l : integration_params) (I : box ι) : (l.to_filter I).ne_bot := (l.to_filter_distortion_ne_bot I).mono $ le_supr _ _ instance to_filter_Union_ne_bot (l : integration_params) (I : box ι) (π₀ : prepartition I) : (l.to_filter_Union I π₀).ne_bot := (l.to_filter_distortion_Union_ne_bot' I π₀).mono $ le_supr (λ c, l.to_filter_distortion_Union I c π₀) _ lemma eventually_is_partition (l : integration_params) (I : box ι) : ∀ᶠ π in l.to_filter_Union I ⊤, tagged_prepartition.is_partition π := eventually_supr.2 $ λ c, eventually_inf_principal.2 $ eventually_of_forall $ λ π h, π.is_partition_iff_Union_eq.2 (h.trans prepartition.Union_top) end integration_params end box_integral
11a233bfef673775b4583945c3776a5b4b0100f5
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/order/galois_connection.lean
cb3e48d563370ed90180abfebcc75fa2ab998a1d
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
11,133
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 Galois connections - order theoretic adjoints. -/ import order.bounds order.order_iso open function set lattice universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β} /-- A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are closely connected to adjoint functors in category theory. -/ def galois_connection [preorder α] [preorder β] (l : α → β) (u : β → α) := ∀a b, l a ≤ b ↔ a ≤ u b /-- Makes a Galois connection from an order-preserving bijection. -/ theorem order_iso.to_galois_connection [preorder α] [preorder β] (oi : @order_iso α β (≤) (≤)) : galois_connection oi oi.symm := λ b g, by rw [order_iso.ord' oi, order_iso.apply_symm_apply] namespace galois_connection section variables [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) lemma monotone_intro (hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ a, l (u a) ≤ a) : galois_connection l u := assume a b, ⟨assume h, le_trans (hul _) (hu h), assume h, le_trans (hl h) (hlu _)⟩ include gc lemma l_le {a : α} {b : β} : a ≤ u b → l a ≤ b := (gc _ _).mpr lemma le_u {a : α} {b : β} : l a ≤ b → a ≤ u b := (gc _ _).mp lemma le_u_l (a) : a ≤ u (l a) := gc.le_u $ le_refl _ lemma l_u_le (a) : l (u a) ≤ a := gc.l_le $ le_refl _ lemma monotone_u : monotone u := assume a b H, gc.le_u (le_trans (gc.l_u_le a) H) lemma monotone_l : monotone l := assume a b H, gc.l_le (le_trans H (gc.le_u_l b)) lemma upper_bounds_l_image_subset {s : set α} : upper_bounds (l '' s) ⊆ u ⁻¹' upper_bounds s := assume b hb c, assume : c ∈ s, gc.le_u (hb _ (mem_image_of_mem _ ‹c ∈ s›)) lemma lower_bounds_u_image_subset {s : set β} : lower_bounds (u '' s) ⊆ l ⁻¹' lower_bounds s := assume a ha c, assume : c ∈ s, gc.l_le (ha _ (mem_image_of_mem _ ‹c ∈ s›)) lemma is_lub_l_image {s : set α} {a : α} (h : is_lub s a) : is_lub (l '' s) (l a) := ⟨mem_upper_bounds_image gc.monotone_l $ and.elim_left ‹is_lub s a›, assume b hb, gc.l_le $ and.elim_right ‹is_lub s a› _ $ gc.upper_bounds_l_image_subset hb⟩ lemma is_glb_u_image {s : set β} {b : β} (h : is_glb s b) : is_glb (u '' s) (u b) := ⟨mem_lower_bounds_image gc.monotone_u $ and.elim_left ‹is_glb s b›, assume a ha, gc.le_u $ and.elim_right ‹is_glb s b› _ $ gc.lower_bounds_u_image_subset ha⟩ lemma is_glb_l {a : α} : is_glb { b | a ≤ u b } (l a) := ⟨assume b, gc.l_le, assume b h, h _ $ gc.le_u_l _⟩ lemma is_lub_u {b : β} : is_lub { a | l a ≤ b } (u b) := ⟨assume b, gc.le_u, assume b h, h _ $ gc.l_u_le _⟩ end section partial_order variables [partial_order α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_l_u_eq_u : u ∘ l ∘ u = u := funext (assume x, le_antisymm (gc.monotone_u (gc.l_u_le _)) (gc.le_u_l _)) lemma l_u_l_eq_l : l ∘ u ∘ l = l := funext (assume x, le_antisymm (gc.l_u_le _) (gc.monotone_l (gc.le_u_l _))) end partial_order section order_top variables [order_top α] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_top : u ⊤ = ⊤ := eq_of_is_glb_of_is_glb (gc.is_glb_u_image is_glb_empty) $ by simp [is_glb_empty, image_empty] end order_top section order_bot variables [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_bot : l ⊥ = ⊥ := eq_of_is_lub_of_is_lub (gc.is_lub_l_image is_lub_empty) $ by simp [is_lub_empty, image_empty] end order_bot section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_sup : l (a₁ ⊔ a₂) = l a₁ ⊔ l a₂ := have {l a₂, l a₁} = l '' {a₂, a₁}, by simp [image_insert_eq, image_singleton], eq.symm $ is_lub_iff_sup_eq.mp $ by rw [this]; exact gc.is_lub_l_image (is_lub_insert_sup is_lub_singleton) end semilattice_sup section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_inf : u (b₁ ⊓ b₂) = u b₁ ⊓ u b₂ := have {u b₂, u b₁} = u '' {b₂, b₁}, by simp [image_insert_eq, image_singleton], eq.symm $ is_glb_iff_inf_eq.mp $ by rw [this]; exact gc.is_glb_u_image (is_glb_insert_inf is_glb_singleton) end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_supr {f : ι → α} : l (supr f) = (⨆i, l (f i)) := eq.symm $ is_lub_iff_supr_eq.mp $ show is_lub (range (l ∘ f)) (l (supr f)), by rw [range_comp, ← Sup_range]; exact gc.is_lub_l_image is_lub_Sup lemma u_infi {f : ι → β} : u (infi f) = (⨅i, u (f i)) := eq.symm $ is_glb_iff_infi_eq.mp $ show is_glb (range (u ∘ f)) (u (infi f)), by rw [range_comp, ← Inf_range]; exact gc.is_glb_u_image is_glb_Inf end complete_lattice section complete_lattice variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_Sup {s : set α} : l (Sup s) = (⨆a∈s, l a) := by simp [Sup_eq_supr, gc.l_supr] lemma u_Inf {s : set β} : u (Inf s) = (⨅a∈s, u a) := by simp [Inf_eq_infi, gc.u_infi] end complete_lattice /- Constructing Galois connections -/ section constructions protected lemma id [pα : preorder α] : @galois_connection α α pα pα id id := assume a b, iff.intro (λx, x) (λx, x) protected lemma compose [preorder α] [preorder β] [preorder γ] (l1 : α → β) (u1 : β → α) (l2 : β → γ) (u2 : γ → β) (gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) : galois_connection (l2 ∘ l1) (u1 ∘ u2) := by intros a b; rw [gc2, gc1] protected lemma dual [pα : preorder α] [pβ : preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) : @galois_connection (order_dual β) (order_dual α) _ _ u l := assume a b, (gc _ _).symm protected lemma dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w} [∀i, preorder (α i)] [∀i, preorder (β i)] (l : Πi, α i → β i) (u : Πi, β i → α i) (gc : ∀i, galois_connection (l i) (u i)) : @galois_connection (Π i, α i) (Π i, β i) _ _ (λa i, l i (a i)) (λb i, u i (b i)) := assume a b, forall_congr $ assume i, gc i (a i) (b i) end constructions end galois_connection namespace nat lemma galois_connection_mul_div {k : ℕ} (h : k > 0) : galois_connection (λn, n * k) (λn, n / k) := assume x y, (le_div_iff_mul_le x y h).symm end nat /-- A Galois insertion is a Galois connection where `l ∘ u = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. -/ structure galois_insertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) := (choice : Πx:α, u (l x) ≤ x → β) (gc : galois_connection l u) (le_l_u : ∀x, x ≤ l (u x)) (choice_eq : ∀a h, choice a h = l a) /-- Makes a Galois insertion from an order-preserving bijection. -/ protected def order_iso.to_galois_insertion [preorder α] [preorder β] (oi : @order_iso α β (≤) (≤)) : @galois_insertion α β _ _ (oi) (oi.symm) := { choice := λ b h, oi b, gc := oi.to_galois_connection, le_l_u := λ g, le_of_eq (oi.right_inv g).symm, choice_eq := λ b h, rfl } /-- Lift the bottom along a Galois connection -/ def galois_connection.lift_order_bot {α β : Type*} [order_bot α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) : order_bot β := { bot := l ⊥, bot_le := assume b, gc.l_le $ bot_le, .. ‹partial_order β› } namespace galois_insertion open lattice variables [partial_order β] {l : α → β} {u : β → α} lemma l_u_eq [preorder α] (gi : galois_insertion l u) (b : β) : l (u b) = b := le_antisymm (gi.gc.l_u_le _) (gi.le_l_u _) /-- Lift the suprema along a Galois insertion -/ def lift_semilattice_sup [semilattice_sup α] (gi : galois_insertion l u) : semilattice_sup β := { sup := λa b, l (u a ⊔ u b), le_sup_left := assume a b, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_sup_left, le_sup_right := assume a b, le_trans (gi.le_l_u b) $ gi.gc.monotone_l $ le_sup_right, sup_le := assume a b c hac hbc, gi.gc.l_le $ sup_le (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the infima along a Galois insertion -/ def lift_semilattice_inf [semilattice_inf α] (gi : galois_insertion l u) : semilattice_inf β := { inf := λa b, gi.choice (u a ⊓ u b) $ (le_inf (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_left) (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_right)), inf_le_left := by simp only [gi.choice_eq]; exact assume a b, gi.gc.l_le inf_le_left, inf_le_right := by simp only [gi.choice_eq]; exact assume a b, gi.gc.l_le inf_le_right, le_inf := by simp only [gi.choice_eq]; exact assume a b c hac hbc, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_inf (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the suprema and infima along a Galois insertion -/ def lift_lattice [lattice α] (gi : galois_insertion l u) : lattice β := { .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf } /-- Lift the top along a Galois insertion -/ def lift_order_top [order_top α] (gi : galois_insertion l u) : order_top β := { top := gi.choice ⊤ $ le_top, le_top := by simp only [gi.choice_eq]; exact assume b, le_trans (gi.le_l_u b) (gi.gc.monotone_l le_top), .. ‹partial_order β› } /-- Lift the top, bottom, suprema, and infima along a Galois insertion -/ def lift_bounded_lattice [bounded_lattice α] (gi : galois_insertion l u) : bounded_lattice β := { .. gi.lift_lattice, .. gi.lift_order_top, .. gi.gc.lift_order_bot } /-- Lift all suprema and infima along a Galois insertion -/ def lift_complete_lattice [complete_lattice α] (gi : galois_insertion l u) : complete_lattice β := { Sup := λs, l (⨆ b∈s, u b), Sup_le := assume s a hs, gi.gc.l_le $ supr_le $ assume b, supr_le $ assume hb, gi.gc.monotone_u $ hs _ hb, le_Sup := assume s a ha, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_supr_of_le a $ le_supr_of_le ha $ le_refl _, Inf := λs, gi.choice (⨅ b∈s, u b) $ le_infi $ assume b, le_infi $ assume hb, gi.gc.monotone_u $ gi.gc.l_le $ infi_le_of_le b $ infi_le_of_le hb $ le_refl _, Inf_le := by simp only [gi.choice_eq]; exact assume s a ha, gi.gc.l_le $ infi_le_of_le a $ infi_le_of_le ha $ le_refl _, le_Inf := by simp only [gi.choice_eq]; exact assume s a hs, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_infi $ assume b, show u a ≤ ⨅ (H : b ∈ s), u b, from le_infi $ assume hb, gi.gc.monotone_u $ hs _ hb, .. gi.lift_bounded_lattice } end galois_insertion
651045d1856c9650d457b4824cf7bf4d8420d4a1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq6.lean
abef80185ee69337cadd8851fcb37364ebc788a0
[ "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
427
lean
import data.list open list definition append {A : Type} : list A → list A → list A | append nil l := l | append (h :: t) l := h :: (append t l) theorem append_nil {A : Type} (l : list A) : append nil l = l := rfl theorem append_cons {A : Type} (h : A) (t l : list A) : append (h :: t) l = h :: (append t l) := rfl example : append ((1:nat) :: 2 :: nil) (3 :: 4 :: 5 :: nil) = (1 :: 2 :: 3 :: 4 :: 5 :: nil) := rfl
df261502884057c1c8b7c24f9b458b9a569c5596
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/graded_algebra/basic.lean
725c8a72f92710687918843d22f480f979765aac
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,661
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang -/ import algebra.direct_sum.algebra import algebra.direct_sum.decomposition import algebra.direct_sum.internal import algebra.direct_sum.ring import group_theory.subgroup.basic /-! # Internally-graded rings and algebras This file defines the typeclass `graded_algebra 𝒜`, for working with an algebra `A` that is internally graded by a collection of submodules `𝒜 : ι → submodule R A`. See the docstring of that typeclass for more information. ## Main definitions * `graded_ring 𝒜`: the typeclass, which is a combination of `set_like.graded_monoid`, and `direct_sum.decomposition 𝒜`. * `graded_algebra 𝒜`: A convenience alias for `graded_ring` when `𝒜` is a family of submodules. * `direct_sum.decompose_ring_equiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of `direct_sum.decompose 𝒜`. * `direct_sum.decompose_alg_equiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of `direct_sum.decompose 𝒜`. * `graded_algebra.proj 𝒜 i` is the linear map from `A` to its degree `i : ι` component, such that `proj 𝒜 i x = decompose 𝒜 x i`. ## Implementation notes For now, we do not have internally-graded semirings and internally-graded rings; these can be represented with `𝒜 : ι → submodule ℕ A` and `𝒜 : ι → submodule ℤ A` respectively, since all `semiring`s are ℕ-algebras via `algebra_nat`, and all `ring`s are `ℤ`-algebras via `algebra_int`. ## Tags graded algebra, graded ring, graded semiring, decomposition -/ open_locale direct_sum big_operators variables {ι R A σ : Type*} section graded_ring variables [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) include A open direct_sum /-- An internally-graded `R`-algebra `A` is one that can be decomposed into a collection of `submodule R A`s indexed by `ι` such that the canonical map `A → ⨁ i, 𝒜 i` is bijective and respects multiplication, i.e. the product of an element of degree `i` and an element of degree `j` is an element of degree `i + j`. Note that the fact that `A` is internally-graded, `graded_algebra 𝒜`, implies an externally-graded algebra structure `direct_sum.galgebra R (λ i, ↥(𝒜 i))`, which in turn makes available an `algebra R (⨁ i, 𝒜 i)` instance. -/ class graded_ring (𝒜 : ι → σ) extends set_like.graded_monoid 𝒜, direct_sum.decomposition 𝒜. variables [graded_ring 𝒜] namespace direct_sum /-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as a ring to a direct sum of components. -/ def decompose_ring_equiv : A ≃+* ⨁ i, 𝒜 i := ring_equiv.symm { map_mul' := (coe_ring_hom 𝒜).map_mul, map_add' := (coe_ring_hom 𝒜).map_add, ..(decompose_add_equiv 𝒜).symm } @[simp] lemma decompose_one : decompose 𝒜 (1 : A) = 1 := map_one (decompose_ring_equiv 𝒜) @[simp] lemma decompose_symm_one : (decompose 𝒜).symm 1 = (1 : A) := map_one (decompose_ring_equiv 𝒜).symm @[simp] lemma decompose_mul (x y : A) : decompose 𝒜 (x * y) = decompose 𝒜 x * decompose 𝒜 y := map_mul (decompose_ring_equiv 𝒜) x y @[simp] lemma decompose_symm_mul (x y : ⨁ i, 𝒜 i) : (decompose 𝒜).symm (x * y) = (decompose 𝒜).symm x * (decompose 𝒜).symm y := map_mul (decompose_ring_equiv 𝒜).symm x y end direct_sum /-- The projection maps of a graded ring -/ def graded_ring.proj (i : ι) : A →+ A := (add_submonoid_class.subtype (𝒜 i)).comp $ (dfinsupp.eval_add_monoid_hom i).comp $ ring_hom.to_add_monoid_hom $ ring_equiv.to_ring_hom $ direct_sum.decompose_ring_equiv 𝒜 @[simp] lemma graded_ring.proj_apply (i : ι) (r : A) : graded_ring.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i := rfl lemma graded_ring.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) : graded_ring.proj 𝒜 i ((decompose 𝒜).symm a) = (decompose 𝒜).symm (direct_sum.of _ i (a i)) := by rw [graded_ring.proj_apply, decompose_symm_of, equiv.apply_symm_apply] lemma graded_ring.mem_support_iff [Π i (x : 𝒜 i), decidable (x ≠ 0)] (r : A) (i : ι) : i ∈ (decompose 𝒜 r).support ↔ graded_ring.proj 𝒜 i r ≠ 0 := dfinsupp.mem_support_iff.trans zero_mem_class.coe_eq_zero.not.symm end graded_ring section add_cancel_monoid open direct_sum dfinsupp finset function lemma direct_sum.coe_decompose_mul_add_of_left_mem {ι σ A} [decidable_eq ι] [add_left_cancel_monoid ι] [semiring A] [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] {a b : A} {i j : ι} (a_mem : a ∈ 𝒜 i) : (decompose 𝒜 (a * b) (i + j) : A) = a * decompose 𝒜 b j := begin obtain rfl | ha := eq_or_ne a 0, { simp }, classical, lift a to (𝒜 i) using a_mem, erw [decompose_mul, coe_mul_apply, decompose_coe, support_of _ i a (λ r,by subst r; exact ha rfl), singleton_product, map_filter, sum_map], simp_rw [comp, embedding.coe_fn_mk, add_left_cancel_iff, filter_eq'], refine dite (decompose 𝒜 b j = 0) (λ h, by simp [if_neg (not_mem_support_iff.mpr h), h]) (λ h, _), erw [if_pos (mem_support_iff.mpr h), finset.sum_singleton, of_eq_same], refl, end lemma direct_sum.coe_decompose_mul_add_of_right_mem {ι σ A} [decidable_eq ι] [add_right_cancel_monoid ι] [semiring A] [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] {a b : A} {i j : ι} (b_mem : b ∈ 𝒜 j) : (decompose 𝒜 (a * b) (i + j) : A) = (decompose 𝒜 a i) * b := begin obtain rfl | hb := eq_or_ne b 0, { simp }, classical, lift b to (𝒜 j) using b_mem, erw [decompose_mul, coe_mul_apply, decompose_coe, support_of _ j b (λ r,by subst r; exact hb rfl), product_singleton, map_filter, sum_map], simp_rw [comp, embedding.coe_fn_mk, add_right_cancel_iff, filter_eq'], refine dite (decompose 𝒜 a i = 0) (λ h, by simp [if_neg (not_mem_support_iff.mpr h), h]) (λ h, _), erw [if_pos (mem_support_iff.mpr h), finset.sum_singleton, of_eq_same], refl, end lemma direct_sum.decompose_mul_add_left {ι σ A} [decidable_eq ι] [add_left_cancel_monoid ι] [semiring A] [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] {i j : ι} (a : 𝒜 i) {b : A} : decompose 𝒜 (↑a * b) (i + j) = @graded_monoid.ghas_mul.mul ι (λ i, 𝒜 i) _ _ _ _ a (decompose 𝒜 b j) := subtype.ext $ direct_sum.coe_decompose_mul_add_of_left_mem 𝒜 a.2 lemma direct_sum.decompose_mul_add_right {ι σ A} [decidable_eq ι] [add_right_cancel_monoid ι] [semiring A] [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] {i j : ι} {a : A} (b : 𝒜 j) : decompose 𝒜 (a * ↑b) (i + j) = @graded_monoid.ghas_mul.mul ι (λ i, 𝒜 i) _ _ _ _ (decompose 𝒜 a i) b := subtype.ext $ direct_sum.coe_decompose_mul_add_of_right_mem 𝒜 b.2 end add_cancel_monoid section graded_algebra variables [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] variables (𝒜 : ι → submodule R A) /-- A special case of `graded_ring` with `σ = submodule R A`. This is useful both because it can avoid typeclass search, and because it provides a more concise name. -/ @[reducible] def graded_algebra := graded_ring 𝒜 /-- A helper to construct a `graded_algebra` when the `set_like.graded_monoid` structure is already available. This makes the `left_inv` condition easier to prove, and phrases the `right_inv` condition in a way that allows custom `@[ext]` lemmas to apply. See note [reducible non-instances]. -/ @[reducible] def graded_algebra.of_alg_hom [set_like.graded_monoid 𝒜] (decompose : A →ₐ[R] ⨁ i, 𝒜 i) (right_inv : (direct_sum.coe_alg_hom 𝒜).comp decompose = alg_hom.id R A) (left_inv : ∀ i (x : 𝒜 i), decompose (x : A) = direct_sum.of (λ i, ↥(𝒜 i)) i x) : graded_algebra 𝒜 := { decompose' := decompose, left_inv := alg_hom.congr_fun right_inv, right_inv := begin suffices : decompose.comp (direct_sum.coe_alg_hom 𝒜) = alg_hom.id _ _, from alg_hom.congr_fun this, ext i x : 2, exact (decompose.congr_arg $ direct_sum.coe_alg_hom_of _ _ _).trans (left_inv i x), end} variable [graded_algebra 𝒜] namespace direct_sum /-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as an algebra to a direct sum of components. -/ @[simps] def decompose_alg_equiv : A ≃ₐ[R] ⨁ i, 𝒜 i := alg_equiv.symm { map_mul' := (coe_alg_hom 𝒜).map_mul, map_add' := (coe_alg_hom 𝒜).map_add, commutes' := (coe_alg_hom 𝒜).commutes, ..(decompose_add_equiv 𝒜).symm } end direct_sum open direct_sum /-- The projection maps of graded algebra-/ def graded_algebra.proj (𝒜 : ι → submodule R A) [graded_algebra 𝒜] (i : ι) : A →ₗ[R] A := (𝒜 i).subtype.comp $ (dfinsupp.lapply i).comp $ (decompose_alg_equiv 𝒜).to_alg_hom.to_linear_map @[simp] lemma graded_algebra.proj_apply (i : ι) (r : A) : graded_algebra.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i := rfl lemma graded_algebra.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) : graded_algebra.proj 𝒜 i ((decompose 𝒜).symm a) = (decompose 𝒜).symm (of _ i (a i)) := by rw [graded_algebra.proj_apply, decompose_symm_of, equiv.apply_symm_apply] lemma graded_algebra.mem_support_iff [decidable_eq A] (r : A) (i : ι) : i ∈ (decompose 𝒜 r).support ↔ graded_algebra.proj 𝒜 i r ≠ 0 := dfinsupp.mem_support_iff.trans submodule.coe_eq_zero.not.symm end graded_algebra section canonical_order open graded_ring set_like.graded_monoid direct_sum variables [semiring A] [decidable_eq ι] variables [canonically_ordered_add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] /-- If `A` is graded by a canonically ordered add monoid, then the projection map `x ↦ x₀` is a ring homomorphism. -/ @[simps] def graded_ring.proj_zero_ring_hom : A →+* A := { to_fun := λ a, decompose 𝒜 a 0, map_one' := decompose_of_mem_same 𝒜 one_mem, map_zero' := by { rw decompose_zero, refl }, map_add' := λ _ _, by { rw decompose_add, refl }, map_mul' := begin refine direct_sum.decomposition.induction_on 𝒜 (λ x, _) _ _, { simp only [zero_mul, decompose_zero, zero_apply, zero_mem_class.coe_zero] }, { rintros i ⟨c, hc⟩, refine direct_sum.decomposition.induction_on 𝒜 _ _ _, { simp only [mul_zero, decompose_zero, zero_apply, zero_mem_class.coe_zero] }, { rintros j ⟨c', hc'⟩, { simp only [subtype.coe_mk], by_cases h : i + j = 0, { rw [decompose_of_mem_same 𝒜 (show c * c' ∈ 𝒜 0, from h ▸ mul_mem hc hc'), decompose_of_mem_same 𝒜 (show c ∈ 𝒜 0, from (add_eq_zero_iff.mp h).1 ▸ hc), decompose_of_mem_same 𝒜 (show c' ∈ 𝒜 0, from (add_eq_zero_iff.mp h).2 ▸ hc')] }, { rw [decompose_of_mem_ne 𝒜 (mul_mem hc hc') h], cases (show i ≠ 0 ∨ j ≠ 0, by rwa [add_eq_zero_iff, not_and_distrib] at h) with h' h', { simp only [decompose_of_mem_ne 𝒜 hc h', zero_mul] }, { simp only [decompose_of_mem_ne 𝒜 hc' h', mul_zero] } } }, }, { intros _ _ hd he, simp only [mul_add, decompose_add, add_apply, add_mem_class.coe_add, hd, he] }, }, { rintros _ _ ha hb _, simp only [add_mul, decompose_add, add_apply, add_mem_class.coe_add, ha, hb], }, end } end canonical_order
590f49b8e5f071d0c183b1fff9a2b58447f9d0c0
bae21755a4a03bbe0a5c22e258db8633407711ad
/library/init/meta/interaction_monad.lean
a336b7d658e73cf630caf6dd39739c9814c2c572
[ "Apache-2.0" ]
permissive
nor-code/lean
f437357a8f85db0f06f186fa50fcb1bc75f6b122
aa306af3d7c47de3c7937c98d3aa919eb8da6f34
refs/heads/master
1,662,613,329,886
1,586,696,014,000
1,586,696,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,214
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, Sebastian Ullrich -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.data.to_string universes u v meta inductive interaction_monad.result (state : Type) (α : Type u) | success : α → state → interaction_monad.result | exception : option (unit → format) → option pos → state → interaction_monad.result open interaction_monad.result section variables {state : Type} {α : Type u} variables [has_to_string α] meta def interaction_monad.result_to_string : result state α → string | (success a s) := to_string a | (exception (some t) ref s) := "Exception: " ++ to_string (t ()) | (exception none ref s) := "[silent exception]" meta instance interaction_monad.result_has_string : has_to_string (result state α) := ⟨interaction_monad.result_to_string⟩ end meta def interaction_monad.result.clamp_pos {state : Type} {α : Type u} (line0 line col : ℕ) : result state α → result state α | (success a s) := success a s | (exception msg (some p) s) := exception msg (some $ if p.line < line0 then ⟨line, col⟩ else p) s | (exception msg none s) := exception msg (some ⟨line, col⟩) s @[reducible] meta def interaction_monad (state : Type) (α : Type u) := state → result state α section parameter {state : Type} variables {α : Type u} {β : Type v} local notation `m` := interaction_monad state @[inline] meta def interaction_monad_fmap (f : α → β) (t : m α) : m β := λ s, interaction_monad.result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception e s') @[inline] meta def interaction_monad_bind (t₁ : m α) (t₂ : α → m β) : m β := λ s, interaction_monad.result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception e s') @[inline] meta def interaction_monad_return (a : α) : m α := λ s, success a s meta def interaction_monad_orelse {α : Type u} (t₁ t₂ : m α) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s', interaction_monad.result.cases_on (t₂ s) success exception) @[inline] meta def interaction_monad_seq (t₁ : m α) (t₂ : m β) : m β := interaction_monad_bind t₁ (λ a, t₂) meta instance interaction_monad.monad : monad m := {map := @interaction_monad_fmap, pure := @interaction_monad_return, bind := @interaction_monad_bind} meta def interaction_monad.mk_exception {α : Type u} {β : Type v} [has_to_format β] (msg : β) (ref : option expr) (s : state) : result state α := exception (some (λ _, to_fmt msg)) none s meta def interaction_monad.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : m α := λ s, interaction_monad.mk_exception msg none s meta def interaction_monad.silent_fail {α : Type u} : m α := λ s, exception none none s meta def interaction_monad.failed {α : Type u} : m α := interaction_monad.fail "failed" /- Alternative orelse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orelse` uses the second. -/ meta def interaction_monad.orelse' {α : Type u} (t₁ t₂ : m α) (use_first_ex := tt) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s₁', interaction_monad.result.cases_on (t₂ s) success (λ e₂ ref₂ s₂', if use_first_ex then (exception e₁ ref₁ s₁') else (exception e₂ ref₂ s₂'))) meta instance interaction_monad.monad_fail : monad_fail m := { fail := λ α s, interaction_monad.fail (to_fmt s), ..interaction_monad.monad } -- TODO: unify `parser` and `tactic` behavior? -- meta instance interaction_monad.alternative : alternative m := -- ⟨@interaction_monad_fmap, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed, @interaction_monad_orelse⟩ end
23a9c0ac2ad741269b77e73df3d59554ce589b9b
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/univ_bug1.lean
61e13da32e47d9f0929b2f1a1897f17a484e8848
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,068
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- import logic data.nat open nat namespace simp -- set_option pp.universes true -- set_option pp.implicit true -- first define a class of homogeneous equality inductive simplifies_to [class] {T : Type} (t1 t2 : T) : Prop := mk : t1 = t2 → simplifies_to t1 t2 theorem get_eq {T : Type} {t1 t2 : T} (C : simplifies_to t1 t2) : t1 = t2 := simplifies_to.rec (λx, x) C theorem infer_eq {T : Type} (t1 t2 : T) {C : simplifies_to t1 t2} : t1 = t2 := simplifies_to.rec (λx, x) C theorem simp_app [instance] (S T : Type) (f1 f2 : S → T) (s1 s2 : S) (C1 : simplifies_to f1 f2) (C2 : simplifies_to s1 s2) : simplifies_to (f1 s1) (f2 s2) := simplifies_to.mk (congr (get_eq C1) (get_eq C2)) end simp
4c43e71039dacc3b129ef0a0a663893cb67ea3e4
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Server/Utils.lean
e90bc1d98884cbd195be761a0e2189bd04eb921b
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
4,321
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp import Init.System.FilePath namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs if flushEagerly then b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln if flushEagerly then b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs if flushEagerly then a.flush b.write bs putStr := fun s => do a.putStr s if flushEagerly then a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true /-- Transform the given path to a file:// URI. -/ def toFileUri (fname : String) : Lsp.DocumentUri := let fname := System.FilePath.normalizePath fname let fname := if System.Platform.isWindows then fname.map fun c => if c == '\\' then '/' else c else fname -- TODO(WN): URL-encode special characters -- Three slashes denote localhost. "file:///" ++ fname.dropWhile (· == '/') open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) end Lean.Server namespace List universe u def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => if p hd then hd :: takeWhile p tl else [] end List
b0af9699411a04a8eadaacf0d548af385d3510ee
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/subtype/instances.lean
b5b405f6ab54e3639ca86c31ed01a8450caa6c75
[]
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
907
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.mk_dec_eq_instance import Mathlib.Lean3Lib.init.data.subtype.basic universes u namespace Mathlib protected instance subtype.decidable_eq {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq (Subtype fun (x : α) => p x) := id fun (_v : Subtype fun (x : α) => p x) => subtype.cases_on _v fun (val : α) (property : p val) (w : Subtype fun (x : α) => p x) => subtype.cases_on w fun (w_val : α) (w_property : p w_val) => decidable.by_cases (fun (ᾰ : val = w_val) => Eq._oldrec (fun (w_property : p val) => is_true sorry) ᾰ w_property) fun (ᾰ : ¬val = w_val) => isFalse sorry
1d161d88d602021b7d053ea6dc8752e62d62ea41
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/over.lean
64173a3aa150ebda54d910d1e28ca040e60b414a
[]
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
15,492
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.comma import Mathlib.category_theory.punit import Mathlib.category_theory.reflects_isomorphisms import Mathlib.category_theory.epi_mono import Mathlib.PostPort universes v₁ u₁ v₂ u₂ namespace Mathlib /-! # 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 /-- 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. -/ def over {T : Type u₁} [category T] (X : T) := comma 𝟭 (functor.from_punit X) -- Satisfying the inhabited linter protected instance over.inhabited {T : Type u₁} [category T] [Inhabited T] : Inhabited (over Inhabited.default) := { default := comma.mk 𝟙 } namespace over theorem over_morphism.ext {T : Type u₁} [category T] {X : T} {U : over X} {V : over X} {f : U ⟶ V} {g : U ⟶ V} (h : comma_morphism.left f = comma_morphism.left g) : f = g := sorry @[simp] theorem over_right {T : Type u₁} [category T] {X : T} (U : over X) : comma.right U = PUnit.unit := of_as_true trivial @[simp] theorem id_left {T : Type u₁} [category T] {X : T} (U : over X) : comma_morphism.left 𝟙 = 𝟙 := rfl @[simp] theorem comp_left {T : Type u₁} [category T] {X : T} (a : over X) (b : over X) (c : over X) (f : a ⟶ b) (g : b ⟶ c) : comma_morphism.left (f ≫ g) = comma_morphism.left f ≫ comma_morphism.left g := rfl @[simp] theorem w {T : Type u₁} [category T] {X : T} {A : over X} {B : over X} (f : A ⟶ B) : comma_morphism.left f ≫ comma.hom B = comma.hom A := sorry /-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/ @[simp] theorem mk_left {T : Type u₁} [category T] {X : T} {Y : T} (f : Y ⟶ X) : comma.left (mk f) = Y := Eq.refl (comma.left (mk 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 {T : Type u₁} [category T] {X : T} {Y : T} : has_coe (Y ⟶ X) (over X) := has_coe.mk mk @[simp] theorem coe_hom {T : Type u₁} [category T] {X : T} {Y : T} (f : Y ⟶ X) : comma.hom ↑f = f := rfl /-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative triangle. -/ def hom_mk {T : Type u₁} [category T] {X : T} {U : over X} {V : over X} (f : comma.left U ⟶ comma.left V) (w : autoParam (f ≫ comma.hom V = comma.hom U) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])) : U ⟶ V := comma_morphism.mk /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ @[simp] theorem iso_mk_inv_left {T : Type u₁} [category T] {X : T} {f : over X} {g : over X} (hl : comma.left f ≅ comma.left g) (hw : autoParam (iso.hom hl ≫ comma.hom g = comma.hom f) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])) : comma_morphism.left (iso.inv (iso_mk hl)) = iso.inv hl := Eq.refl (iso.inv hl) /-- The forgetful functor mapping an arrow to its domain. See https://stacks.math.columbia.edu/tag/001G. -/ def forget {T : Type u₁} [category T] (X : T) : over X ⥤ T := comma.fst 𝟭 (functor.from_punit X) @[simp] theorem forget_obj {T : Type u₁} [category T] {X : T} {U : over X} : functor.obj (forget X) U = comma.left U := rfl @[simp] theorem forget_map {T : Type u₁} [category T] {X : T} {U : over X} {V : over X} {f : U ⟶ V} : functor.map (forget X) f = comma_morphism.left f := 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 {T : Type u₁} [category T] {X : T} {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right 𝟭 (discrete.nat_trans fun (_x : discrete PUnit) => f) @[simp] theorem map_obj_left {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : over X} : comma.left (functor.obj (map f) U) = comma.left U := rfl @[simp] theorem map_obj_hom {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : over X} : comma.hom (functor.obj (map f) U) = comma.hom U ≫ f := rfl @[simp] theorem map_map_left {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : over X} {V : over X} {g : U ⟶ V} : comma_morphism.left (functor.map (map f) g) = comma_morphism.left g := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id {T : Type u₁} [category T] {Y : T} : map 𝟙 ≅ 𝟭 := nat_iso.of_components (fun (X : over Y) => iso_mk (iso.refl (comma.left (functor.obj (map 𝟙) X)))) sorry /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {T : Type u₁} [category T] {X : T} {Y : T} {Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g := nat_iso.of_components (fun (X_1 : over X) => iso_mk (iso.refl (comma.left (functor.obj (map (f ≫ g)) X_1)))) sorry protected instance forget_reflects_iso {T : Type u₁} [category T] {X : T} : reflects_isomorphisms (forget X) := reflects_isomorphisms.mk fun (Y Z : over X) (f : Y ⟶ Z) (t : is_iso (functor.map (forget X) f)) => is_iso.mk (hom_mk (inv (functor.map (forget X) f))) protected instance forget_faithful {T : Type u₁} [category T] {X : T} : faithful (forget X) := faithful.mk /-- If `k.left` is an epimorphism, then `k` is an epimorphism. In other words, `over.forget X` reflects epimorphisms. The converse does not hold without additional assumptions on the underlying category. -/ -- TODO: Show the converse holds if `T` has binary products or pushouts. theorem epi_of_epi_left {T : Type u₁} [category T] {X : T} {f : over X} {g : over X} (k : f ⟶ g) [hk : epi (comma_morphism.left k)] : epi k := faithful_reflects_epi (forget X) hk /-- If `k.left` is a monomorphism, then `k` is a monomorphism. In other words, `over.forget X` reflects monomorphisms. The converse of `category_theory.over.mono_left_of_mono`. This lemma is not an instance, to avoid loops in type class inference. -/ theorem mono_of_mono_left {T : Type u₁} [category T] {X : T} {f : over X} {g : over X} (k : f ⟶ g) [hk : mono (comma_morphism.left k)] : mono k := faithful_reflects_mono (forget X) hk /-- If `k` is a monomorphism, then `k.left` is a monomorphism. In other words, `over.forget X` preserves monomorphisms. The converse of `category_theory.over.mono_of_mono_left`. -/ protected instance mono_left_of_mono {T : Type u₁} [category T] {X : T} {f : over X} {g : over X} (k : f ⟶ g) [mono k] : mono (comma_morphism.left k) := mono.mk fun (Y : T) (l m : Y ⟶ comma.left f) (a : l ≫ comma_morphism.left k = m ≫ comma_morphism.left k) => let l' : mk (m ≫ comma.hom f) ⟶ f := hom_mk l; congr_arg comma_morphism.left (eq.mpr (id (Eq._oldrec (Eq.refl (l' = hom_mk m)) (Eq.symm (propext (cancel_mono k))))) (over_morphism.ext a)) /-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/ @[simp] theorem iterated_slice_forward_obj {T : Type u₁} [category T] {X : T} (f : over X) (α : over f) : functor.obj (iterated_slice_forward f) α = mk (comma_morphism.left (comma.hom α)) := Eq.refl (functor.obj (iterated_slice_forward f) α) /-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/ @[simp] theorem iterated_slice_backward_map {T : Type u₁} [category T] {X : T} (f : over X) (g : over (comma.left f)) (h : over (comma.left f)) (α : g ⟶ h) : functor.map (iterated_slice_backward f) α = hom_mk (hom_mk (comma_morphism.left α)) := Eq.refl (functor.map (iterated_slice_backward f) α) /-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/ @[simp] theorem iterated_slice_equiv_counit_iso {T : Type u₁} [category T] {X : T} (f : over X) : equivalence.counit_iso (iterated_slice_equiv f) = nat_iso.of_components (fun (g : over (comma.left f)) => iso_mk (iso.refl (comma.left (functor.obj (iterated_slice_backward f ⋙ iterated_slice_forward f) g)))) (iterated_slice_equiv._proof_5 f) := Eq.refl (equivalence.counit_iso (iterated_slice_equiv f)) theorem iterated_slice_forward_forget {T : Type u₁} [category T] {X : T} (f : over X) : iterated_slice_forward f ⋙ forget (comma.left f) = forget f ⋙ forget X := rfl theorem iterated_slice_backward_forget_forget {T : Type u₁} [category T] {X : T} (f : over X) : iterated_slice_backward f ⋙ forget f ⋙ forget X = forget (comma.left f) := rfl /-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/ @[simp] theorem post_map_right {T : Type u₁} [category T] {X : T} {D : Type u₂} [category D] (F : T ⥤ D) (Y₁ : over X) (Y₂ : over X) (f : Y₁ ⟶ Y₂) : comma_morphism.right (functor.map (post F) f) = id (fun (F : T ⥤ D) (Y₁ Y₂ : over X) (f : Y₁ ⟶ Y₂) => ulift.up (eq.mpr post._proof_1 (plift.up (of_as_true trivial)))) F Y₁ Y₂ f := Eq.refl (comma_morphism.right (functor.map (post F) f)) end over /-- The under category has as objects arrows with domain `X` and as morphisms commutative triangles. -/ def under {T : Type u₁} [category T] (X : T) := comma (functor.from_punit X) 𝟭 -- Satisfying the inhabited linter protected instance under.inhabited {T : Type u₁} [category T] [Inhabited T] : Inhabited (under Inhabited.default) := { default := comma.mk 𝟙 } namespace under theorem under_morphism.ext {T : Type u₁} [category T] {X : T} {U : under X} {V : under X} {f : U ⟶ V} {g : U ⟶ V} (h : comma_morphism.right f = comma_morphism.right g) : f = g := sorry @[simp] theorem under_left {T : Type u₁} [category T] {X : T} (U : under X) : comma.left U = PUnit.unit := of_as_true trivial @[simp] theorem id_right {T : Type u₁} [category T] {X : T} (U : under X) : comma_morphism.right 𝟙 = 𝟙 := rfl @[simp] theorem comp_right {T : Type u₁} [category T] {X : T} (a : under X) (b : under X) (c : under X) (f : a ⟶ b) (g : b ⟶ c) : comma_morphism.right (f ≫ g) = comma_morphism.right f ≫ comma_morphism.right g := rfl @[simp] theorem w {T : Type u₁} [category T] {X : T} {A : under X} {B : under X} (f : A ⟶ B) : comma.hom A ≫ comma_morphism.right f = comma.hom B := sorry /-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/ @[simp] theorem mk_left {T : Type u₁} [category T] {X : T} {Y : T} (f : X ⟶ Y) : comma.left (mk f) = PUnit.unit := Eq.refl (comma.left (mk f)) /-- To give a morphism in the under category, it suffices to give a morphism fitting in a commutative triangle. -/ @[simp] theorem hom_mk_left {T : Type u₁} [category T] {X : T} {U : under X} {V : under X} (f : comma.right U ⟶ comma.right V) (w : autoParam (comma.hom U ≫ f = comma.hom V) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])) : comma_morphism.left (hom_mk f) = id (fun {X : T} {U V : under X} (f : comma.right U ⟶ comma.right V) (w : comma.hom U ≫ f = comma.hom V) => eq.mpr hom_mk._proof_1 (ulift.up (eq.mpr hom_mk._proof_2 (plift.up (of_as_true trivial))))) X U V f w := Eq.refl (comma_morphism.left (hom_mk f)) /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ def iso_mk {T : Type u₁} [category T] {X : T} {f : under X} {g : under X} (hr : comma.right f ≅ comma.right g) (hw : comma.hom f ≫ iso.hom hr = comma.hom g) : f ≅ g := comma.iso_mk (eq_to_iso sorry) hr sorry @[simp] theorem iso_mk_hom_right {T : Type u₁} [category T] {X : T} {f : under X} {g : under X} (hr : comma.right f ≅ comma.right g) (hw : comma.hom f ≫ iso.hom hr = comma.hom g) : comma_morphism.right (iso.hom (iso_mk hr hw)) = iso.hom hr := rfl @[simp] theorem iso_mk_inv_right {T : Type u₁} [category T] {X : T} {f : under X} {g : under X} (hr : comma.right f ≅ comma.right g) (hw : comma.hom f ≫ iso.hom hr = comma.hom g) : comma_morphism.right (iso.inv (iso_mk hr hw)) = iso.inv hr := rfl /-- The forgetful functor mapping an arrow to its domain. -/ def forget {T : Type u₁} [category T] (X : T) : under X ⥤ T := comma.snd (functor.from_punit X) 𝟭 @[simp] theorem forget_obj {T : Type u₁} [category T] {X : T} {U : under X} : functor.obj (forget X) U = comma.right U := rfl @[simp] theorem forget_map {T : Type u₁} [category T] {X : T} {U : under X} {V : under X} {f : U ⟶ V} : functor.map (forget X) f = comma_morphism.right f := rfl /-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/ def map {T : Type u₁} [category T] {X : T} {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left 𝟭 (discrete.nat_trans fun (_x : discrete PUnit) => f) @[simp] theorem map_obj_right {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : under Y} : comma.right (functor.obj (map f) U) = comma.right U := rfl @[simp] theorem map_obj_hom {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : under Y} : comma.hom (functor.obj (map f) U) = f ≫ comma.hom U := rfl @[simp] theorem map_map_right {T : Type u₁} [category T] {X : T} {Y : T} {f : X ⟶ Y} {U : under Y} {V : under Y} {g : U ⟶ V} : comma_morphism.right (functor.map (map f) g) = comma_morphism.right g := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id {T : Type u₁} [category T] {Y : T} : map 𝟙 ≅ 𝟭 := nat_iso.of_components (fun (X : under Y) => iso_mk (iso.refl (comma.right (functor.obj (map 𝟙) X))) sorry) sorry /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {T : Type u₁} [category T] {X : T} {Y : T} {Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := nat_iso.of_components (fun (X_1 : under Z) => iso_mk (iso.refl (comma.right (functor.obj (map (f ≫ g)) X_1))) sorry) sorry /-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/ @[simp] theorem post_map_left {T : Type u₁} [category T] {D : Type u₂} [category D] {X : T} (F : T ⥤ D) (Y₁ : under X) (Y₂ : under X) (f : Y₁ ⟶ Y₂) : comma_morphism.left (functor.map (post F) f) = id (fun {X : T} (F : T ⥤ D) (Y₁ Y₂ : under X) (f : Y₁ ⟶ Y₂) => ulift.up (eq.mpr post._proof_1 (plift.up (of_as_true trivial)))) X F Y₁ Y₂ f := Eq.refl (comma_morphism.left (functor.map (post F) f))
fe9716f4f7fc2087293d35a65efed8bccd4349db
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/one.lean
ab2fc15dab0cc6ca2d40f2b65e96b48b8d1b7791
[ "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
312
lean
inductive {u} one1 : Type (max 1 u) | unit : one1 set_option pp.universes true check one1 inductive {u} one2 : Type (max 1 u) | unit : one2 check one2 section foo universe u2 parameter A : Type u2 inductive {u} wrapper : Type (max 1 u u2) | mk : A → wrapper check wrapper end foo check wrapper
649dd9d60f127db5b20338d079dd10599832089b
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/module/ulift.lean
03be5bfbcb427a81eeb118d3e335cd0724f9d149
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,377
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 linear_algebra.basic import algebra.ring.ulift /-! # `ulift` instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We also provide `ulift.semimodule_equiv : ulift M ≃ₗ[R] M`. -/ namespace ulift universes u v w variable {R : Type u} variable {M : Type v} variable {N : Type w} instance has_scalar [has_scalar R M] : has_scalar (ulift R) M := ⟨λ s x, s.down • x⟩ @[simp] lemma smul_down [has_scalar R M] (s : ulift R) (x : M) : (s • x) = s.down • x := rfl instance has_scalar' [has_scalar R M] : has_scalar R (ulift M) := ⟨λ s x, ⟨s • x.down⟩⟩ @[simp] lemma smul_down' [has_scalar R M] (s : R) (x : ulift M) : (s • x).down = s • x.down := rfl instance is_scalar_tower [has_scalar R M] [has_scalar M N] [has_scalar R N] [is_scalar_tower R M N] : is_scalar_tower (ulift R) M N := ⟨λ x y z, show (x.down • y) • z = x.down • y • z, from smul_assoc _ _ _⟩ instance is_scalar_tower' [has_scalar R M] [has_scalar M N] [has_scalar R N] [is_scalar_tower R M N] : is_scalar_tower R (ulift M) N := ⟨λ x y z, show (x • y.down) • z = x • y.down • z, from smul_assoc _ _ _⟩ instance is_scalar_tower'' [has_scalar R M] [has_scalar M N] [has_scalar R N] [is_scalar_tower R M N] : is_scalar_tower R M (ulift N) := ⟨λ x y z, show up ((x • y) • z.down) = ⟨x • y • z.down⟩, by rw smul_assoc⟩ instance mul_action [monoid R] [mul_action R M] : mul_action (ulift R) M := { smul := (•), mul_smul := λ r s f, by { cases r, cases s, simp [mul_smul], }, one_smul := λ f, by { simp [one_smul], } } instance mul_action' [monoid R] [mul_action R M] : mul_action R (ulift M) := { smul := (•), mul_smul := λ r s f, by { cases f, ext, simp [mul_smul], }, one_smul := λ f, by { ext, simp [one_smul], } } instance distrib_mul_action [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action (ulift R) M := { smul_zero := λ c, by { cases c, simp [smul_zero], }, smul_add := λ c f g, by { cases c, simp [smul_add], }, ..ulift.mul_action } instance distrib_mul_action' [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (ulift M) := { smul_zero := λ c, by { ext, simp [smul_zero], }, smul_add := λ c f g, by { ext, simp [smul_add], }, ..ulift.mul_action' } instance semimodule [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule (ulift R) M := { add_smul := λ c f g, by { cases c, simp [add_smul], }, zero_smul := λ f, by { simp [zero_smul], }, ..ulift.distrib_mul_action } instance semimodule' [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (ulift M) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } /-- The `R`-linear equivalence between `ulift M` and `M`. -/ def semimodule_equiv [semiring R] [add_comm_monoid M] [semimodule R M] : ulift M ≃ₗ[R] M := { to_fun := ulift.down, inv_fun := ulift.up, map_smul' := λ r x, rfl, map_add' := λ x y, rfl, left_inv := by tidy, right_inv := by tidy, } end ulift
d23470767e0629370da07641545198e992110245
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/data/list/qsort.lean
7e434fd7a9513d2a0b0c355985587f34421383ac
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
694
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic namespace list /- TODO(Leo): remove meta as soon as equation compiler has support for well founded recursion. This is based on the minimalist Haskell "quicksort". Remark: this is *not* really quicksort since it doesn't partition the elements in-place -/ meta def qsort {α} (lt : α → α → bool) : list α → list α | [] := [] | (h::t) := let small := filter (λ x, lt h x = ff) t, large := filter (λ x, lt h x = tt) t in qsort small ++ h :: qsort large end list
7fa8bed24f90e0db3759d63acfe0841c085e72c9
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Logic_and_Proof/Chapter4/4.32.lean
bf07c74c038d24a6ca32e8b557977dbc41da42ef
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
325
lean
-- Building Natural Deduction Proofs -- 4.32 Conjunction variables A B: Prop -- We implement and-introduction with and.intro. variable h1: A variable h2: B -- We implement and-elimination rules with and.left and and.right. variable h3: A /\ B example: A := show A, from and.left h3 example: B := show B, from and.right h3
d7543de724fdb984106e58d274f307fd9e2ae65f
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/logic/examples/colog88.lean
469be3e754861c93ab0c598d6550d9be10153b5b
[ "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
2,733
lean
/- Example from "Inductively defined types", from Thierry Coquand and Christine Paulin, COLOG-88. It shows it is inconsistent to allow inductive datatypes such as inductive A : Type := | intro : ((A → Prop) → Prop) → A -/ /- Phi is a positive, but not strictly positive, operator. -/ definition Phi (A : Type) := (A → Prop) → Prop /- If we were allowed to form the inductive type inductive A: Type := | introA : Phi A -> A we would get the following -/ universe l -- The new type A axiom A : Type.{l} -- The constructor axiom introA : Phi A → A -- The eliminator axiom recA : Π {C : A → Type}, (Π (p : Phi A), C (introA p)) → (Π (a : A), C a) -- The "computational rule" axiom recA_comp : Π {C : A → Type} (H : Π (p : Phi A), C (introA p)) (p : Phi A), recA H (introA p) = H p -- The recursor could be used to define matchA noncomputable definition matchA (a : A) : Phi A := recA (λ p, p) a -- and the computation rule would allows us to define lemma betaA (p : Phi A) : matchA (introA p) = p := !recA_comp -- As in all inductive datatypes, we would be able to prove that constructors are injective. lemma introA_injective : ∀ {p p' : Phi A}, introA p = introA p' → p = p' := λ p p' h, have aux : matchA (introA p) = matchA (introA p'), by rewrite h, by rewrite [*betaA at aux]; exact aux -- For any type T, there is an injection from T to (T → Prop) definition i {T : Type} : T → (T → Prop) := λ x y, x = y lemma i_injective {T : Type} {a b : T} : i a = i b → a = b := λ h, have e₁ : i a a = i b a, by rewrite [h], have e₂ : (a = a) = (b = a), from e₁, have e₃ : b = a, from eq.subst e₂ rfl, eq.symm e₃ -- Hence, by composition, we get an injection f from (A → Prop) to A noncomputable definition f : (A → Prop) → A := λ p, introA (i p) lemma f_injective : ∀ {p p' : A → Prop}, f p = f p' → p = p':= λ (p p' : A → Prop) (h : introA (i p) = introA (i p')), i_injective (introA_injective h) /- We are now back to the usual Cantor-Russel paradox. We can define -/ noncomputable definition P0 (a : A) : Prop := ∃ (P : A → Prop), f P = a ∧ ¬ P a -- i.e., P0 a := codes a set P such that x∉P noncomputable definition x0 : A := f P0 lemma fP0_eq : f P0 = x0 := rfl lemma not_P0_x0 : ¬ P0 x0 := λ h : P0 x0, obtain (P : A → Prop) (hp : f P = x0 ∧ ¬ P x0), from h, have fp_eq : f P = f P0, from and.elim_left hp, have p_eq : P = P0, from f_injective fp_eq, have nh : ¬ P0 x0, by rewrite [p_eq at hp]; exact (and.elim_right hp), absurd h nh lemma P0_x0 : P0 x0 := exists.intro P0 (and.intro fP0_eq not_P0_x0) theorem inconsistent : false := absurd P0_x0 not_P0_x0
27e7d96571f5fb1b82126e229b22770e7cf8b5b0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/category/ulift.lean
f9ee205cd05037de8b03e5ee1faf1d83879ae198
[ "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
5,899
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.category.basic import category_theory.equivalence import category_theory.eq_to_hom /-! # Basic API for ulift This file contains a very basic API for working with the categorical instance on `ulift C` where `C` is a type with a category instance. 1. `category_theory.ulift.up` is the functorial version of the usual `ulift.up`. 2. `category_theory.ulift.down` is the functorial version of the usual `ulift.down`. 3. `category_theory.ulift.equivalence` is the categorical equivalence between `C` and `ulift C`. # ulift_hom Given a type `C : Type u`, `ulift_hom.{w} C` is just an alias for `C`. If we have `category.{v} C`, then `ulift_hom.{w} C` is endowed with a category instance whose morphisms are obtained by applying `ulift.{w}` to the morphisms from `C`. This is a category equivalent to `C`. The forward direction of the equivalence is `ulift_hom.up`, the backward direction is `ulift_hom.donw` and the equivalence is `ulift_hom.equiv`. # as_small This file also contains a construction which takes a type `C : Type u` with a category instance `category.{v} C` and makes a small category `as_small.{w} C : Type (max w v u)` equivalent to `C`. The forward direction of the equivalence, `C ⥤ as_small C`, is denoted `as_small.up` and the backward direction is `as_small.down`. The equivalence itself is `as_small.equiv`. -/ universes w₁ v₁ v₂ u₁ u₂ namespace category_theory variables {C : Type u₁} [category.{v₁} C] /-- The functorial version of `ulift.up`. -/ @[simps] def ulift.up_functor : C ⥤ (ulift.{u₂} C) := { obj := ulift.up, map := λ X Y f, f } /-- The functorial version of `ulift.down`. -/ @[simps] def ulift.down_functor : (ulift.{u₂} C) ⥤ C := { obj := ulift.down, map := λ X Y f, f } /-- The categorical equivalence between `C` and `ulift C`. -/ @[simps] def ulift.equivalence : C ≌ (ulift.{u₂} C) := { functor := ulift.up_functor, inverse := ulift.down_functor, unit_iso := { hom := 𝟙 _, inv := 𝟙 _ }, counit_iso := { hom := { app := λ X, 𝟙 _, naturality' := λ X Y f, by {change f ≫ 𝟙 _ = 𝟙 _ ≫ f, simp} }, inv := { app := λ X, 𝟙 _, naturality' := λ X Y f, by {change f ≫ 𝟙 _ = 𝟙 _ ≫ f, simp} }, hom_inv_id' := by {ext, change (𝟙 _) ≫ (𝟙 _) = 𝟙 _, simp}, inv_hom_id' := by {ext, change (𝟙 _) ≫ (𝟙 _) = 𝟙 _, simp} }, functor_unit_iso_comp' := λ X, by {change (𝟙 X) ≫ (𝟙 X) = 𝟙 X, simp} } section ulift_hom /-- `ulift_hom.{w} C` is an alias for `C`, which is endowed with a category instance whose morphisms are obtained by applying `ulift.{w}` to the morphisms from `C`. -/ def {w u} ulift_hom (C : Type u) := C instance {C} [inhabited C] : inhabited (ulift_hom C) := ⟨(arbitrary C : C)⟩ /-- The obvious function `ulift_hom C → C`. -/ def ulift_hom.obj_down {C} (A : ulift_hom C) : C := A /-- The obvious function `C → ulift_hom C`. -/ def ulift_hom.obj_up {C} (A : C) : ulift_hom C := A @[simp] lemma obj_down_obj_up {C} (A : C) : (ulift_hom.obj_up A).obj_down = A := rfl @[simp] lemma obj_up_obj_down {C} (A : ulift_hom C) : ulift_hom.obj_up A.obj_down = A := rfl instance : category.{max v₂ v₁} (ulift_hom.{v₂} C) := { hom := λ A B, ulift.{v₂} $ A.obj_down ⟶ B.obj_down, id := λ A, ⟨𝟙 _⟩, comp := λ A B C f g, ⟨f.down ≫ g.down⟩} /-- One half of the quivalence between `C` and `ulift_hom C`. -/ @[simps] def ulift_hom.up : C ⥤ ulift_hom C := { obj := ulift_hom.obj_up, map := λ X Y f, ⟨f⟩ } /-- One half of the quivalence between `C` and `ulift_hom C`. -/ @[simps] def ulift_hom.down : ulift_hom C ⥤ C := { obj := ulift_hom.obj_down, map := λ X Y f, f.down } /-- The equivalence between `C` and `ulift_hom C`. -/ def ulift_hom.equiv : C ≌ ulift_hom C := { functor := ulift_hom.up, inverse := ulift_hom.down, unit_iso := nat_iso.of_components (λ A, eq_to_iso rfl) (by tidy), counit_iso := nat_iso.of_components (λ A, eq_to_iso rfl) (by tidy) } end ulift_hom /-- `as_small C` is a small category equivalent to `C`. More specifically, if `C : Type u` is endowed with `category.{v} C`, then `as_small.{w} C : Type (max w v u)` is endowed with an instance of a small category. The objects and morphisms of `as_small C` are defined by applying `ulift` to the objects and morphisms of `C`. Note: We require a category instance for this definition in order to have direct access to the universe level `v`. -/ @[nolint unused_arguments] def {w v u} as_small (C : Type u) [category.{v} C] := ulift.{max w v} C instance : small_category (as_small.{w₁} C) := { hom := λ X Y, ulift.{max w₁ u₁} $ X.down ⟶ Y.down, id := λ X, ⟨𝟙 _⟩, comp := λ X Y Z f g, ⟨f.down ≫ g.down⟩ } /-- One half of the equivalence between `C` and `as_small C`. -/ @[simps] def as_small.up : C ⥤ as_small C := { obj := λ X, ⟨X⟩, map := λ X Y f, ⟨f⟩ } /-- One half of the equivalence between `C` and `as_small C`. -/ @[simps] def as_small.down : as_small C ⥤ C := { obj := λ X, X.down, map := λ X Y f, f.down } /-- The equivalence between `C` and `as_small C`. -/ @[simps] def as_small.equiv : C ≌ as_small C := { functor := as_small.up, inverse := as_small.down, unit_iso := nat_iso.of_components (λ X, eq_to_iso rfl) (by tidy), counit_iso := nat_iso.of_components (λ X, eq_to_iso $ by { ext, refl }) (by tidy) } instance [inhabited C] : inhabited (as_small C) := ⟨⟨arbitrary _⟩⟩ /-- The equivalence between `C` and `ulift_hom (ulift C)`. -/ def {v' u' v u} ulift_hom_ulift_category.equiv (C : Type u) [category.{v} C] : C ≌ ulift_hom.{v'} (ulift.{u'} C) := ulift.equivalence.trans ulift_hom.equiv end category_theory
6c6712d9c359de841a5dcbd84cf2b82d5ae76630
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simp_constructor.lean
281d6ff35c85b2df5a6e416a128625535e2fc225
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,154
lean
inductive term | var : string → term | app : string → list term → term example (h : term.var "a" = term.app "f" []) : false := begin simp at h, exact false.elim h end example : ¬ term.var "a" = term.app "f" [] := by simp universes u inductive vec (α : Type u) : nat → Type u | nil : vec 0 | cons : Π {n}, α → vec n → vec (nat.succ n) #check @vec.cons.inj_eq example (a b : nat) (h : a == b) : a + 1 = b + 1 := begin subst h end mutual inductive Expr, Expr_list with Expr : Type | var : string → Expr | app : string → Expr_list → Expr with Expr_list : Type | nil : Expr_list | cons : Expr → Expr_list → Expr_list #check @Expr.app.inj_eq example {α : Type u} (n : nat) (a₁ a₂ : α) (t : vec α n) (h : vec.cons a₁ t = vec.cons a₂ t) : a₁ = a₂ := begin simp at h, exact h end example (a₁ a₂ : nat) (h₁ : a₁ > 0) (h₂ : a₂ > 0) (h : a₁ = a₂) : subtype.mk a₁ h₁ = subtype.mk a₂ h₂ := begin simp, exact h end example (a₁ a₂ : nat) (h₁ : a₁ > 0) (h₂ : a₂ > 0) (h : subtype.mk a₁ h₁ = subtype.mk a₂ h₂) : a₁ = a₂ := begin simp at h, exact h end
fbfe6da3db3e715d9d4bc74df2af809501342fb4
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/05_Interacting_with_Lean.org.15.lean
c2ac010dc5a9c0c797306700382eea31da010e8f
[]
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
152
lean
/- page 72 -/ import standard import data.nat data.int open nat int variables a b : int variables m n : nat check a + b check m + n print notation +
173957fe856d29ffaed553ce881ea3747d32581b
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/system_of_complexes/double.lean
c37f70f65343a81803c34cc955e36aa47b5d48ad
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,519
lean
import algebra.homology.chain_complex import hacks_and_tricks.by_exactI_hack import system_of_complexes.basic import normed_group.NormedGroup import facts universe variables v u noncomputable theory open opposite category_theory open_locale nnreal /-! # Systems of double complexes of normed abelian groups In this file we define systems of double complexes of normed abelian groups, as needed for Definition 9.6 of [Analytic]. ## Main declarations * `system_of_double_complexes`: a system of complexes of normed abelian groups. * `admissible`: such a system is *admissible* if all maps that occur in the system are norm-nonincreasing. -/ /-- A system of double complexes of normed abelian groups, indexed by `ℝ≥0`. See also Definition 9.3 of [Analytic]. Implementation detail: `cochain_complex` assumes that the complex is indexed by `ℤ`, whereas we are interested in complexes indexed by `ℕ`. We therefore set all objects indexed by negative integers to `0`, in our use case. -/ @[derive category_theory.category] def system_of_double_complexes : Type (u+1) := ℝ≥0ᵒᵖ ⥤ (cochain_complex (cochain_complex NormedGroup.{u})) namespace system_of_double_complexes variables (C : system_of_double_complexes) /-- `C.X c p q` is the object $C_c^{p,q}$ in a system of double complexes `C`. -/ def X (c : ℝ≥0) (p q : ℤ) : NormedGroup := ((C.obj $ op c).X p).X q /-- `C.res` is the restriction map `C.X c' p q ⟶ C.X c p q` for a system of complexes `C`, and nonnegative reals `c ≤ c'`. -/ def res {c' c : ℝ≥0} {p q : ℤ} [h : fact (c ≤ c')] : C.X c' p q ⟶ C.X c p q := ((C.map (hom_of_le h).op).f p).f q variables (c : ℝ≥0) {c₁ c₂ c₃ : ℝ≥0} (p q : ℤ) @[simp] lemma res_refl : @res C c c p q _ = 𝟙 _ := begin have := (category_theory.functor.map_id C (op $ c)), delta res, erw this, refl end @[simp] lemma res_comp_res (h₁ : fact (c₂ ≤ c₁)) (h₂ : fact (c₃ ≤ c₂)) : @res C _ _ p q h₁ ≫ @res C _ _ p q h₂ = @res C _ _ p q (le_trans h₂ h₁) := begin have := (category_theory.functor.map_comp C (hom_of_le h₁).op (hom_of_le h₂).op), rw [← op_comp] at this, delta res, erw this, refl, end @[simp] lemma res_res (h₁ : fact (c₂ ≤ c₁)) (h₂ : fact (c₃ ≤ c₂)) (x : C.X c₁ p q) : @res C _ _ p q h₂ (@res C _ _ p q h₁ x) = @res C _ _ p q (le_trans h₂ h₁) x := by { rw ← (C.res_comp_res p q h₁ h₂), refl } /-- `C.d` is the differential `C.X c p q ⟶ C.X c (p+1) q` for a system of double complexes `C`. -/ def d {c : ℝ≥0} {p q : ℤ} : C.X c p q ⟶ C.X c (p+1) q := ((C.obj $ op c).d p).f q lemma d_comp_res (h : fact (c₂ ≤ c₁)) : @d C c₁ p q ≫ @res C _ _ _ _ h = @res C _ _ p q _ ≫ @d C c₂ p q := begin have step1 := (homological_complex.comm_at (C.map (hom_of_le h).op) p), have step2 := congr_arg differential_object.hom.f step1, exact congr_fun step2 q end lemma d_res (h : fact (c₂ ≤ c₁)) (x) : @d C c₂ p q (@res C _ _ p q _ x) = @res C _ _ _ _ h (@d C c₁ p q x) := show (@res C _ _ p q _ ≫ @d C c₂ p q) x = (@d C c₁ p q ≫ @res C _ _ _ _ h) x, by rw d_comp_res @[simp] lemma d_comp_d {c : ℝ≥0} {p q : ℤ} : @d C c p q ≫ C.d = 0 := begin have step1 := (homological_complex.d_squared (C.obj $ op c)) p, have step2 := congr_arg differential_object.hom.f step1, exact congr_fun step2 q end @[simp] lemma d_d {c : ℝ≥0} {p q : ℤ} (x : C.X c p q) : C.d (C.d x) = 0 := show (@d C c _ _ ≫ C.d) x = 0, by { rw d_comp_d, refl } /-- `C.d'` is the differential `C.X c p q ⟶ C.X c p (q+1)` for a system of double complexes `C`. -/ def d' {c : ℝ≥0} {p q : ℤ} : C.X c p q ⟶ C.X c p (q+1) := ((C.obj $ op c).X p).d q lemma d'_comp_res (h : fact (c₂ ≤ c₁)) : @d' C c₁ p q ≫ @res C _ _ _ _ h = @res C _ _ p q _ ≫ @d' C c₂ p q := homological_complex.comm_at ((C.map (hom_of_le h).op).f p) q lemma d'_res (h : fact (c₂ ≤ c₁)) (x) : @d' C c₂ p q (@res C _ _ p q _ x) = @res C _ _ _ _ h (@d' C c₁ p q x) := show (@res C _ _ p q _ ≫ @d' C c₂ p q) x = (@d' C c₁ p q ≫ @res C _ _ _ _ h) x, by rw d'_comp_res @[simp] lemma d'_comp_d' {c : ℝ≥0} {p q : ℤ} : @d' C c p q ≫ C.d' = 0 := ((C.obj $ op c).X p).d_squared q @[simp] lemma d'_d' {c : ℝ≥0} {p q : ℤ} (x : C.X c p q) : C.d' (C.d' x) = 0 := show (@d' C c _ _ ≫ C.d') x = 0, by { rw d'_comp_d', refl } /-- Convenience definition: The identity morphism of an object in the system of double complexes when it is given by different indices that are not definitionally equal. -/ def congr {c c' : ℝ≥0} {p p' q q' : ℤ} (hc : c = c') (hp : p = p') (hq : q = q') : C.X c p q ⟶ C.X c' p' q' := eq_to_hom $ by { subst hc, subst hp, subst hq, } /-- A system of double complexes is *admissible* if all the differentials and restriction maps are norm-nonincreasing. See Definition 9.3 of [Analytic]. -/ structure admissible (C : system_of_double_complexes) : Prop := (d_norm_noninc : ∀ c p q (x : C.X c p q), ∥C.d x∥ ≤ ∥x∥) (d'_norm_noninc : ∀ c p q (x : C.X c p q), ∥C.d' x∥ ≤ ∥x∥) (res_norm_noninc : ∀ c' c p q h (x : C.X c' p q), ∥@res C c' c p q h x∥ ≤ ∥x∥) attribute [simps] differential_object.forget /-- The `p`-th row in a system of double complexes, as system of complexes. It has object `(C.obj c).X p`over `c`. -/ def row (C : system_of_double_complexes) (p : ℤ) : system_of_complexes := C.comp ((homological_complex.forget _).comp $ pi.eval _ p) @[simp] lemma row_X (C : system_of_double_complexes) (p q : ℤ) (c : ℝ≥0) : C.row p c q = C.X c p q := by refl @[simp] lemma row_res (C : system_of_double_complexes) (p q : ℤ) {c' c : ℝ≥0} [h : fact (c ≤ c')] : @system_of_complexes.res (C.row p) _ _ q h = @res C _ _ p q h := by refl @[simp] lemma row_d (C : system_of_double_complexes) (p q : ℤ) (c : ℝ≥0) : @system_of_complexes.d (C.row p) _ _ = @d' C c p q := by refl /-- The `q`-th column in a system of double complexes, as system of complexes. -/ def col (C : system_of_double_complexes) (q : ℤ) : system_of_complexes := C.comp (functor.map_differential_object _ (functor.pi $ λ n, (homological_complex.forget _).comp $ pi.eval _ q) { app := λ X, 𝟙 _, naturality' := by { intros, ext, simp } } (by { intros, ext, simp })) @[simp] lemma col_X (C : system_of_double_complexes) (p q : ℤ) (c : ℝ≥0) : C.col q c p = C.X c p q := by refl @[simp] lemma col_res (C : system_of_double_complexes) (p q : ℤ) {c' c : ℝ≥0} [h : fact (c ≤ c')] : @system_of_complexes.res (C.col q) _ _ _ _ = @res C _ _ p q h := by refl @[simp] lemma col_d (C : system_of_double_complexes) (p q : ℤ) (c : ℝ≥0) : @system_of_complexes.d (C.col q) _ _ = @d C c p q := by { dsimp [system_of_complexes.d, col, d], simp } /-- The assumptions on `M` in Proposition 9.6 bundled into a structure. Note that in `cond3b` our `q` is one smaller than the `q` in the notes (so that we don't have to deal with `q - 1`). -/ structure normed_spectral_conditions (m : ℕ) (k K : ℝ≥0) [fact (1 ≤ k)] (ε : ℝ) (hε : 0 < ε) (k₀ : ℝ≥0) [fact (1 ≤ k₀)] (M : system_of_double_complexes) (k' : ℝ≥0) [fact (k₀ ≤ k')] [fact (1 ≤ k')] (c₀ H : ℝ≥0) [fact (0 < H)] := (col_exact : ∀ j ≤ m, (M.col j).is_bounded_exact k K (m+1) c₀) (row_exact : ∀ i ≤ m + 1, (M.row i).is_bounded_exact k K m c₀) (h : Π {q : ℤ} [fact (q ≤ m)] {c} [fact (c₀ ≤ c)], M.X (k' * c) 0 (q+1) ⟶ M.X c 1 q) (norm_h_le : ∀ (q : ℤ) [fact (q ≤ m)] (c) [fact (c₀ ≤ c)] (x : M.X (k' * c) 0 (q+1)), ​∥h x∥ ≤ H * ∥x∥) (cond3b : ∀ (q : ℤ) [fact (q+1 ≤ m)] (c) [fact (c₀ ≤ c)] (x : M.X (k' * (k' * c)) 0 (q+1)) (u1 u2 : units ℤ), ​∥M.res (M.d x) + (u1:ℤ) • h (M.d' x) + (u2:ℤ) • M.d' (h x)∥ ≤ ε * ∥(res M x : M.X c 0 (q+1))∥) . namespace normed_spectral_conditions variables (m : ℕ) (k K : ℝ≥0) [fact (1 ≤ k)] variables (ε : ℝ) (hε : 0 < ε) (k₀ : ℝ≥0) [fact (1 ≤ k₀)] variables (M : system_of_double_complexes.{u}) variables (k' : ℝ≥0) [fact (k₀ ≤ k')] [fact (1 ≤ k')] (c₀ H : ℝ≥0) [fact (0 < H)] lemma cond3bpp (NSC : normed_spectral_conditions.{u u} m k K ε hε k₀ M k' c₀ H) (q : ℤ) [fact (q + 1 ≤ m)] (c : ℝ≥0) [fact (c₀ ≤ c)] (x : M.X (k' * (k' * c)) 0 (q+1)) : ​∥M.res (M.d x) + NSC.h (M.d' x) + M.d' (NSC.h x)∥ ≤ ε * ∥(res M x : M.X c 0 (q+1))∥ := by simpa only [units.coe_one, one_smul] using NSC.cond3b q c x 1 1 lemma cond3bpm (NSC : normed_spectral_conditions.{u u} m k K ε hε k₀ M k' c₀ H) (q : ℤ) [fact (q + 1 ≤ m)] (c : ℝ≥0) [fact (c₀ ≤ c)] (x : M.X (k' * (k' * c)) 0 (q+1)) : ​∥M.res (M.d x) + NSC.h (M.d' x) - M.d' (NSC.h x)∥ ≤ ε * ∥(res M x : M.X c 0 (q+1))∥ := by simpa only [units.coe_one, one_smul, neg_smul, units.coe_neg, ← sub_eq_add_neg] using NSC.cond3b q c x 1 (-1) lemma cond3bmp (NSC : normed_spectral_conditions.{u u} m k K ε hε k₀ M k' c₀ H) (q : ℤ) [fact (q + 1 ≤ m)] (c : ℝ≥0) [fact (c₀ ≤ c)] (x : M.X (k' * (k' * c)) 0 (q+1)) : ​∥M.res (M.d x) - NSC.h (M.d' x) + M.d' (NSC.h x)∥ ≤ ε * ∥(res M x : M.X c 0 (q+1))∥ := by simpa only [units.coe_one, one_smul, neg_smul, units.coe_neg, ← sub_eq_add_neg] using NSC.cond3b q c x (-1) 1 lemma cond3bmm (NSC : normed_spectral_conditions.{u u} m k K ε hε k₀ M k' c₀ H) (q : ℤ) [fact (q + 1 ≤ m)] (c : ℝ≥0) [fact (c₀ ≤ c)] (x : M.X (k' * (k' * c)) 0 (q+1)) : ​∥M.res (M.d x) - NSC.h (M.d' x) - M.d' (NSC.h x)∥ ≤ ε * ∥(res M x : M.X c 0 (q+1))∥ := by simpa only [units.coe_one, one_smul, neg_smul, units.coe_neg, ← sub_eq_add_neg] using NSC.cond3b q c x (-1) (-1) end normed_spectral_conditions /-- Proposition 9.6 in [Analytic] Constants (max (k' * k') (2 * k₀ * H)) and K in the statement are not the right ones. We need to investigate the consequences of the k Zeeman effect here. -/ theorem analytic_9_6 (m : ℕ) (k K : ℝ≥0) [fact (1 ≤ k)] : ∃ (ε : ℝ) (hε : ε > 0) (k₀ : ℝ≥0) [fact (1 ≤ k₀)], ∀ (M : system_of_double_complexes) (k' : ℝ≥0) [fact (k₀ ≤ k')] [fact (1 ≤ k')] -- follows (c₀ H : ℝ≥0) [fact (0 < H)], ​∀ (cond : normed_spectral_conditions m k K ε hε k₀ M k' c₀ H), (M.row 0).is_bounded_exact (max (k' * k') (2 * k₀ * H)) K (m+1) c₀ := begin sorry end end system_of_double_complexes
42f2c894e0ebb426bc158bac1154d291864b1f56
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Std/Data/DList.lean
8b2537fcfd89d9b7c0b8804b29ec5034a0e3ae76
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
1,727
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universes u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) where apply : List α → List α invariant : ∀ l, apply l = apply [] ++ l namespace DList variable {α : Type u} open List def ofList (l : List α) : DList α := ⟨(l ++ ·), fun t => by simp⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := { apply := fun t => a :: t, invariant := fun t => rfl } def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t, invariant := by intro t; simp; rw [h] } def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g, invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← append_assoc (f []) (g []) t, ← h₁ (g [])] } def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t), invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), append_assoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ end DList end Std
805b142e800f91afe008aa47d30dfcfad2cc2e1e
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/metric/edit_distance/default.lean
7edb81556e007b824fad131cc9604b3248e428ea
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
1,546
lean
import tactic.rewrite_search.core import tactic.rewrite_search.module import .core import .cm import .svm open tactic.rewrite_search open tactic.rewrite_search.bound_progress namespace tactic.rewrite_search.metric open tactic.rewrite_search.edit_distance open tactic.rewrite_search.metric.edit_distance meta def weight.none : ed_weight_constructor := λ α δ, ⟨init_result.pure (), λ g, return table.create⟩ -- TODO I'm ugly meta def edit_distance_cnst (conf : iconfig.result) (n : option name) := λ α δ, let w := match n with | some `cm := weight.cm | some `svm := weight.svm | _ := weight.none end in @metric.mk α ed_state ed_partial δ (ed_decode conf (w α δ).init) (ed_update (w α δ).calc_weights) ed_init_bound ed_improve_estimate_over meta def edit_distance (conf : iconfig.result := iconfig.empty_result) (weight : option name := none) : tactic expr := generic_args ``tactic.rewrite_search.metric.edit_distance_cnst [`(conf), `(weight)] section iconfig_mk edit_distance iconfig_add_struct edit_distance tactic.rewrite_search.metric.edit_distance.ed_config meta def edit_distance_cfg (_ : name) (cfg : iconfig edit_distance) (w : interactive.parse (optional lean.parser.ident)) : cfgtactic unit := do cfg ← iconfig.read cfg, e ← tactic.to_expr $ ``(edit_distance) (pexpr.of_expr `(cfg)) (pexpr.of_expr `(w)), iconfig.publish `metric $ cfgopt.value.pexpr $ pexpr.of_expr e iconfig_add rewrite_search [ metric.edit_distance : custom edit_distance_cfg ] end end tactic.rewrite_search.metric
46b6b3314a93ed53637f003848367c91dc14249b
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/instances/sphere.lean
5b25152ceaa64c583a465d3a8b773edcc3b2710a
[ "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
20,041
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.complex.circle import analysis.inner_product_space.calculus import analysis.inner_product_space.pi_L2 import geometry.manifold.algebra.lie_group import geometry.manifold.instances.real /-! # Manifold structure on the sphere This file defines stereographic projection from the sphere in an inner product space `E`, and uses it to put a smooth manifold structure on the sphere. ## Main results For a unit vector `v` in `E`, the definition `stereographic` gives the stereographic projection centred at `v`, a local homeomorphism from the sphere to `(ℝ ∙ v)ᗮ` (the orthogonal complement of `v`). For finite-dimensional `E`, we then construct a smooth manifold instance on the sphere; the charts here are obtained by composing the local homeomorphisms `stereographic` with arbitrary isometries from `(ℝ ∙ v)ᗮ` to Euclidean space. We prove two lemmas about smooth maps: * `cont_mdiff_coe_sphere` states that the coercion map from the sphere into `E` is smooth; this is a useful tool for constructing smooth maps *from* the sphere. * `cont_mdiff.cod_restrict_sphere` states that a map from a manifold into the sphere is smooth if its lift to a map to `E` is smooth; this is a useful tool for constructing smooth maps *to* the sphere. As an application we prove `cont_mdiff_neg_sphere`, that the antipodal map is smooth. Finally, we equip the `circle` (defined in `analysis.complex.circle` to be the sphere in `ℂ` centred at `0` of radius `1`) with the following structure: * a charted space with model space `euclidean_space ℝ (fin 1)` (inherited from `metric.sphere`) * a Lie group with model with corners `𝓡 1` We furthermore show that `exp_map_circle` (defined in `analysis.complex.circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`) is smooth. ## Implementation notes The model space for the charted space instance is `euclidean_space ℝ (fin n)`, where `n` is a natural number satisfying the typeclass assumption `[fact (finrank ℝ E = n + 1)]`. This may seem a little awkward, but it is designed to circumvent the problem that the literal expression for the dimension of the model space (up to definitional equality) determines the type. If one used the naive expression `euclidean_space ℝ (fin (finrank ℝ E - 1))` for the model space, then the sphere in `ℂ` would be a manifold with model space `euclidean_space ℝ (fin (2 - 1))` but not with model space `euclidean_space ℝ (fin 1)`. -/ variables {E : Type*} [inner_product_space ℝ E] noncomputable theory open metric finite_dimensional open_locale manifold local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ section stereographic_projection variables (v : E) /-! ### Construction of the stereographic projection -/ /-- Stereographic projection, forward direction. This is a map from an inner product space `E` to the orthogonal complement of an element `v` of `E`. It is smooth away from the affine hyperplane through `v` parallel to the orthogonal complement. It restricts on the sphere to the stereographic projection. -/ def stereo_to_fun [complete_space E] (x : E) : (ℝ ∙ v)ᗮ := (2 / ((1:ℝ) - innerSL v x)) • orthogonal_projection (ℝ ∙ v)ᗮ x variables {v} @[simp] lemma stereo_to_fun_apply [complete_space E] (x : E) : stereo_to_fun v x = (2 / ((1:ℝ) - innerSL v x)) • orthogonal_projection (ℝ ∙ v)ᗮ x := rfl lemma cont_diff_on_stereo_to_fun [complete_space E] : cont_diff_on ℝ ⊤ (stereo_to_fun v) {x : E | innerSL v x ≠ (1:ℝ)} := begin refine cont_diff_on.smul _ (orthogonal_projection ((ℝ ∙ v)ᗮ)).cont_diff.cont_diff_on, refine cont_diff_const.cont_diff_on.div _ _, { exact (cont_diff_const.sub (innerSL v).cont_diff).cont_diff_on }, { intros x h h', exact h (sub_eq_zero.mp h').symm } end lemma continuous_on_stereo_to_fun [complete_space E] : continuous_on (stereo_to_fun v) {x : E | innerSL v x ≠ (1:ℝ)} := cont_diff_on_stereo_to_fun.continuous_on variables (v) /-- Auxiliary function for the construction of the reverse direction of the stereographic projection. This is a map from the orthogonal complement of a unit vector `v` in an inner product space `E` to `E`; we will later prove that it takes values in the unit sphere. For most purposes, use `stereo_inv_fun`, not `stereo_inv_fun_aux`. -/ def stereo_inv_fun_aux (w : E) : E := (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) variables {v} @[simp] lemma stereo_inv_fun_aux_apply (w : E) : stereo_inv_fun_aux v w = (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) := rfl lemma stereo_inv_fun_aux_mem (hv : ∥v∥ = 1) {w : E} (hw : w ∈ (ℝ ∙ v)ᗮ) : stereo_inv_fun_aux v w ∈ (sphere (0:E) 1) := begin have h₁ : 0 ≤ ∥w∥ ^ 2 + 4 := by nlinarith, suffices : ∥(4:ℝ) • w + (∥w∥ ^ 2 - 4) • v∥ = ∥w∥ ^ 2 + 4, { have h₂ : ∥w∥ ^ 2 + 4 ≠ 0 := by nlinarith, simp only [mem_sphere_zero_iff_norm, norm_smul, real.norm_eq_abs, abs_inv, this, abs_of_nonneg h₁, stereo_inv_fun_aux_apply], field_simp }, suffices : ∥(4:ℝ) • w + (∥w∥ ^ 2 - 4) • v∥ ^ 2 = (∥w∥ ^ 2 + 4) ^ 2, { have h₃ : 0 ≤ ∥stereo_inv_fun_aux v w∥ := norm_nonneg _, simpa [h₁, h₃, -one_pow] using this }, simp [norm_add_sq_real, norm_smul, inner_smul_left, inner_smul_right, inner_left_of_mem_orthogonal_singleton _ hw, mul_pow, real.norm_eq_abs, hv], ring end lemma cont_diff_stereo_inv_fun_aux : cont_diff ℝ ⊤ (stereo_inv_fun_aux v) := begin have h₀ : cont_diff ℝ ⊤ (λ w : E, ∥w∥ ^ 2) := cont_diff_norm_sq, have h₁ : cont_diff ℝ ⊤ (λ w : E, (∥w∥ ^ 2 + 4)⁻¹), { refine (h₀.add cont_diff_const).inv _, intros x, nlinarith }, have h₂ : cont_diff ℝ ⊤ (λ w, (4:ℝ) • w + (∥w∥ ^ 2 - 4) • v), { refine (cont_diff_const.smul cont_diff_id).add _, refine (h₀.sub cont_diff_const).smul cont_diff_const }, exact h₁.smul h₂ end /-- Stereographic projection, reverse direction. This is a map from the orthogonal complement of a unit vector `v` in an inner product space `E` to the unit sphere in `E`. -/ def stereo_inv_fun (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : sphere (0:E) 1 := ⟨stereo_inv_fun_aux v (w:E), stereo_inv_fun_aux_mem hv w.2⟩ @[simp] lemma stereo_inv_fun_apply (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : (stereo_inv_fun hv w : E) = (∥w∥ ^ 2 + 4)⁻¹ • ((4:ℝ) • w + (∥w∥ ^ 2 - 4) • v) := rfl lemma stereo_inv_fun_ne_north_pole (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : stereo_inv_fun hv w ≠ (⟨v, by simp [hv]⟩ : sphere (0:E) 1) := begin refine subtype.ne_of_val_ne _, rw ← inner_lt_one_iff_real_of_norm_one _ hv, { have hw : ⟪v, w⟫_ℝ = 0 := inner_right_of_mem_orthogonal_singleton v w.2, have hw' : (∥(w:E)∥ ^ 2 + 4)⁻¹ * (∥(w:E)∥ ^ 2 - 4) < 1, { refine (inv_mul_lt_iff' _).mpr _, { nlinarith }, linarith }, simpa [real_inner_comm, inner_add_right, inner_smul_right, real_inner_self_eq_norm_mul_norm, hw, hv] using hw' }, { simpa using stereo_inv_fun_aux_mem hv w.2 } end lemma continuous_stereo_inv_fun (hv : ∥v∥ = 1) : continuous (stereo_inv_fun hv) := continuous_induced_rng (cont_diff_stereo_inv_fun_aux.continuous.comp continuous_subtype_coe) variables [complete_space E] lemma stereo_left_inv (hv : ∥v∥ = 1) {x : sphere (0:E) 1} (hx : (x:E) ≠ v) : stereo_inv_fun hv (stereo_to_fun v x) = x := begin ext, simp only [stereo_to_fun_apply, stereo_inv_fun_apply, smul_add], -- name two frequently-occuring quantities and write down their basic properties set a : ℝ := innerSL v x, set y := orthogonal_projection (ℝ ∙ v)ᗮ x, have split : ↑x = a • v + ↑y, { convert eq_sum_orthogonal_projection_self_orthogonal_complement (ℝ ∙ v) x, exact (orthogonal_projection_unit_singleton ℝ hv x).symm }, have hvy : ⟪v, y⟫_ℝ = 0 := inner_right_of_mem_orthogonal_singleton v y.2, have pythag : 1 = a ^ 2 + ∥y∥ ^ 2, { have hvy' : ⟪a • v, y⟫_ℝ = 0 := by simp [inner_smul_left, hvy], convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero _ _ hvy' using 2, { simp [← split] }, { simp [norm_smul, hv, real.norm_eq_abs, ← sq, sq_abs] }, { exact sq _ } }, -- two facts which will be helpful for clearing denominators in the main calculation have ha : 1 - a ≠ 0, { have : a < 1 := (inner_lt_one_iff_real_of_norm_one hv (by simp)).mpr hx.symm, linarith }, have : 2 ^ 2 * ∥y∥ ^ 2 + 4 * (1 - a) ^ 2 ≠ 0, { refine ne_of_gt _, have := norm_nonneg (y:E), have : 0 < (1 - a) ^ 2 := sq_pos_of_ne_zero (1 - a) ha, nlinarith }, -- the core of the problem is these two algebraic identities: have h₁ : (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 + 4)⁻¹ * 4 * (2 / (1 - a)) = 1, { field_simp, simp only [submodule.coe_norm] at *, nlinarith }, have h₂ : (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 + 4)⁻¹ * (2 ^ 2 / (1 - a) ^ 2 * ∥y∥ ^ 2 - 4) = a, { field_simp, transitivity (1 - a) ^ 2 * (a * (2 ^ 2 * ∥y∥ ^ 2 + 4 * (1 - a) ^ 2)), { congr, simp only [submodule.coe_norm] at *, nlinarith }, ring }, -- deduce the result convert congr_arg2 has_add.add (congr_arg (λ t, t • (y:E)) h₁) (congr_arg (λ t, t • v) h₂) using 1, { simp [inner_add_right, inner_smul_right, hvy, real_inner_self_eq_norm_mul_norm, hv, mul_smul, mul_pow, real.norm_eq_abs, sq_abs, norm_smul] }, { simp [split, add_comm] } end lemma stereo_right_inv (hv : ∥v∥ = 1) (w : (ℝ ∙ v)ᗮ) : stereo_to_fun v (stereo_inv_fun hv w) = w := begin have : 2 / (1 - (∥(w:E)∥ ^ 2 + 4)⁻¹ * (∥(w:E)∥ ^ 2 - 4)) * (∥(w:E)∥ ^ 2 + 4)⁻¹ * 4 = 1, { have : ∥(w:E)∥ ^ 2 + 4 ≠ 0 := by nlinarith, have : (4:ℝ) + 4 ≠ 0 := by nlinarith, field_simp, ring }, convert congr_arg (λ c, c • w) this, { have h₁ : orthogonal_projection (ℝ ∙ v)ᗮ v = 0 := orthogonal_projection_orthogonal_complement_singleton_eq_zero v, have h₂ : orthogonal_projection (ℝ ∙ v)ᗮ w = w := orthogonal_projection_mem_subspace_eq_self w, have h₃ : innerSL v w = (0:ℝ) := inner_right_of_mem_orthogonal_singleton v w.2, have h₄ : innerSL v v = (1:ℝ) := by simp [real_inner_self_eq_norm_mul_norm, hv], simp [h₁, h₂, h₃, h₄, continuous_linear_map.map_add, continuous_linear_map.map_smul, mul_smul] }, { simp } end /-- Stereographic projection from the unit sphere in `E`, centred at a unit vector `v` in `E`; this is the version as a local homeomorphism. -/ def stereographic (hv : ∥v∥ = 1) : local_homeomorph (sphere (0:E) 1) (ℝ ∙ v)ᗮ := { to_fun := (stereo_to_fun v) ∘ coe, inv_fun := stereo_inv_fun hv, source := {⟨v, by simp [hv]⟩}ᶜ, target := set.univ, map_source' := by simp, map_target' := λ w _, stereo_inv_fun_ne_north_pole hv w, left_inv' := λ _ hx, stereo_left_inv hv (λ h, hx (subtype.ext h)), right_inv' := λ w _, stereo_right_inv hv w, open_source := is_open_compl_singleton, open_target := is_open_univ, continuous_to_fun := continuous_on_stereo_to_fun.comp continuous_subtype_coe.continuous_on (λ w h, h ∘ subtype.ext ∘ eq.symm ∘ (inner_eq_norm_mul_iff_of_norm_one hv (by simp)).mp), continuous_inv_fun := (continuous_stereo_inv_fun hv).continuous_on } @[simp] lemma stereographic_source (hv : ∥v∥ = 1) : (stereographic hv).source = {⟨v, by simp [hv]⟩}ᶜ := rfl @[simp] lemma stereographic_target (hv : ∥v∥ = 1) : (stereographic hv).target = set.univ := rfl end stereographic_projection section charted_space /-! ### Charted space structure on the sphere In this section we construct a charted space structure on the unit sphere in a finite-dimensional real inner product space `E`; that is, we show that it is locally homeomorphic to the Euclidean space of dimension one less than `E`. The restriction to finite dimension is for convenience. The most natural `charted_space` structure for the sphere uses the stereographic projection from the antipodes of a point as the canonical chart at this point. However, the codomain of the stereographic projection constructed in the previous section is `(ℝ ∙ v)ᗮ`, the orthogonal complement of the vector `v` in `E` which is the "north pole" of the projection, so a priori these charts all have different codomains. So it is necessary to prove that these codomains are all continuously linearly equivalent to a fixed normed space. This could be proved in general by a simple case of Gram-Schmidt orthogonalization, but in the finite-dimensional case it follows more easily by dimension-counting. -/ /-- Variant of the stereographic projection, for the sphere in an `n + 1`-dimensional inner product space `E`. This version has codomain the Euclidean space of dimension `n`, and is obtained by composing the original sterographic projection (`stereographic`) with an arbitrary linear isometry from `(ℝ ∙ v)ᗮ` to the Euclidean space. -/ def stereographic' (n : ℕ) [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : local_homeomorph (sphere (0:E) 1) (euclidean_space ℝ (fin n)) := (stereographic (norm_eq_of_mem_sphere v)) ≫ₕ (linear_isometry_equiv.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v)).to_homeomorph.to_local_homeomorph @[simp] lemma stereographic'_source {n : ℕ} [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : (stereographic' n v).source = {v}ᶜ := by simp [stereographic'] @[simp] lemma stereographic'_target {n : ℕ} [fact (finrank ℝ E = n + 1)] (v : sphere (0:E) 1) : (stereographic' n v).target = set.univ := by simp [stereographic'] /-- The unit sphere in an `n + 1`-dimensional inner product space `E` is a charted space modelled on the Euclidean space of dimension `n`. -/ instance {n : ℕ} [fact (finrank ℝ E = n + 1)] : charted_space (euclidean_space ℝ (fin n)) (sphere (0:E) 1) := { atlas := {f | ∃ v : (sphere (0:E) 1), f = stereographic' n v}, chart_at := λ v, stereographic' n (-v), mem_chart_source := λ v, by simpa using ne_neg_of_mem_unit_sphere ℝ v, chart_mem_atlas := λ v, ⟨-v, rfl⟩ } end charted_space section smooth_manifold /-! ### Smooth manifold structure on the sphere -/ /-- The unit sphere in an `n + 1`-dimensional inner product space `E` is a smooth manifold, modelled on the Euclidean space of dimension `n`. -/ instance {n : ℕ} [fact (finrank ℝ E = n + 1)] : smooth_manifold_with_corners (𝓡 n) (sphere (0:E) 1) := smooth_manifold_with_corners_of_cont_diff_on (𝓡 n) (sphere (0:E) 1) begin rintros _ _ ⟨v, rfl⟩ ⟨v', rfl⟩, let U : (ℝ ∙ (v:E))ᗮ ≃ₗᵢ[ℝ] euclidean_space ℝ (fin n) := linear_isometry_equiv.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v), let U' : (ℝ ∙ (v':E))ᗮ ≃ₗᵢ[ℝ] euclidean_space ℝ (fin n) := linear_isometry_equiv.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere v'), have hUv : stereographic' n v = (stereographic (norm_eq_of_mem_sphere v)) ≫ₕ U.to_homeomorph.to_local_homeomorph := rfl, have hU'v' : stereographic' n v' = (stereographic (norm_eq_of_mem_sphere v')).trans U'.to_homeomorph.to_local_homeomorph := rfl, have H₁ := U'.cont_diff.comp_cont_diff_on cont_diff_on_stereo_to_fun, have H₂ := (cont_diff_stereo_inv_fun_aux.comp (ℝ ∙ (v:E))ᗮ.subtypeL.cont_diff).comp U.symm.cont_diff, convert H₁.comp' (H₂.cont_diff_on : cont_diff_on ℝ ⊤ _ set.univ) using 1, have h_set : ∀ p : sphere (0:E) 1, p = v' ↔ ⟪(p:E), v'⟫_ℝ = 1, { simp [subtype.ext_iff, inner_eq_norm_mul_iff_of_norm_one] }, ext, simp [h_set, hUv, hU'v', stereographic, real_inner_comm, ← submodule.coe_norm] end /-- The inclusion map (i.e., `coe`) from the sphere in `E` to `E` is smooth. -/ lemma cont_mdiff_coe_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] : cont_mdiff (𝓡 n) 𝓘(ℝ, E) ∞ (coe : (sphere (0:E) 1) → E) := begin rw cont_mdiff_iff, split, { exact continuous_subtype_coe }, { intros v _, let U : (ℝ ∙ ((-v):E))ᗮ ≃ₗᵢ[ℝ] euclidean_space ℝ (fin n) := linear_isometry_equiv.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere (-v)), exact ((cont_diff_stereo_inv_fun_aux.comp (ℝ ∙ ((-v):E))ᗮ.subtypeL.cont_diff).comp U.symm.cont_diff).cont_diff_on } end variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {H : Type*} [topological_space H] {I : model_with_corners ℝ F H} variables {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-- If a `cont_mdiff` function `f : M → E`, where `M` is some manifold, takes values in the sphere, then it restricts to a `cont_mdiff` function from `M` to the sphere. -/ lemma cont_mdiff.cod_restrict_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] {m : with_top ℕ} {f : M → E} (hf : cont_mdiff I 𝓘(ℝ, E) m f) (hf' : ∀ x, f x ∈ sphere (0:E) 1) : cont_mdiff I (𝓡 n) m (set.cod_restrict _ _ hf' : M → (sphere (0:E) 1)) := begin rw cont_mdiff_iff_target, refine ⟨continuous_induced_rng hf.continuous, _⟩, intros v, let U : (ℝ ∙ ((-v):E))ᗮ ≃ₗᵢ[ℝ] euclidean_space ℝ (fin n) := (linear_isometry_equiv.from_orthogonal_span_singleton n (ne_zero_of_mem_unit_sphere (-v))), have h : cont_diff_on ℝ ⊤ U set.univ := U.cont_diff.cont_diff_on, have H₁ := (h.comp' cont_diff_on_stereo_to_fun).cont_mdiff_on, have H₂ : cont_mdiff_on _ _ _ _ set.univ := hf.cont_mdiff_on, convert (H₁.of_le le_top).comp' H₂ using 1, ext x, have hfxv : f x = -↑v ↔ ⟪f x, -↑v⟫_ℝ = 1, { have hfx : ∥f x∥ = 1 := by simpa using hf' x, rw inner_eq_norm_mul_iff_of_norm_one hfx, exact norm_eq_of_mem_sphere (-v) }, dsimp [chart_at], simp [not_iff_not, subtype.ext_iff, hfxv, real_inner_comm] end /-- The antipodal map is smooth. -/ lemma cont_mdiff_neg_sphere {n : ℕ} [fact (finrank ℝ E = n + 1)] : cont_mdiff (𝓡 n) (𝓡 n) ∞ (λ x : sphere (0:E) 1, -x) := begin -- this doesn't elaborate well in term mode apply cont_mdiff.cod_restrict_sphere, apply cont_diff_neg.cont_mdiff.comp _, exact cont_mdiff_coe_sphere, end end smooth_manifold section circle open complex local attribute [instance] finrank_real_complex_fact /-- The unit circle in `ℂ` is a charted space modelled on `euclidean_space ℝ (fin 1)`. This follows by definition from the corresponding result for `metric.sphere`. -/ instance : charted_space (euclidean_space ℝ (fin 1)) circle := metric.sphere.charted_space instance : smooth_manifold_with_corners (𝓡 1) circle := metric.sphere.smooth_manifold_with_corners /-- The unit circle in `ℂ` is a Lie group. -/ instance : lie_group (𝓡 1) circle := { smooth_mul := begin apply cont_mdiff.cod_restrict_sphere, let c : circle → ℂ := coe, have h₂ : cont_mdiff (𝓘(ℝ, ℂ).prod 𝓘(ℝ, ℂ)) 𝓘(ℝ, ℂ) ∞ (λ (z : ℂ × ℂ), z.fst * z.snd), { rw cont_mdiff_iff, exact ⟨continuous_mul, λ x y, (cont_diff_mul.restrict_scalars ℝ).cont_diff_on⟩ }, suffices h₁ : cont_mdiff _ _ _ (prod.map c c), { apply h₂.comp h₁ }, -- this elaborates much faster with `apply` apply cont_mdiff.prod_map; exact cont_mdiff_coe_sphere, end, smooth_inv := begin apply cont_mdiff.cod_restrict_sphere, exact complex.conj_cle.cont_diff.cont_mdiff.comp cont_mdiff_coe_sphere end } /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ` is smooth. -/ lemma cont_mdiff_exp_map_circle : cont_mdiff 𝓘(ℝ, ℝ) (𝓡 1) ∞ exp_map_circle := (((cont_diff_exp.restrict_scalars ℝ).comp (cont_diff_id.smul cont_diff_const)).cont_mdiff).cod_restrict_sphere _ end circle
32aebc5b21d52b3c699a0a3db65155aedf5be0b9
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Meta/Tactic/Intro.lean
96970e9f183474538553e1be169eb39d629ed942
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,413
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.Meta.Tactic.Util namespace Lean namespace Meta @[specialize] partial def introNCoreAux {σ} (mvarId : MVarId) (mkName : LocalContext → Name → σ → Name × σ) : Nat → LocalContext → Array Expr → Nat → σ → Expr → MetaM (Array Expr × MVarId) | 0, lctx, fvars, j, _, type => let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewLocalInstances fvars j $ do tag ← getMVarTag mvarId; let type := type.headBeta; newMVar ← mkFreshExprSyntheticOpaqueMVar type tag; lctx ← getLCtx; newVal ← mkLambdaFVars fvars newMVar; assignExprMVar mvarId newVal; pure $ (fvars, newMVar.mvarId!) | (i+1), lctx, fvars, j, s, Expr.letE n type val body _ => do let type := type.instantiateRevRange j fvars.size fvars; let type := type.headBeta; let val := val.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let (n, s) := mkName lctx n s; let lctx := lctx.mkLetDecl fvarId n type val; let fvar := mkFVar fvarId; let fvars := fvars.push fvar; introNCoreAux i lctx fvars j s body | (i+1), lctx, fvars, j, s, Expr.forallE n type body c => do let type := type.instantiateRevRange j fvars.size fvars; let type := type.headBeta; fvarId ← mkFreshId; let (n, s) := mkName lctx n s; let lctx := lctx.mkLocalDecl fvarId n type c.binderInfo; let fvar := mkFVar fvarId; let fvars := fvars.push fvar; introNCoreAux i lctx fvars j s body | (i+1), lctx, fvars, j, s, type => let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewLocalInstances fvars j $ do newType ← whnf type; if newType.isForall then introNCoreAux (i+1) lctx fvars fvars.size s newType else throwTacticEx `introN mvarId "insufficient number of binders" @[specialize] def introNCore {σ} (mvarId : MVarId) (n : Nat) (mkName : LocalContext → Name → σ → Name × σ) (s : σ) : MetaM (Array FVarId × MVarId) := withMVarContext mvarId $ do checkNotAssigned mvarId `introN; mvarType ← getMVarType mvarId; lctx ← getLCtx; (fvars, mvarId) ← introNCoreAux mvarId mkName n lctx #[] 0 s mvarType; pure (fvars.map Expr.fvarId!, mvarId) def mkAuxName (useUnusedNames : Bool) (lctx : LocalContext) (defaultName : Name) : List Name → Name × List Name | [] => (if useUnusedNames then lctx.getUnusedName defaultName else defaultName, []) | n :: rest => (if n != "_" then n else if useUnusedNames then lctx.getUnusedName defaultName else defaultName, rest) def introN (mvarId : MVarId) (n : Nat) (givenNames : List Name := []) (useUnusedNames := true) : MetaM (Array FVarId × MVarId) := if n == 0 then pure (#[], mvarId) else introNCore mvarId n (mkAuxName useUnusedNames) givenNames def intro (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do (fvarIds, mvarId) ← introN mvarId 1 [name]; pure (fvarIds.get! 0, mvarId) def intro1 (mvarId : MVarId) (useUnusedNames := true) : MetaM (FVarId × MVarId) := do (fvarIds, mvarId) ← introN mvarId 1 [] useUnusedNames; pure (fvarIds.get! 0, mvarId) end Meta end Lean
0055f6f87a1b19af2781af42cc7fc798a3859b1a
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/cc_lemmas.lean
845e250cb98a0f6167d7d70301f6c5b67fe5a844
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
4,657
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.propext init.classical /- Lemmas use by the congruence closure module -/ lemma iff_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ↔ b) = b := h.symm ▸ propext (true_iff _) lemma iff_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ↔ b) = a := h.symm ▸ propext (iff_true _) lemma iff_eq_true_of_eq {a b : Prop} (h : a = b) : (a ↔ b) = true := h ▸ propext (iff_self _) lemma and_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∧ b) = b := h.symm ▸ propext (true_and _) lemma and_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∧ b) = a := h.symm ▸ propext (and_true _) lemma and_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∧ b) = false := h.symm ▸ propext (false_and _) lemma and_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∧ b) = false := h.symm ▸ propext (and_false _) lemma and_eq_of_eq {a b : Prop} (h : a = b) : (a ∧ b) = a := h ▸ propext (and_self _) lemma or_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∨ b) = true := h.symm ▸ propext (true_or _) lemma or_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∨ b) = true := h.symm ▸ propext (or_true _) lemma or_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∨ b) = b := h.symm ▸ propext (false_or _) lemma or_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∨ b) = a := h.symm ▸ propext (or_false _) lemma or_eq_of_eq {a b : Prop} (h : a = b) : (a ∨ b) = a := h ▸ propext (or_self _) lemma imp_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a → b) = b := h.symm ▸ propext (iff.intro (λ h, h trivial) (λ h₁ h₂, h₁)) lemma imp_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a → b) = true := h.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, h₁)) lemma imp_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a → b) = true := h.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, false.elim h₂)) lemma imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a → b) = not a := h.symm ▸ propext (iff.intro (λ h, h) (λ hna ha, hna ha)) /- Remark: the congruence closure module will only use the following lemma is cc_config.em is tt. -/ lemma not_imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (not a → b) = a := h.symm ▸ propext (iff.intro (λ h', classical.by_contradiction (λ hna, h' hna)) (λ ha hna, hna ha)) lemma imp_eq_true_of_eq {a b : Prop} (h : a = b) : (a → b) = true := h ▸ propext (iff.intro (λ h, trivial) (λ h ha, ha)) lemma not_eq_of_eq_true {a : Prop} (h : a = true) : (not a) = false := h.symm ▸ propext not_true_iff lemma not_eq_of_eq_false {a : Prop} (h : a = false) : (not a) = true := h.symm ▸ propext not_false_iff lemma false_of_a_eq_not_a {a : Prop} (h : a = not a) : false := have not a, from λ ha, absurd ha (eq.mp h ha), absurd (eq.mpr h this) this universes u lemma if_eq_of_eq_true {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = true) : (@ite c d α t e) = t := if_pos (of_eq_true h) lemma if_eq_of_eq_false {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = false) : (@ite c d α t e) = e := if_neg (not_of_eq_false h) lemma if_eq_of_eq (c : Prop) [d : decidable c] {α : Sort u} {t e : α} (h : t = e) : (@ite c d α t e) = t := match d with | (is_true hc) := rfl | (is_false hnc) := eq.symm h end lemma eq_true_of_and_eq_true_left {a b : Prop} (h : (a ∧ b) = true) : a = true := eq_true_intro (and.left (of_eq_true h)) lemma eq_true_of_and_eq_true_right {a b : Prop} (h : (a ∧ b) = true) : b = true := eq_true_intro (and.right (of_eq_true h)) lemma eq_false_of_or_eq_false_left {a b : Prop} (h : (a ∨ b) = false) : a = false := eq_false_intro (λ ha, false.elim (eq.mp h (or.inl ha))) lemma eq_false_of_or_eq_false_right {a b : Prop} (h : (a ∨ b) = false) : b = false := eq_false_intro (λ hb, false.elim (eq.mp h (or.inr hb))) lemma eq_false_of_not_eq_true {a : Prop} (h : (not a) = true) : a = false := eq_false_intro (λ ha, absurd ha (eq.mpr h trivial)) /- Remark: the congruence closure module will only use the following lemma is cc_config.em is tt. -/ lemma eq_true_of_not_eq_false {a : Prop} (h : (not a) = false) : a = true := eq_true_intro (classical.by_contradiction (λ hna, eq.mp h hna)) lemma ne_of_eq_of_ne {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b ≠ c) : a ≠ c := h₁.symm ▸ h₂ lemma ne_of_ne_of_eq {α : Sort u} {a b c : α} (h₁ : a ≠ b) (h₂ : b = c) : a ≠ c := h₂ ▸ h₁
9240ee74922dc73a49db866f633190d30a1b3c4a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/copy.lean
e33bf8c203dc64a1ea028f76026df28dcda13fad
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,552
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 order.conditionally_complete_lattice.basic /-! # Tooling to make copies of lattice structures Sometimes it is useful to make a copy of a lattice structure where one replaces the data parts with provably equal definitions that have better definitional properties. -/ open order universe u variables {α : Type u} /-- A function to create a provable equal copy of a bounded order with possibly different definitional equalities. -/ def bounded_order.copy {h : has_le α} {h' : has_le α} (c : @bounded_order α h') (top : α) (eq_top : top = @bounded_order.top α _ c) (bot : α) (eq_bot : bot = @bounded_order.bot α _ c) (le_eq : ∀ (x y : α), ((@has_le.le α h) x y) ↔ x ≤ y) : @bounded_order α h := begin refine { top := top, bot := bot, .. }, all_goals { abstract { subst_vars, casesI c, simp_rw le_eq, assumption } } end /-- A function to create a provable equal copy of a lattice with possibly different definitional equalities. -/ def lattice.copy (c : lattice α) (le : α → α → Prop) (eq_le : le = @lattice.le α c) (sup : α → α → α) (eq_sup : sup = @lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @lattice.inf α c) : lattice α := begin refine { le := le, sup := sup, inf := inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a distributive lattice with possibly different definitional equalities. -/ def distrib_lattice.copy (c : distrib_lattice α) (le : α → α → Prop) (eq_le : le = @distrib_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @distrib_lattice.inf α c) : distrib_lattice α := begin refine { le := le, sup := sup, inf := inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a complete lattice with possibly different definitional equalities. -/ def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. lattice.copy (@complete_lattice.to_lattice α c) le eq_le sup eq_sup inf eq_inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a frame with possibly different definitional equalities. -/ def frame.copy (c : frame α) (le : α → α → Prop) (eq_le : le = @frame.le α c) (top : α) (eq_top : top = @frame.top α c) (bot : α) (eq_bot : bot = @frame.bot α c) (sup : α → α → α) (eq_sup : sup = @frame.sup α c) (inf : α → α → α) (eq_inf : inf = @frame.inf α c) (Sup : set α → α) (eq_Sup : Sup = @frame.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @frame.Inf α c) : frame α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. complete_lattice.copy (@frame.to_complete_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a coframe with possibly different definitional equalities. -/ def coframe.copy (c : coframe α) (le : α → α → Prop) (eq_le : le = @coframe.le α c) (top : α) (eq_top : top = @coframe.top α c) (bot : α) (eq_bot : bot = @coframe.bot α c) (sup : α → α → α) (eq_sup : sup = @coframe.sup α c) (inf : α → α → α) (eq_inf : inf = @coframe.inf α c) (Sup : set α → α) (eq_Sup : Sup = @coframe.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @coframe.Inf α c) : coframe α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. complete_lattice.copy (@coframe.to_complete_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. }, all_goals { abstract { subst_vars, casesI c, assumption } } end /-- A function to create a provable equal copy of a complete distributive lattice with possibly different definitional equalities. -/ def complete_distrib_lattice.copy (c : complete_distrib_lattice α) (le : α → α → Prop) (eq_le : le = @complete_distrib_lattice.le α c) (top : α) (eq_top : top = @complete_distrib_lattice.top α c) (bot : α) (eq_bot : bot = @complete_distrib_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_distrib_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_distrib_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_distrib_lattice.Inf α c) : complete_distrib_lattice α := { .. frame.copy (@complete_distrib_lattice.to_frame α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. coframe.copy (@complete_distrib_lattice.to_coframe α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf} /-- A function to create a provable equal copy of a conditionally complete lattice with possibly different definitional equalities. -/ def conditionally_complete_lattice.copy (c : conditionally_complete_lattice α) (le : α → α → Prop) (eq_le : le = @conditionally_complete_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @conditionally_complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @conditionally_complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @conditionally_complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @conditionally_complete_lattice.Inf α c) : conditionally_complete_lattice α := begin refine { le := le, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}, all_goals { abstract { subst_vars, casesI c, assumption } } end
d82dbf7c83acb74c3b6b5c5341d5d87810271bb8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/has_limits.lean
fa70d008c6d82eeae5d56577c0ccb26e0745e4e5
[ "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
39,091
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.limits.is_limit /-! # Existence of limits and colimits In `category_theory.limits.is_limit` we defined `is_limit c`, the data showing that a cone `c` is a limit cone. The two main structures defined in this file are: * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits -- morphism levels before object levels. See note [category_theory universes]. universes v u u' u'' w variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F . tactic.apply_instance) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits : Prop := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] : (limit.cone F).π.app = limit.π _ := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := limit.lift_π _ j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w @[simp] lemma limit.lift_map {F G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) : limit.lift F c ≫ lim_map α = limit.lift G ((cones.postcompose α).obj c) := by { ext, rw [assoc, lim_map_π, limit.lift_π_assoc, limit.lift_π], refl } @[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := (limit.is_limit _).lift_self /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _ @[simp, reassoc] lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) : limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom = limit.lift G ((cones.postcompose w.hom).obj _) := is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _ /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp, reassoc] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp, reassoc] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] section /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) -- We generate this manually since `simps` gives it a weird name. @[simp] lemma lim_map_eq_lim_map : lim.map α = lim_map α := rfl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by { ext, simp } lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) := begin ext, simp only [whisker_right_app, lim_map_π, assoc, limit.post_π_assoc, limit.post_π, ← H.map_comp], end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F . tactic.apply_instance) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits : Prop := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := colimit.ι_desc _ j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w @[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) := (colimit.is_colimit _).desc_self /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _ @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) : (has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t = colimit.desc F ((cocones.precompose w.hom).obj _) := is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _ /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit section opposite /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op := { desc := λ s, (P.lift s.unop).op, fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op := { lift := λ s, (P.desc s.unop).op, fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop := { desc := λ s, (P.lift s.op).unop, fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop := { lift := λ s, (P.desc s.op).unop, fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op := equiv_of_subsingleton_of_subsingleton is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy))) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op := equiv_of_subsingleton_of_subsingleton is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy))) end opposite end category_theory.limits
b7f926e13fa12b48dbd78d660aff7d3af06bdd1f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/free_monoid.lean
988ec4181db1a919f3dbf486de0d2f8e0b1dac88
[ "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
4,901
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import data.equiv.basic import data.list.basic import algebra.star.basic /-! # Free monoid over a given alphabet ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance : monoid (free_monoid α) := { one := [], mul := λ x y, (x ++ y : list α), mul_one := by intros; apply list.append_nil, one_mul := by intros; refl, mul_assoc := by intros; apply list.append_assoc } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[to_additive] lemma one_def : (1 : free_monoid α) = [] := rfl @[to_additive] lemma mul_def (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := [x] @[to_additive] lemma of_def (x : α) : of x = [x] := rfl @[to_additive] lemma of_injective : function.injective (@of α) := λ a b, list.head_eq_of_cons_eq /-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_monoid` using `0` and `of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih @[ext, to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, (l.map f).prod, rfl, λ l₁ l₂, by simp only [mul_def, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, funext $ λ x, one_mul (f x), right_inv := λ f, hom_eq $ λ x, one_mul (f (of x)) } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.map f).prod := rfl @[to_additive] lemma lift_comp_of (f : α → M) : (lift f) ∘ of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := congr_fun (lift_comp_of f) x @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f @[to_additive] lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } @[to_additive] lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl instance : star_monoid (free_monoid α) := { star := list.reverse, star_involutive := list.reverse_reverse, star_mul := list.reverse_append, } @[simp] lemma star_of (x : α) : star (of x) = of x := rfl /-- Note that `star_one` is already a global simp lemma, but this one works with dsimp too -/ @[simp] lemma star_one : star (1 : free_monoid α) = 1 := rfl end free_monoid
25ffb8f4256604b8cdd3189223a8be0656c6fffe
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/hints/thursday/afternoon/category_theory/exercise10/hint.lean
26a485957ae3a7a575e1800896bdb9a3acbc542d
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,595
lean
import category_theory.limits.shapes.zero import category_theory.full_subcategory import algebra.homology.chain_complex import data.int.basic /-! Here's a partial solution. It provides most of the data, but doesn't check required properties. It starts becoming rough going at about this point, when you start proving properties of `long_map`. -/ open category_theory open category_theory.limits namespace exercise variables (C : Type) [category.{0} C] [has_zero_morphisms C] @[derive category] def complex : Type := { F : ℤ ⥤ C // ∀ i : ℤ, F.map (by tidy : i ⟶ i+2) = 0 } def functor : complex C ⥤ cochain_complex C := { obj := λ P, { X := P.1.obj, d := λ i, P.1.map (by tidy : i ⟶ i+1), d_squared' := sorry, }, map := λ P Q α, { f := λ i, α.app i, comm' := sorry, } } def long_map (P : cochain_complex C) (i j : ℤ) : P.X i ⟶ P.X j := if h₀ : j = i then eq_to_hom (by rw h₀) else if h₁ : j = i+1 then P.d i ≫ eq_to_hom (by {simp [h₁]}) else 0 def inverse : cochain_complex C ⥤ complex C := { obj := λ P, { val := { obj := λ i, P.X i, map := λ i j p, long_map C P i j, map_id' := sorry, map_comp' := sorry }, property := sorry, }, map := λ P Q f, { app := λ i, f.f i, naturality' := sorry, }, map_id' := sorry, map_comp' := sorry, } def exercise : complex C ≌ cochain_complex C := { functor := functor C, inverse := inverse C, unit_iso := sorry, -- There's still more data to provide here. counit_iso := sorry, -- and here. functor_unit_iso_comp' := sorry, } end exercise
a5e961c1be48d86552e9d3b337067aba218efd77
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/data/char/basic.lean
1029a3d70701d8282987399b9ada2fb96b266cca
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
2,601
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.uint @[inline, reducible] def isValidChar (n : UInt32) : Prop := n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000) /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char := (val : UInt32) (valid : isValidChar val) instance : HasSizeof Char := ⟨fun c => c.val.toNat⟩ namespace Char def utf8Size (c : Char) : UInt32 := let v := c.val; if UInt32.land v 0x80 = 0 then 1 else if UInt32.land v 0xE0 = 0xC0 then 2 else if UInt32.land v 0xF0 = 0xE0 then 3 else if UInt32.land v 0xF8 = 0xF0 then 4 else if UInt32.land v 0xFC = 0xF8 then 5 else if UInt32.land v 0xFE = 0xFC then 6 else if v = 0xFF then 1 else 0 protected def Less (a b : Char) : Prop := a.val < b.val protected def LessEq (a b : Char) : Prop := a.val ≤ b.val instance : HasLess Char := ⟨Char.Less⟩ instance : HasLessEq Char := ⟨Char.LessEq⟩ protected def lt (a b : Char) : Bool := a.val < b.val instance decLt (a b : Char) : Decidable (a < b) := UInt32.decLt _ _ instance decLe (a b : Char) : Decidable (a ≤ b) := UInt32.decLe _ _ axiom isValidChar0 : isValidChar 0 @[noinline, matchPattern] def ofNat (n : Nat) : Char := if h : isValidChar (UInt32.ofNat n) then {val := UInt32.ofNat n, valid := h} else {val := 0, valid := isValidChar0} @[inline] def toNat (c : Char) : Nat := c.val.toNat theorem eqOfVeq : ∀ {c d : Char}, c.val = d.val → c = d | ⟨v, h⟩ ⟨_, _⟩ rfl := rfl theorem veqOfEq : ∀ {c d : Char}, c = d → c.val = d.val | _ _ rfl := rfl theorem neOfVne {c d : Char} (h : c.val ≠ d.val) : c ≠ d := fun h' => absurd (veqOfEq h') h theorem vneOfNe {c d : Char} (h : c ≠ d) : c.val ≠ d.val := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := {decEq := fun i j => decidableOfDecidableOfIff (decEq i.val j.val) ⟨Char.eqOfVeq, Char.veqOfEq⟩} instance : Inhabited Char := ⟨'A'⟩ def isWhitespace (c : Char) : Bool := c = ' ' || c = '\t' || c = '\n' def isUpper (c : Char) : Bool := c.val ≥ 65 && c.val ≤ 90 def isLower (c : Char) : Bool := c.val ≥ 97 && c.val ≤ 122 def isAlpha (c : Char) : Bool := c.isUpper || c.isLower def isDigit (c : Char) : Bool := c.val ≥ 48 && c.val ≤ 57 def isAlphanum (c : Char) : Bool := c.isAlpha || c.isDigit def toLower (c : Char) : Char := let n := toNat c; if n >= 65 ∧ n <= 90 then ofNat (n + 32) else c end Char
77f5e3a570726348969cbd0a7b882327db82863f
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Meta/Tactic/Congr.lean
4752528d03dfb9449afe79303e920d33f64e90bf
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,928
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.Meta.CongrTheorems import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Refl import Lean.Meta.Tactic.Assumption namespace Lean open Meta /-- Postprocessor after applying congruence theorem. Tries to close new goals using `Eq.refl`, `HEq.refl`, and `assumption`. It also tries to apply `heq_of_eq`. -/ private def congrPost (mvarIds : List MVarId) : MetaM (List MVarId) := mvarIds.filterMapM fun mvarId => do let mvarId ← mvarId.heqOfEq try mvarId.refl; return none catch _ => pure () try mvarId.hrefl; return none catch _ => pure () if (← mvarId.assumptionCore) then return none return some mvarId /-- Asserts the given congruence theorem as fresh hypothesis, and then applies it. Return the `fvarId` for the new hypothesis and the new subgoals. -/ private def applyCongrThm? (mvarId : MVarId) (congrThm : CongrTheorem) : MetaM (List MVarId) := do let mvarId ← mvarId.assert (← mkFreshUserName `h_congr_thm) congrThm.type congrThm.proof let (fvarId, mvarId) ← mvarId.intro1P let mvarIds ← mvarId.apply (mkFVar fvarId) mvarIds.mapM fun mvarId => mvarId.tryClear fvarId /-- Try to apply a `simp` congruence theorem. -/ def MVarId.congr? (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext do mvarId.checkNotAssigned `congr let target ← mvarId.getType' let some (_, lhs, _) := target.eq? | return none let lhs := lhs.cleanupAnnotations unless lhs.isApp do return none let some congrThm ← mkCongrSimp? lhs.getAppFn (subsingletonInstImplicitRhs := false) | return none applyCongrThm? mvarId congrThm /-- Try to apply a `hcongr` congruence theorem, and then tries to close resulting goals using `Eq.refl`, `HEq.refl`, and assumption. -/ def MVarId.hcongr? (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext do mvarId.checkNotAssigned `congr let target ← mvarId.getType' let some (_, lhs, _, _) := target.heq? | return none let lhs := lhs.cleanupAnnotations unless lhs.isApp do return none let congrThm ← mkHCongr lhs.getAppFn applyCongrThm? mvarId congrThm /-- Try to apply `implies_congr`. -/ def MVarId.congrImplies? (mvarId : MVarId) : MetaM (Option (List MVarId)) := observing? do let mvarId₁ :: mvarId₂ :: _ ← mvarId.apply (← mkConstWithFreshMVarLevels ``implies_congr) | throwError "unexpected number of goals" return [mvarId₁, mvarId₂] /-- Given a goal of the form `⊢ f as = f bs`, `⊢ (p → q) = (p' → q')`, or `⊢ HEq (f as) (f bs)`, try to apply congruence. It takes proof irrelevance into account, the fact that `Decidable p` is a subsingleton. If `closeEasy := true`, it tries to close new subgoals using `Eq.refl`, `HEq.refl`, and `assumption`. -/ def MVarId.congr (mvarId : MVarId) (closeEasy := true) : MetaM (List MVarId) := do let mvarIds ← if let some mvarIds ← mvarId.congr? then pure mvarIds else if let some mvarIds ← mvarId.hcongr? then pure mvarIds else if let some mvarIds ← mvarId.congrImplies? then pure mvarIds else throwTacticEx `congr mvarId "failed to apply congruence" if closeEasy then congrPost mvarIds else return mvarIds /-- Applies `congr` recursively up to depth `n`. -/ def MVarId.congrN (mvarId : MVarId) (n : Nat) : MetaM (List MVarId) := do if n == 1 then mvarId.congr else let (_, s) ← go n mvarId |>.run #[] return s.toList where go (n : Nat) (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do match n with | 0 => modify (·.push mvarId) | n+1 => let some mvarIds ← observing? (m := MetaM) mvarId.congr | modify (·.push mvarId) mvarIds.forM (go n) end Lean
1909ab72a3b0af0626d72413942e27682c9a8bff
6214e13b31733dc9aeb4833db6a6466005763162
/src/sizeof.lean
8756b8141ad46bf4999db812e44ee3cf45c5ec79
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
14,395
lean
-- lemmas about sizes of syntactic elements used for termination import .syntax .etc -- to use values, expressions, terms, specs, histories and environments with recursion, -- we need to show that the recursion is decreasing, i.e. its parts are smaller than the whole lemma sizeof_value_func_R {f x: var} {R S: spec} {e: exp} {σ: env}: R.sizeof < (value.func f x R S e σ).sizeof := begin unfold value.sizeof, rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_value_func_S {f x: var} {R S: spec} {e: exp} {σ: env}: S.sizeof < (value.func f x R S e σ).sizeof := begin unfold value.sizeof, rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_value_func_e {f x: var} {R S: spec} {e: exp} {σ: env}: e.sizeof < (value.func f x R S e σ).sizeof := begin unfold value.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_value_func_σ {f x: var} {R S: spec} {e: exp} {σ: env}: σ.sizeof < (value.func f x R S e σ).sizeof := begin unfold value.sizeof, rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_true {x: var} {e: exp}: e.sizeof < (exp.true x e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_false {x: var} {e: exp}: e.sizeof < (exp.false x e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_num {x: var} {n: ℤ} {e: exp}: e.sizeof < (exp.num x n e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_func_R {f x: var} {R S: spec} {e₁ e₂: exp}: R.sizeof < (exp.func f x R S e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_func_S {f x: var} {R S: spec} {e₁ e₂: exp}: S.sizeof < (exp.func f x R S e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_func_e₁ {f x: var} {R S: spec} {e₁ e₂: exp}: e₁.sizeof < (exp.func f x R S e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_func_e₂ {f x: var} {R S: spec} {e₁ e₂: exp}: e₂.sizeof < (exp.func f x R S e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_unop {x y: var} {op: unop} {e: exp}: e.sizeof < (exp.unop y op x e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_binop {x y z: var} {op: binop} {e: exp}: e.sizeof < (exp.binop z op x y e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_app {x y z: var} {e: exp}: e.sizeof < (exp.app z x y e).sizeof := begin unfold exp.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_ite_e₁ {x: var} {e₁ e₂: exp}: e₁.sizeof < (exp.ite x e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_exp_ite_e₂ {x: var} {e₁ e₂: exp}: e₂.sizeof < (exp.ite x e₁ e₂).sizeof := begin unfold exp.sizeof, rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_term_value {v: value}: v.sizeof < (term.value v).sizeof := begin unfold term.sizeof, rw[add_comm], apply lt_add_of_pos_right, from zero_lt_one end lemma sizeof_term_unop {op: unop} {t: term}: t.sizeof < (term.unop op t).sizeof := begin unfold term.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_term_binop₁ {op: binop} {t₁ t₂: term}: t₁.sizeof < (term.binop op t₁ t₂).sizeof := begin unfold term.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_term_binop₂ {op: binop} {t₁ t₂: term}: t₂.sizeof < (term.binop op t₁ t₂).sizeof := begin unfold term.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_term_app₁ {t₁ t₂: term}: t₁.sizeof < (term.app t₁ t₂).sizeof := begin unfold term.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_term_app₂ {t₁ t₂: term}: t₂.sizeof < (term.app t₁ t₂).sizeof := begin unfold term.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_term {t: term}: t.sizeof < (spec.term t).sizeof := begin unfold spec.sizeof, rw[add_comm], apply lt_add_of_pos_right, from zero_lt_one end lemma sizeof_spec_not {R: spec}: R.sizeof < R.not.sizeof := begin unfold spec.sizeof, rw[add_comm], apply lt_add_of_pos_right, from zero_lt_one end lemma sizeof_spec_and₁ {R S: spec}: R.sizeof < (spec.and R S).sizeof := begin unfold spec.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof S + 1, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_and₂ {R S: spec}: S.sizeof < (spec.and R S).sizeof := begin unfold spec.sizeof, rw[add_comm], apply lt_add_of_pos_right, change 0 < 1 + sizeof R, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_or₁ {R S: spec}: R.sizeof < (spec.or R S).sizeof := begin unfold spec.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof S + 1, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_or₂ {R S: spec}: S.sizeof < (spec.or R S).sizeof := begin unfold spec.sizeof, rw[add_comm], apply lt_add_of_pos_right, change 0 < 1 + sizeof R, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_func_t {f: term} {x: var} {R S: spec}: f.sizeof < (spec.func f x R S).sizeof := begin unfold spec.sizeof, rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_func_R {f: term} {x: var} {R S: spec}: R.sizeof < (spec.func f x R S).sizeof := begin unfold spec.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof S + (1 + sizeof f + sizeof x), apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_spec_func_S {f: term} {x: var} {R S: spec}: S.sizeof < (spec.func f x R S).sizeof := begin unfold spec.sizeof, rw[add_comm], apply lt_add_of_pos_right, change 0 < 1 + sizeof f + sizeof x + sizeof R, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_env_rest {σ: env} {x: var} {v: value}: σ.sizeof < (env.cons σ x v).sizeof := begin unfold env.sizeof, rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof x + (sizeof v + 1), apply lt_add_of_le_of_pos nonneg_of_nat, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_env_value {σ: env} {x: var} {v: value}: v.sizeof < (env.cons σ x v).sizeof := begin unfold env.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_not {P: prop}: P.sizeof < P.not.sizeof := begin unfold prop.sizeof, rw[add_comm], apply lt_add_of_pos_right, from zero_lt_one end lemma sizeof_prop_and₁ {P S: prop}: P.sizeof < (prop.and P S).sizeof := begin unfold prop.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof S + 1, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_and₂ {P S: prop}: S.sizeof < (prop.and P S).sizeof := begin unfold prop.sizeof, rw[add_comm], apply lt_add_of_pos_right, change 0 < 1 + sizeof P, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_or₁ {P S: prop}: P.sizeof < (prop.or P S).sizeof := begin unfold prop.sizeof, rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, change 0 < sizeof S + 1, apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_or₂ {P S: prop}: S.sizeof < (prop.or P S).sizeof := begin unfold prop.sizeof, rw[add_comm], apply lt_add_of_pos_right, change 0 < 1 + sizeof P, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_exis {P: prop} {x: var}: P.sizeof < (prop.exis x P).sizeof := begin unfold prop.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end lemma sizeof_prop_forall {P: prop} {x: var}: P.sizeof < (prop.forallc x P).sizeof := begin unfold prop.sizeof, rw[add_comm], apply lt_add_of_pos_right, rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end
b8622a0d944a38e7885451abb439b68434f2a261
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/tm_to_partrec.lean
fa03f6b14f08dd6d8a9d85b5f02404d35d82da96
[]
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
38,413
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.computability.halting import Mathlib.computability.turing_machine import Mathlib.data.num.lemmas import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # Modelling partial recursive functions using Turing machines This file defines a simplified basis for partial recursive functions, and a `turing.TM2` model Turing machine for evaluating these functions. This amounts to a constructive proof that every `partrec` function can be evaluated by a Turing machine. ## Main definitions * `to_partrec.code`: a simplified basis for partial recursive functions, valued in `list ℕ →. list ℕ`. * `to_partrec.code.eval`: semantics for a `to_partrec.code` program * `partrec_to_TM2.tr`: A TM2 turing machine which can evaluate `code` programs -/ namespace turing /-! ## A simplified basis for partrec This section constructs the type `code`, which is a data type of programs with `list ℕ` input and output, with enough expressivity to write any partial recursive function. The primitives are: * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) This basis is convenient because it is closer to the Turing machine model - the key operations are splitting and merging of lists of unknown length, while the messy `n`-ary composition operation from the traditional basis for partial recursive functions is absent - but it retains a compositional semantics. The first step in transitioning to Turing machines is to make a sequential evaluator for this basis, which we take up in the next section. -/ namespace to_partrec /-- The type of codes for primitive recursive functions. Unlike `nat.partrec.code`, this uses a set of operations on `list ℕ`. See `code.eval` for a description of the behavior of the primitives. -/ inductive code where | zero' : code | succ : code | tail : code | cons : code → code → code | comp : code → code → code | case : code → code → code | fix : code → code /-- The semantics of the `code` primitives, as partial functions `list ℕ →. list ℕ`. By convention we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where `v` will be ignored by a subsequent function. * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) -/ @[simp] def code.eval : code → List ℕ →. List ℕ := sorry namespace code /-- `nil` is the constant nil function: `nil v = []`. -/ def nil : code := comp tail succ @[simp] theorem nil_eval (v : List ℕ) : eval nil v = pure [] := sorry /-- `id` is the identity function: `id v = v`. -/ def id : code := comp tail zero' @[simp] theorem id_eval (v : List ℕ) : eval id v = pure v := sorry /-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/ def head : code := cons id nil @[simp] theorem head_eval (v : List ℕ) : eval head v = pure [list.head v] := sorry /-- `zero` is the constant zero function: `zero v = [0]`. -/ def zero : code := cons zero' nil @[simp] theorem zero_eval (v : List ℕ) : eval zero v = pure [0] := sorry /-- `pred` returns the predecessor of the head of the input: `pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/ def pred : code := case zero head @[simp] theorem pred_eval (v : List ℕ) : eval pred v = pure [Nat.pred (list.head v)] := sorry /-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions. `rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`. It is implemented as: rfind f v = pred (fix (λ (n::v), f (n::v) :: n+1 :: v) (0 :: v)) The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state; it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get `n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result. -/ def rfind (f : code) : code := comp pred (comp (fix (cons f (cons succ tail))) zero') /-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive functions. `prec f g` evaluates as: * `prec f g [] = [f []]` * `prec f g (0 :: v) = [f v]` * `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]` It is implemented as: G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v) F (0 :: f_v :: v) = (f_v :: v) F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail prec f g (a :: v) = [(F (a :: f v :: v)).head] Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid calling `g` more times than necessary (which could be bad if `g` diverges). If the input is `0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`, we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first number counts up, providing arguments for the applications to `g`, while the second number counts down, providing the exit condition (this is the initial `b` in the return value of `G`, which is stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where `res` is the desired result, and the rest reduces this to `[res]`. -/ def prec (f : code) (g : code) : code := let G : code := cons tail (cons succ (cons (comp pred tail) (cons (comp g (cons id (comp tail tail))) (comp tail (comp tail tail))))); let F : code := case id (comp (comp (comp tail tail) (fix G)) zero'); cons (comp F (cons head (cons (comp f tail) tail))) nil theorem exists_code.comp {m : ℕ} {n : ℕ} {f : vector ℕ n →. ℕ} {g : fin n → vector ℕ m →. ℕ} (hf : ∃ (c : code), ∀ (v : vector ℕ n), eval c (subtype.val v) = pure <$> f v) (hg : ∀ (i : fin n), ∃ (c : code), ∀ (v : vector ℕ m), eval c (subtype.val v) = pure <$> g i v) : ∃ (c : code), ∀ (v : vector ℕ m), eval c (subtype.val v) = pure <$> ((vector.m_of_fn fun (i : fin n) => g i v) >>= f) := sorry theorem exists_code {n : ℕ} {f : vector ℕ n →. ℕ} (hf : nat.partrec' f) : ∃ (c : code), ∀ (v : vector ℕ n), eval c (subtype.val v) = pure <$> f v := sorry end code /-! ## From compositional semantics to sequential semantics Our initial sequential model is designed to be as similar as possible to the compositional semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than defining an `eval c : list ℕ →. list ℕ` function for each program, defined by recursion on programs, we have a type `cfg` with a step function `step : cfg → option cfg` that provides a deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*, which can be viewed as a `code` with a hole in it where evaluation is currently taking place. Continuations can be assigned a `list ℕ →. list ℕ` semantics as well, with the interpretation being that given a `list ℕ` result returned from the code in the hole, the remainder of the program will evaluate to a `list ℕ` final value. The continuations are: * `halt`: the empty continuation: the hole is the whole program, whatever is returned is the final result. In our notation this is just `_`. * `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the outer continuation. * `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.head :: _)`. (Technically we don't need to hold on to all of `ns` here since we are already committed to taking the head, but this is more regular.) * `comp f k`: evaluating the first part of a composition: `k (f _)`. * `fix f k`: waiting for the result of `f` in a `fix f` expression: `k (if _.head = 0 then _.tail else fix f (_.tail))` The type `cfg` of evaluation states is: * `ret k v`: we have received a result, and are now evaluating the continuation `k` with result `v`; that is, `k v` where `k` is ready to evaluate. * `halt v`: we are done and the result is `v`. The main theorem of this section is that for each code `c`, the state `step_normal c halt v` steps to `v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ /-- The type of continuations, built up during evaluation of a `code` expression. -/ inductive cont where | halt : cont | cons₁ : code → List ℕ → cont → cont | cons₂ : List ℕ → cont → cont | comp : code → cont → cont | fix : code → cont → cont /-- The semantics of a continuation. -/ def cont.eval : cont → List ℕ →. List ℕ := sorry /-- The semantics of a continuation. -/ inductive cfg where | halt : List ℕ → cfg | ret : cont → List ℕ → cfg /-- Evaluating `c : code` in a continuation `k : cont` and input `v : list ℕ`. This goes by recursion on `c`, building an augmented continuation and a value to pass to it. * `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation * `succ v = [v.head.succ]` evaluates immediately, so we return it to the parent continuation * `tail v = v.tail` evaluates immediately, so we return it to the parent continuation * `cons f fs v = (f v).head :: fs v` requires two sub-evaluations, so we evaluate `f v` in the continuation `k (_.head :: fs v)` (called `cont.cons₁ fs v k`) * `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate `g v` in the continuation `k (f _)` (called `cont.comp f k`) * `case f g v = v.head.cases_on (f v.tail) (λ n, g (n :: v.tail))` has the information needed to evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`. * `fix f v = let v' := f v in if v'.head = 0 then k v'.tail else fix f v'.tail` needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called `cont.fix f k`) -/ def step_normal : code → cont → List ℕ → cfg := sorry /-- Evaluating a continuation `k : cont` on input `v : list ℕ`. This is the second part of evaluation, when we receive results from continuations built by `step_normal`. * `cont.halt v = v`, so we are done and transition to the `cfg.halt v` state * `cont.cons₁ fs as k v = k (v.head :: fs as)`, so we evaluate `fs as` now with the continuation `k (v.head :: _)` (called `cons₂ v k`). * `cont.cons₂ ns k v = k (ns.head :: v)`, where we now have everything we need to evaluate `ns.head :: v`, so we return it to `k`. * `cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation. * `cont.fix f k v = k (if v.head = 0 then k v.tail else fix f v.tail)`, where `v` is a value, so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as the continuation (which immediately calls `f` with `cont.fix f k` as the continuation). -/ def step_ret : cont → List ℕ → cfg := sorry /-- If we are not done (in `cfg.halt` state), then we must be still stuck on a continuation, so this main loop calls `step_ret` with the new continuation. The overall `step` function transitions from one `cfg` to another, only halting at the `cfg.halt` state. -/ def step : cfg → Option cfg := sorry /-- In order to extract a compositional semantics from the sequential execution behavior of configurations, we observe that continuations have a monoid structure, with `cont.halt` as the unit and `cont.then` as the multiplication. `cont.then k₁ k₂` runs `k₁` until it halts, and then takes the result of `k₁` and passes it to `k₂`. We will not prove it is associative (although it is), but we are instead interested in the associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and compositional levels, and allows us to express running a machine without the ambient continuation and relate it to the original machine's evaluation steps. In the literature this is usually where one uses Turing machines embedded inside other Turing machines, but this approach allows us to avoid changing the ambient type `cfg` in the middle of the recursion. -/ def cont.then : cont → cont → cont := sorry theorem cont.then_eval {k : cont} {k' : cont} {v : List ℕ} : cont.eval (cont.then k k') v = cont.eval k v >>= cont.eval k' := sorry /-- The `then k` function is a "configuration homomorphism". Its operation on states is to append `k` to the continuation of a `cfg.ret` state, and to run `k` on `v` if we are in the `cfg.halt v` state. -/ def cfg.then : cfg → cont → cfg := sorry /-- The `step_normal` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_normal_then (c : code) (k : cont) (k' : cont) (v : List ℕ) : step_normal c (cont.then k k') v = cfg.then (step_normal c k v) k' := sorry /-- The `step_ret` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_ret_then {k : cont} {k' : cont} {v : List ℕ} : step_ret (cont.then k k') v = cfg.then (step_ret k v) k' := sorry /-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds. It asserts that `c` is semantically correct; that is, for any `k` and `v`, `eval (step_normal c k v) = eval (cfg.ret k (code.eval c v))`, as an equality of partial values (so one diverges iff the other does). In particular, we can let `k = cont.halt`, and then this asserts that `step_normal c cont.halt v` evaluates to `cfg.halt (code.eval c v)`. -/ def code.ok (c : code) := ∀ (k : cont) (v : List ℕ), eval step (step_normal c k v) = do let v ← code.eval c v eval step (cfg.ret k v) theorem code.ok.zero {c : code} (h : code.ok c) {v : List ℕ} : eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v := sorry theorem step_normal.is_ret (c : code) (k : cont) (v : List ℕ) : ∃ (k' : cont), ∃ (v' : List ℕ), step_normal c k v = cfg.ret k' v' := sorry theorem cont_eval_fix {f : code} {k : cont} {v : List ℕ} (fok : code.ok f) : eval step (step_normal f (cont.fix f k) v) = do let v ← code.eval (code.fix f) v eval step (cfg.ret k v) := sorry theorem code_is_ok (c : code) : code.ok c := sorry theorem step_normal_eval (c : code) (v : List ℕ) : eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v := code.ok.zero (code_is_ok c) theorem step_ret_eval {k : cont} {v : List ℕ} : eval step (step_ret k v) = cfg.halt <$> cont.eval k v := sorry end to_partrec /-! ## Simulating sequentialized partial recursive functions in TM2 At this point we have a sequential model of partial recursive functions: the `cfg` type and `step : cfg → option cfg` function from the previous section. The key feature of this model is that it does a finite amount of computation (in fact, an amount which is statically bounded by the size of the program) between each step, and no individual step can diverge (unlike the compositional semantics, where every sub-part of the computation is potentially divergent). So we can utilize the same techniques as in the other TM simulations in `computability.turing_machine` to prove that each step corresponds to a finite number of steps in a lower level model. (We don't prove it here, but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.) The target model is `turing.TM2`, which has a fixed finite set of stacks, a bit of local storage, with programs selected from a potentially infinite (but finitely accessible) set of program positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands. For this program we will need four stacks, each on an alphabet `Γ'` like so: inductive Γ' | Cons | cons | bit0 | bit1 We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and lists of lists of natural numbers by putting `Cons` after each list. For example: 0 ~> [] 1 ~> [bit1] 6 ~> [bit0, bit1, bit1] [1, 2] ~> [bit1, cons, bit0, bit1, cons] [[], [1, 2]] ~> [Cons, bit1, cons, bit0, bit1, cons, Cons] The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the current program (a `list ℕ`) and `stack` contains data (a `list (list ℕ)`) associated to the current continuation, and in `ret` mode `main` contains the value that is being passed to the continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁` evaluation. The only local store we need is `option Γ'`, which stores the result of the last pop operation. (Most of our working data are natural numbers, which are too large to fit in the local store.) The continuations from the previous section are data-carrying, containing all the values that have been computed and are awaiting other arguments. In order to have only a finite number of continuations appear in the program so that they can be used in machine states, we separate the data part (anything with type `list ℕ`) from the `cont` type, producing a `cont'` type that lacks this information. The data is kept on the `stack` stack. Because we want to have subroutines for e.g. moving an entire stack to another place, we use an infinite inductive type `Λ'` so that we can execute a program and then return to do something else without having to define too many different kinds of intermediate states. (We must nevertheless prove that only finitely many labels are accessible.) The labels are: * `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved. The last element, that fails `p`, is placed in neither stack but left in the local store. At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`. * `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is left in the local storage. Then do `q`. * `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order), then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`. * `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine just for this purpose we can build up programs to execute inside a `goto` statement, where we have the flexibility to be general recursive. * `read (f : option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only here for convenience. * `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before, `[n+1]` will be on main after. This implements successor for binary natural numbers. * `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on `main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main` before then `n :: v` will be on `main` after and we transition to `q₂`. * `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in `stack` and sets up the data for the next continuation. * `ret (cons₁ fs k)`: `v :: k_data` on `stack` and `ns` on `main`, and the next step expects `v` on `main` and `ns :: k_data` on `stack`. So we have to do a little dance here with six reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two reversals. * `ret (cons₂ k)`: `ns :: k_data` is on `stack` and `v` is on `main`, and we have to put `ns.head :: v` on `main` and `k_data` on `stack`. This is done using the `head` subroutine. * `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and if so, remove it and call `k`, otherwise `clear` the first value and call `f`. * `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt. In addition to these basic states, we define some additional subroutines that are used in the above: * `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply inputs and outputs. * `unrev`: special case `move ff rev main` to move everything from `rev` back to `main`. Used as a cleanup operation in several functions. * `move_excl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack. * `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target stack. Implemented as `move_excl p k rev; move ff rev k₂`. Assumes that neither `k₁` nor `k₂` is `rev` and `rev` is initially empty. * `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.head]` will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on `main` and `ns :: k_data` on `stack`, and results in `k_data` on `stack` and `ns.head :: v` on `main`. * `tr_normal` is the main entry point, defining states that perform a given `code` computation. It mostly just dispatches to functions written above. The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`, the state `init c v` steps to `halt v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ namespace partrec_to_TM2 /-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values as lists of binary digits, `cons` is used to separate `list ℕ` values, and `Cons` is used to separate `list (list ℕ)` values. See the section documentation. -/ inductive Γ' where | Cons : Γ' | cons : Γ' | bit0 : Γ' | bit1 : Γ' /-- The four stacks used by the program. `main` is used to store the input value in `tr_normal` mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the continuations. `rev` is used to store reversed lists when transferring values between stacks, and `aux` is only used once in `cons₁`. See the section documentation. -/ inductive K' where | main : K' | rev : K' | aux : K' | stack : K' /-- Continuations as in `to_partrec.cont` but with the data removed. This is done because we want the set of all continuations in the program to be finite (so that it can ultimately be encoded into the finite state machine of a Turing machine), but a continuation can handle a potentially infinite number of data values during execution. -/ inductive cont' where | halt : cont' | cons₁ : to_partrec.code → cont' → cont' | cons₂ : cont' → cont' | comp : to_partrec.code → cont' → cont' | fix : to_partrec.code → cont' → cont' /-- The set of program positions. We make extensive use of inductive types here to let us describe "subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where `q` is another label. In order to prevent this from resulting in an infinite number of distinct accessible states, we are careful to be non-recursive (although loops are okay). See the section documentation for a description of all the programs. -/ inductive Λ' where | move : (Γ' → Bool) → K' → K' → Λ' → Λ' | clear : (Γ' → Bool) → K' → Λ' → Λ' | copy : Λ' → Λ' | push : K' → (Option Γ' → Option Γ') → Λ' → Λ' | read : (Option Γ' → Λ') → Λ' | succ : Λ' → Λ' | pred : Λ' → Λ' → Λ' | ret : cont' → Λ' protected instance Λ'.inhabited : Inhabited Λ' := { default := Λ'.ret cont'.halt } /-- The type of TM2 statements used by this machine. -/ /-- The type of TM2 configurations used by this machine. -/ def stmt' := TM2.stmt (fun (_x : K') => Γ') Λ' (Option Γ') def cfg' := TM2.cfg (fun (_x : K') => Γ') Λ' (Option Γ') /-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.Cons` (or implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/ def nat_end : Γ' → Bool := sorry /-- Pop a value from the stack and place the result in local store. -/ /-- Peek a value from the stack and place the result in local store. -/ @[simp] def pop' (k : K') : stmt' → stmt' := TM2.stmt.pop k fun (x v : Option Γ') => v /-- Push the value in the local store to the given stack. -/ @[simp] def peek' (k : K') : stmt' → stmt' := TM2.stmt.peek k fun (x v : Option Γ') => v @[simp] def push' (k : K') : stmt' → stmt' := TM2.stmt.push k fun (x : Option Γ') => option.iget x /-- Move everything from the `rev` stack to the `main` stack (reversed). -/ def unrev (q : Λ') : Λ' := Λ'.move (fun (_x : Γ') => false) K'.rev K'.main /-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/ def move_excl (p : Γ' → Bool) (k₁ : K') (k₂ : K') (q : Λ') : Λ' := Λ'.move p k₁ k₂ (Λ'.push k₁ id q) /-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev` stack. -/ def move₂ (p : Γ' → Bool) (k₁ : K') (k₂ : K') (q : Λ') : Λ' := move_excl p k₁ K'.rev (Λ'.move (fun (_x : Γ') => false) K'.rev k₂ q) /-- Assuming `tr_list v` is on the front of stack `k`, remove it, and push `v.head` onto `main`. See the section documentation. -/ def head (k : K') (q : Λ') : Λ' := Λ'.move nat_end k K'.rev (Λ'.push K'.rev (fun (_x : Option Γ') => some Γ'.cons) (Λ'.read fun (s : Option Γ') => ite (s = some Γ'.Cons) id (Λ'.clear (fun (x : Γ') => to_bool (x = Γ'.Cons)) k) (unrev q))) /-- The program that evaluates code `c` with continuation `k`. This expects an initial state where `tr_list v` is on `main`, `tr_cont_stack k` is on `stack`, and `aux` and `rev` are empty. See the section documentation for details. -/ @[simp] def tr_normal : to_partrec.code → cont' → Λ' := sorry /-- The main program. See the section documentation for details. -/ @[simp] def tr : Λ' → stmt' := sorry /-- Translating a `cont` continuation to a `cont'` continuation simply entails dropping all the data. This data is instead encoded in `tr_cont_stack` in the configuration. -/ def tr_cont : to_partrec.cont → cont' := sorry /-- We use `pos_num` to define the translation of binary natural numbers. A natural number is represented as a little-endian list of `bit0` and `bit1` elements: 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/ def tr_pos_num : pos_num → List Γ' := sorry /-- We use `num` to define the translation of binary natural numbers. Positive numbers are translated using `tr_pos_num`, and `tr_num 0 = []`. So there are never any trailing `bit0`'s in a translated `num`. 0 = [] 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] -/ def tr_num : num → List Γ' := sorry /-- Because we use binary encoding, we define `tr_nat` in terms of `tr_num`, using `num`, which are binary natural numbers. (We could also use `nat.binary_rec_on`, but `num` and `pos_num` make for easy inductions.) -/ def tr_nat (n : ℕ) : List Γ' := tr_num ↑n @[simp] theorem tr_nat_zero : tr_nat 0 = [] := rfl /-- Lists are translated with a `cons` after each encoded number. For example: [] = [] [0] = [cons] [1] = [bit1, cons] [6, 0] = [bit0, bit1, bit1, cons, cons] -/ @[simp] def tr_list : List ℕ → List Γ' := sorry /-- Lists of lists are translated with a `Cons` after each encoded list. For example: [] = [] [[]] = [Cons] [[], []] = [Cons, Cons] [[0]] = [cons, Cons] [[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, Cons, cons, Cons] -/ @[simp] def tr_llist : List (List ℕ) → List Γ' := sorry /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ @[simp] def cont_stack : to_partrec.cont → List (List ℕ) := sorry /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ def tr_cont_stack (k : to_partrec.cont) : List Γ' := tr_llist (cont_stack k) /-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to represent the stack data as four lists rather than as a function `K' → list Γ'`, because this makes rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated after an `update` to one of the components. -/ @[simp] def K'.elim (a : List Γ') (b : List Γ') (c : List Γ') (d : List Γ') : K' → List Γ' := sorry @[simp] theorem K'.elim_update_main {a : List Γ'} {b : List Γ'} {c : List Γ'} {d : List Γ'} {a' : List Γ'} : function.update (K'.elim a b c d) K'.main a' = K'.elim a' b c d := sorry @[simp] theorem K'.elim_update_rev {a : List Γ'} {b : List Γ'} {c : List Γ'} {d : List Γ'} {b' : List Γ'} : function.update (K'.elim a b c d) K'.rev b' = K'.elim a b' c d := sorry @[simp] theorem K'.elim_update_aux {a : List Γ'} {b : List Γ'} {c : List Γ'} {d : List Γ'} {c' : List Γ'} : function.update (K'.elim a b c d) K'.aux c' = K'.elim a b c' d := sorry @[simp] theorem K'.elim_update_stack {a : List Γ'} {b : List Γ'} {c : List Γ'} {d : List Γ'} {d' : List Γ'} : function.update (K'.elim a b c d) K'.stack d' = K'.elim a b c d' := sorry /-- The halting state corresponding to a `list ℕ` output value. -/ def halt (v : List ℕ) : cfg' := TM2.cfg.mk none none (K'.elim (tr_list v) [] [] []) /-- The `cfg` states map to `cfg'` states almost one to one, except that in normal operation the local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly clear it in the halt state so that there is exactly one configuration corresponding to output `v`. -/ def tr_cfg : to_partrec.cfg → cfg' → Prop := sorry /-- This could be a general list definition, but it is also somewhat specialized to this application. `split_at_pred p L` will search `L` for the first element satisfying `p`. If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns `(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/ def split_at_pred {α : Type u_1} (p : α → Bool) : List α → List α × Option α × List α := sorry theorem split_at_pred_eq {α : Type u_1} (p : α → Bool) (L : List α) (l₁ : List α) (o : Option α) (l₂ : List α) : (∀ (x : α), x ∈ l₁ → p x = false) → (option.elim o (L = l₁ ∧ l₂ = []) fun (a : α) => p a = tt ∧ L = l₁ ++ a :: l₂) → split_at_pred p L = (l₁, o, l₂) := sorry theorem split_at_pred_ff {α : Type u_1} (L : List α) : split_at_pred (fun (_x : α) => false) L = (L, none, []) := split_at_pred_eq (fun (_x : α) => false) L L none [] (fun (_x : α) (_x : _x ∈ L) => rfl) { left := rfl, right := rfl } theorem move_ok {p : Γ' → Bool} {k₁ : K'} {k₂ : K'} {q : Λ'} {s : Option Γ'} {L₁ : List Γ'} {o : Option Γ'} {L₂ : List Γ'} {S : K' → List Γ'} (h₁ : k₁ ≠ k₂) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.move p k₁ k₂ q)) s S) (TM2.cfg.mk (some q) o (function.update (function.update S k₁ L₂) k₂ (list.reverse_core L₁ (S k₂)))) := sorry theorem unrev_ok {q : Λ'} {s : Option Γ'} {S : K' → List Γ'} : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (unrev q)) s S) (TM2.cfg.mk (some q) none (function.update (function.update S K'.rev []) K'.main (list.reverse_core (S K'.rev) (S K'.main)))) := move_ok (of_as_true trivial) (split_at_pred_ff (S K'.rev)) theorem move₂_ok {p : Γ' → Bool} {k₁ : K'} {k₂ : K'} {q : Λ'} {s : Option Γ'} {L₁ : List Γ'} {o : Option Γ'} {L₂ : List Γ'} {S : K' → List Γ'} (h₁ : k₁ ≠ K'.rev ∧ k₂ ≠ K'.rev ∧ k₁ ≠ k₂) (h₂ : S K'.rev = []) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (move₂ p k₁ k₂ q)) s S) (TM2.cfg.mk (some q) none (function.update (function.update S k₁ (option.elim o id List.cons L₂)) k₂ (L₁ ++ S k₂))) := sorry theorem clear_ok {p : Γ' → Bool} {k : K'} {q : Λ'} {s : Option Γ'} {L₁ : List Γ'} {o : Option Γ'} {L₂ : List Γ'} {S : K' → List Γ'} (e : split_at_pred p (S k) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.clear p k q)) s S) (TM2.cfg.mk (some q) o (function.update S k L₂)) := sorry theorem copy_ok (q : Λ') (s : Option Γ') (a : List Γ') (b : List Γ') (c : List Γ') (d : List Γ') : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.copy q)) s (K'.elim a b c d)) (TM2.cfg.mk (some q) none (K'.elim (list.reverse_core b a) [] c (list.reverse_core b d))) := sorry theorem tr_pos_num_nat_end (n : pos_num) (x : Γ') (H : x ∈ tr_pos_num n) : nat_end x = false := sorry theorem tr_num_nat_end (n : num) (x : Γ') (H : x ∈ tr_num n) : nat_end x = false := sorry theorem tr_nat_nat_end (n : ℕ) (x : Γ') (H : x ∈ tr_nat n) : nat_end x = false := tr_num_nat_end ↑n theorem tr_list_ne_Cons (l : List ℕ) (x : Γ') (H : x ∈ tr_list l) : x ≠ Γ'.Cons := sorry theorem head_main_ok {q : Λ'} {s : Option Γ'} {L : List ℕ} {c : List Γ'} {d : List Γ'} : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (head K'.main q)) s (K'.elim (tr_list L) [] c d)) (TM2.cfg.mk (some q) none (K'.elim (tr_list [list.head L]) [] c d)) := sorry theorem head_stack_ok {q : Λ'} {s : Option Γ'} {L₁ : List ℕ} {L₂ : List ℕ} {L₃ : List Γ'} : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (head K'.stack q)) s (K'.elim (tr_list L₁) [] [] (tr_list L₂ ++ Γ'.Cons :: L₃))) (TM2.cfg.mk (some q) none (K'.elim (tr_list (list.head L₂ :: L₁)) [] [] L₃)) := sorry theorem succ_ok {q : Λ'} {s : Option Γ'} {n : ℕ} {c : List Γ'} {d : List Γ'} : reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.succ q)) s (K'.elim (tr_list [n]) [] c d)) (TM2.cfg.mk (some q) none (K'.elim (tr_list [Nat.succ n]) [] c d)) := sorry theorem pred_ok (q₁ : Λ') (q₂ : Λ') (s : Option Γ') (v : List ℕ) (c : List Γ') (d : List Γ') : ∃ (s' : Option Γ'), reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.pred q₁ q₂)) s (K'.elim (tr_list v) [] c d)) (nat.elim (TM2.cfg.mk (some q₁) s' (K'.elim (tr_list (list.tail v)) [] c d)) (fun (n : ℕ) (_x : TM2.cfg (fun (_x : K') => Γ') Λ' (Option Γ')) => TM2.cfg.mk (some q₂) s' (K'.elim (tr_list (n :: list.tail v)) [] c d)) (list.head v)) := sorry theorem tr_normal_respects (c : to_partrec.code) (k : to_partrec.cont) (v : List ℕ) (s : Option Γ') : ∃ (b₂ : cfg'), tr_cfg (to_partrec.step_normal c k v) b₂ ∧ reaches₁ (TM2.step tr) (TM2.cfg.mk (some (tr_normal c (tr_cont k))) s (K'.elim (tr_list v) [] [] (tr_cont_stack k))) b₂ := sorry theorem tr_ret_respects (k : to_partrec.cont) (v : List ℕ) (s : Option Γ') : ∃ (b₂ : cfg'), tr_cfg (to_partrec.step_ret k v) b₂ ∧ reaches₁ (TM2.step tr) (TM2.cfg.mk (some (Λ'.ret (tr_cont k))) s (K'.elim (tr_list v) [] [] (tr_cont_stack k))) b₂ := sorry theorem tr_respects : respects to_partrec.step (TM2.step tr) tr_cfg := sorry /-- The initial state, evaluating function `c` on input `v`. -/ def init (c : to_partrec.code) (v : List ℕ) : cfg' := TM2.cfg.mk (some (tr_normal c cont'.halt)) none (K'.elim (tr_list v) [] [] []) theorem tr_init (c : to_partrec.code) (v : List ℕ) : ∃ (b : cfg'), tr_cfg (to_partrec.step_normal c to_partrec.cont.halt v) b ∧ reaches₁ (TM2.step tr) (init c v) b := tr_normal_respects c to_partrec.cont.halt v none theorem tr_eval (c : to_partrec.code) (v : List ℕ) : eval (TM2.step tr) (init c v) = halt <$> to_partrec.code.eval c v := sorry
185b8a182de444bd8a622aa9ba7dc454f89622e8
aa2345b30d710f7e75f13157a35845ee6d48c017
/data/padics/padic_numbers.lean
a564aa48898986ba83d6f93b2d9ab566095e2ae1
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
28,348
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Define the p-adic numbers (rationals) ℚ_p as the completion of ℚ wrt the p-adic norm. Show that the p-adic norm extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is complete -/ import data.real.cau_seq_completion data.real.cau_seq_filter import data.padics.padic_norm algebra.archimedean analysis.normed_space noncomputable theory local attribute [instance, priority 1] classical.prop_decidable open nat padic_val padic_norm cau_seq cau_seq.completion @[reducible] def padic_seq (p : ℕ) [p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [nat.prime p] lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, m ≥ N → n ≥ N → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw ←hnam at this, apply _root_.lt_irrefl _ (by simp at this; exact this) end ⟩ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [nat.prime p] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding end padic_seq section open padic_seq meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : nat.prime p] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = fpow ↑p (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.gt_one] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hgt : padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg))) : false := begin have hpn : padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hgt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hgt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq def padic (p : ℕ) [nat.prime p] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [nat.prime p] instance discrete_field : discrete_field (ℚ_[p]) := cau_seq.completion.discrete_field -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [nat.prime p] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end example {α} [discrete_field α] (n : ℤ) : α := n -- without short circuits, this needs an increase of class.instance_max_depth @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom _, by simp [this, rat.mk_eq_div, of_rat_div] lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ instance : char_zero ℚ_[p] := ⟨ λ m n, suffices of_rat p ↑m = of_rat p ↑n ↔ m = n, by simpa using this, by simp [of_rat_eq] ⟩ end completion end padic def padic_norm_e {p : ℕ} [hp : nat.prime p] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [nat.prime p] lemma defn (f : padic_seq p) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = fpow p (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [nat.prime p] (q : ℚ_[p]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [nat.prime p] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma cast_succ_nat_pos (n : ℕ) : (↑(n + 1) : ℚ) > 0 := nat.cast_pos.2 $ succ_pos _ private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (cast_succ_nat_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - of_rat p ((lim_seq f) i)) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), rw ← cast_eq_of_rat, refine lt_of_lt_of_le h (div_le_of_le_mul (cast_succ_nat_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (nat.cast_le.2 hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, rw [←padic_norm_e.eq_padic_norm', padic.of_rat_sub], suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, simpa only [cast_eq_of_rat] }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa, apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hj }, { apply hN2, apply le_of_max_le_right hj, apply le_max_right } } }, { rw cast_eq_of_rat, apply hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (2 : ℚ) ≠ 0, by norm_num, have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, apply le_of_max_le_right hi }, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hi } } } end ⟩ end complete section normed_space variables (p : ℕ) [nat.prime p] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, rw ←rat.cast_add, apply rat.cast_le.2, apply padic_norm_e.triangle_ineq end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, simpa using h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_triangle, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : ε > 0) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, rw ←rat.cast_max, apply rat.cast_le.2, apply nonarchimedean' end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, rw ←rat.cast_max, congr, apply add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, congr, apply h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥padic.of_rat p q∥ = padic_norm p q := by unfold has_norm.norm; congr; apply padic_seq.norm_const protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑(fpow (↑p : ℚ) (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_image f this in ⟨n, congr_arg rat.cast hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_of_num_zero hnz, by simp [this, padic.cast_eq_of_rat, zero_le_one] else have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, have fpow (p : ℚ) (-↑(padic_val p n)) ≤ 1, from fpow_le_one_of_nonpos (show (↑p : ℚ) ≥ ↑(1: ℕ), from le_of_lt (nat.cast_lt.2 hp.gt_one)) (neg_nonpos_of_nonneg (int.coe_nat_nonneg _)), have (↑(fpow (p : ℚ) (-↑(padic_val p n))) : ℝ) ≤ (1 : ℚ), from rat.cast_le.2 this, by simpa [padic.cast_eq_of_rat, hnz', padic_norm, padic_val_rat, padic_val_eq_zero_of_not_dvd' hq] using this lemma eq_of_norm_add_lt_right {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [nat.prime p] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := ⟨λ f, let f' : cau_seq ℚ_[p] padic_norm_e := ⟨λ n, f n, λ ε hε, let ⟨N, hN⟩ := is_cau f ↑ε (rat.cast_pos.2 hε) in ⟨N, λ j hj, rat.cast_lt.1 (hN _ hj)⟩⟩ in let ⟨q, hq⟩ := padic.complete' f' in ⟨ q, λ ε hε, let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨N, hN⟩ := hq _ (by simpa using hε'l) in ⟨N, λ i hi, lt.trans (rat.cast_lt.2 (hN _ hi)) hε'r ⟩⟩⟩ lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : a > 0) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := cau_seq.lim_spec f _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) end padic
a67533137b1a999da5a9c62c7d52387f608850ec
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/mv_polynomial/basic.lean
5c6fa01b53389c0312e5e6a2ebd2108b14a24c01
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,280
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, Johan Commelin, Mario Carneiro -/ import data.polynomial.eval /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance : inhabited (mv_polynomial σ R) := ⟨0⟩ instance : has_scalar R (mv_polynomial σ R) := add_monoid_algebra.has_scalar instance : semimodule R (mv_polynomial σ R) := add_monoid_algebra.semimodule instance : algebra R (mv_polynomial σ R) := add_monoid_algebra.algebra /-- The coercion turning an `mv_polynomial` into the function which reports the coefficient of a given monomial. -/ def coeff_coe_to_fun : has_coe_to_fun (mv_polynomial σ R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, map_zero' := by simp [monomial], map_one' := rfl, map_add' := λ a a', single_add, map_mul' := λ a a', by simp [monomial, single_mul_single] } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) (hσ : ¬ nonempty σ) : function.surjective (C : R → mv_polynomial σ R) := begin refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩, simpa [(finsupp.ext (λ x, absurd (nonempty.intro x) hσ) : a = 0), C, monomial], end lemma C_surjective_fin_0 {R : Type*} [comm_ring R] : function.surjective (mv_polynomial.C : R → mv_polynomial (fin 0) R) := C_surjective (fin 0) (λ h, let ⟨n⟩ := h in fin_zero_elim n) @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := infinite.of_injective (λ i : ℕ, monomial (single (classical.arbitrary σ) i) 1) begin intros m n h, have := (single_eq_single_iff _ _ _ _).mp h, simp only [and_true, eq_self_iff_true, or_false, one_ne_zero, and_self, single_eq_single_iff, eq_self_iff_true, true_and] at this, rcases this with (rfl|⟨rfl, rfl⟩); refl end lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := begin apply finsupp.induction p, { exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero R (mv_polynomial σ R) _ _ _ a).symm }, intros p b f haf hb0 ih, rw [mul_add, ih, @smul_add R (mv_polynomial σ R) _ _ _ a], congr' 1, rw [add_monoid_algebra.mul_def, finsupp.smul_single], simp only [mv_polynomial.C], dsimp [mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add], { rw [mul_zero, finsupp.single_zero] }, { rw finsupp.sum_single_index, all_goals { rw [zero_mul, finsupp.single_zero] }, } end lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma single_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by { rw [← zero_add (single s n), monomial_add_single, C], refl } @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := by simp [monomial] @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := by rw [monomial, monomial, monomial, add_monoid_algebra.single_mul_single] @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := by rw [monomial, single_zero]; refl @[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) attribute [elab_as_eliminator] theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) @[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A} (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := by { ext, exacts [hC _, hX _] } lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := ring_hom.congr_fun (ring_hom_ext hC hX) p lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p @[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] {f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := by { ext, exact hf _ } @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section coeff section -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. local attribute [reducible] mv_polynomial /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := p m end @[ext] lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := by convert single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := by convert single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def], simp only [C, monomial], dsimp, rw [monomial], rw sum_single_index, { simp only [zero_add], convert sum_apply, simp only [single_apply, finsupp.sum], rw finset.sum_eq_single m, { rw if_pos rfl, refl }, { intros m' hm' H, apply if_neg, exact H }, { intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] } }, simp only [zero_mul, single_zero, zero_add, sum_zero], end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in (antidiagonal n).support, coeff x.1 p * coeff x.2 q := begin rw mul_def, -- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`, -- so we need to turn both sides into a sum over a product. have := @finset.sum_product (σ →₀ ℕ) R _ _ p.support q.support (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only }, convert single_apply }, symmetry, -- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`. apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)), { intros x hx hx', simp only [mem_antidiagonal_support, eq_self_iff_true, if_false, forall_true_iff], contrapose! hx', rw [if_neg hx'] }, { rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl', simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro }, { rintros ⟨i, j⟩ hij hij', refine ⟨⟨i, j⟩, _, _⟩, { simp only [mem_support_iff, finset.mem_product], contrapose! hij', exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' }, { rw [mem_antidiagonal_support] at hij, simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } }, { intros x hx hx', simp only [ne.def] at hx' ⊢, split_ifs with H, { refl }, { rw if_neg H at hx', contradiction } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { delta coeff, rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H, rcases H with ⟨j, hj, i', hi', H⟩, delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i', erw finset.mem_singleton at H, subst m, rw [mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0, let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i), use ψ, apply mv_polynomial.ext, intro i, simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'], split_ifs with hi hi, { rw hc }, { rw finsupp.not_mem_support_iff at hi, rwa mul_zero } }, end end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] variables (σ R) @[simp] lemma constant_coeff_comp_C : constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R := by { ext, apply constant_coeff_C } @[simp] lemma constant_coeff_comp_algebra_map : constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C _ _ end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables [comm_semiring S₁] variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := eval₂_one _ _ | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section local attribute [instance, priority 10] is_semiring_hom.comp lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables [comm_semiring S₁] variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff := by { ext; simp } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [finsupp.mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw finsupp.mem_support_iff, contrapose! hx, simp only [not_not, finsupp.mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end lemma C_dvd_iff_map_hom_eq_zero (q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : C r ∣ φ ↔ map q φ = 0 := begin rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff], simp only [coeff_map, ring_hom.coe_of, coeff_zero, hr], end lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ := begin rw mv_polynomial.ext_iff, apply forall_congr, intro m, rw [coeff_map], apply eq_iff_eq_cancel_right.mpr, refl end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [comm_semiring S₁] [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := by { ext i, simp } lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = aeval (λ i, φ (f i)) := by { ext i, simp } @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) := begin suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff, from ring_hom.congr_fun this p, ext; simp end @[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) := eval₂_hom_zero f p @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := eval₂_hom_zero (algebra_map R S₁) p @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
23447475fd19805c6c4a7218d03b4c523f8363cc
e91b0bc0bcf14cf6e1bfc20ad1f00ad7cfa5fa76
/src/glueing_functions/exact_sequence.lean
57e0843bb5dda8c02aa4c0a4e23fe3f80ef0da27
[]
no_license
kckennylau/lean-scheme
b2de50025289a0339d97798466ef777e1899b0f8
8dc513ef9606d2988227490e915b7c7e173a2791
refs/heads/master
1,587,165,137,978
1,548,172,249,000
1,548,172,249,000
167,025,881
0
0
null
1,548,173,930,000
1,548,173,924,000
Lean
UTF-8
Lean
false
false
10,855
lean
import localization_UMP import massot_indexed_products import data.fintype import data.set.finite import group_theory.submonoid import tactic.ring import chris_ring_lemma local attribute [instance] classical.prop_decidable -- Chris' proof of exactness universes u v w -- 00EJ open finset classical quotient section variables {α : Type u} {β : Type v} {γ : Type w} lemma is_ring_hom.inj_of_kernel_eq_zero [comm_ring α] [comm_ring β] {f : α → β} [hf : is_ring_hom f] (h : ∀ {x}, f x = 0 → x = 0) : function.injective f := λ x y hxy, by rw [← sub_eq_zero_iff_eq, ← is_ring_hom.map_sub f] at hxy; exact sub_eq_zero_iff_eq.1 (h hxy) instance indexed_product.is_ring_hom [comm_ring α] {I : Type v} {f : I → Type w} [∀ i, comm_ring (f i)] (g : α → Π i : I, f i) [rh : ∀ i : I, is_ring_hom (λ a : α, g a i)] : is_ring_hom g := { map_add := λ x y, funext $ λ i, @is_ring_hom.map_add _ _ _ _ _ (rh i) x y, map_mul := λ x y, funext $ λ i, @is_ring_hom.map_mul _ _ _ _ _ (rh i) x y, map_one := funext $ λ i, @is_ring_hom.map_one _ _ _ _ _ (rh i) } open finset lemma exists_sum_iff_mem_span_finset {x : β} [ring α] [module α β] {s : finset β} : x ∈ span (↑s : set β) ↔ ∃ r : β → α, x = s.sum (λ y, r y • y) := ⟨λ ⟨r, hr⟩, ⟨r, hr.2.symm ▸ sum_bij_ne_zero (λ a _ _, a) (λ a has ha, classical.by_contradiction (λ h, ha (by simp [hr.1 _ h]))) (λ _ _ _ _ _ _, id) (λ b hbr hb, ⟨b, (finsupp.mem_support_iff).2 (λ h, hb (by simp [h])), hb, rfl⟩) (λ _ _ _, rfl)⟩, λ ⟨r, hr⟩, hr.symm ▸ is_submodule.sum (λ c hc, is_submodule.smul _ (subset_span hc))⟩ lemma exists_sum_iff_mem_span_image_finset {x : β} [ring α] [module α β] {s : finset γ} {f : γ → β} : x ∈ span (↑(s.image f) : set β) ↔ ∃ r : γ → α, x = s.sum (λ b, r b • f b) := ⟨λ h, let ⟨r, hr⟩ := exists_sum_iff_mem_span_finset.1 h in have hc : ∀ y ∈ s, ∃ z ∈ s, f z = f y := λ y hy, ⟨y, hy, rfl⟩, ⟨λ y, if ∃ hy : y ∈ s, y = some (hc y hy) then r (f y) else 0, hr.symm ▸ sum_bij_ne_zero (λ a ha _, some (mem_image.1 ha)) (λ a ha _, let ⟨h, _⟩ := some_spec (mem_image.1 ha) in h) (λ a₁ a₂ ha₁ _ ha₂ _ h, let ⟨_, h₁⟩ := some_spec (mem_image.1 ha₁) in let ⟨_, h₂⟩ := some_spec (mem_image.1 ha₂) in h₁ ▸ h₂ ▸ h ▸ rfl) (λ b hbs hb0, have hfb : f b ∈ image f s := mem_image.2 ⟨b, hbs, rfl⟩, have hb : b = some (mem_image.1 hfb) := classical.by_contradiction (λ h, have h' : ¬∃ (x : b ∈ s), b = some _ := not_exists.2 (λ hy : b ∈ s, h), by rw [if_neg h', zero_smul] at hb0; exact hb0 rfl), ⟨f b, hfb, by rwa if_pos at hb0; exact ⟨hbs, hb⟩, hb⟩) (λ a ha ha0, let ⟨h₁, h₂⟩ := some_spec (mem_image.1 ha) in by rw [if_pos, h₂]; exact ⟨h₁, by simp only [h₂]⟩)⟩, λ ⟨r, hr⟩, hr.symm ▸ is_submodule.sum (λ c hc, is_submodule.smul _ (subset_span (mem_image.2 ⟨c, hc, rfl⟩)))⟩ lemma sum_pow_mem_span {α R : Type*} [comm_ring R] (s : finset α) (f : α → R) (n : α → ℕ) (r : α → R) : s.sum (λ a, r a • f a) ^ (s.sum n + 1) ∈ span (↑(s.image (λ a, f a ^ n a)) : set R) := finset.induction_on s (by simp) $ λ a s has hi, begin rw [sum_insert has, add_pow], refine @is_submodule.sum R R _ _ (span _) _ _ _ _ _ (λ k hk, _), cases le_total (n a) k with hak hak, { rw [← nat.add_sub_cancel' hak, pow_add], simp only [mul_assoc, smul_eq_mul, mul_pow, mul_left_comm _ (f a ^ n a)], exact is_submodule.smul' _ (subset_span (mem_image.2 ⟨a, mem_insert_self _ _, rfl⟩)) }, { rw [sum_insert has, add_assoc, add_comm (n a), nat.add_sub_assoc hak, pow_add], simp only [mul_assoc, smul_eq_mul, mul_pow, mul_left_comm _ (sum s _ ^ (sum s n + 1))], have : span ↑(image (λ a, f a ^ n a) s) ⊆ span ↑(image (λ a, f a ^ n a) (insert a s)) := span_minimal is_submodule_span (set.subset.trans (by rw [image_insert,coe_subset]; exact subset_insert _ _) subset_span), exact is_submodule.smul' _ (this hi), } end lemma one_mem_span_pow_of_mem_span {α R : Type*} [comm_ring R] {s : finset α} {f : α → R} (n : α → ℕ) (h : (1 : R) ∈ span (↑(s.image f) : set R)) : (1 : R) ∈ span (↑(s.image (λ x, f x ^ n x)) : set R) := let ⟨r, hr⟩ := exists_sum_iff_mem_span_image_finset.1 h in @one_pow R _ (s.sum n + 1) ▸ hr.symm ▸ sum_pow_mem_span _ _ _ _ end variables {R : Type u} {γ : Type v} [comm_ring R] [fintype γ] open localization def tag00EJ.α (f : γ → R) (x : R) : Π i, loc R (powers (f i)) := λ i, of_comm_ring R _ x noncomputable def tag00EJ.β {f : γ → R} (r : Π i, loc R (powers (f i))) (j k : γ) : loc R (powers (f j * f k)) := localize_more_left (f j) (f k) (r j) - localize_more_right (f j) (f k) (r k) -- β not a ring hom but it's β₁ - β₂ with ring homs defined below. noncomputable def tag00EJ.β₁ {f : γ → R} (r : Π i, loc R (powers (f i))) (j k : γ) : loc R (powers (f j * f k)) := localize_more_left (f j) (f k) (r j) noncomputable def tag00EJ.β₂ {f : γ → R} (r : Π i, loc R (powers (f i))) (j k : γ) : loc R (powers (f j * f k)) := localize_more_right (f j) (f k) (r k) open tag00EJ lemma localize_more_left_eq (f g x : R) (n : ℕ) : localize_more_left f g ⟦⟨x, ⟨f^n, n, rfl⟩⟩⟧ = ⟦⟨x * g^n, (f * g)^n, n, rfl⟩⟧ := begin let h, show ⟦_⟧ * classical.some h = ⟦_⟧, have := some_spec h, rw ← quotient.out_eq (some h) at *, rcases out (some h) with ⟨s₁, s₂, hs⟩, intro this, rcases quotient.exact this with ⟨r, hr₁, hr₂⟩, refine quot.sound ⟨r, hr₁, _⟩, rw [sub_mul, sub_eq_zero_iff_eq] at hr₂, have hr₂' : s₂ * r = f ^ n * s₁ * r, { simpa using hr₂ }, suffices : (s₂ * (x * g ^ n) - ((f * g) ^ n * (x * s₁))) * r = 0, { rw ← this, simp }, simp only [sub_mul, mul_pow, mul_assoc, mul_left_comm s₂, mul_comm r, mul_left_comm r, hr₂'], ring end lemma localize_more_right_eq (f g x : R) (n : ℕ) : localize_more_right f g ⟦⟨x, ⟨g^n, n, rfl⟩⟩⟧ = ⟦⟨x * f^n, (f * g)^n, n, rfl⟩⟧ := begin let h, show ⟦_⟧ * classical.some h = ⟦_⟧, have := some_spec h, rw ← quotient.out_eq (some h) at *, rcases out (some h) with ⟨s₁, s₂, hs⟩, intro this, rcases quotient.exact this with ⟨r, hr₁, hr₂⟩, refine quot.sound ⟨r, hr₁, _⟩, rw [sub_mul, sub_eq_zero_iff_eq] at hr₂, have hr₂' : s₂ * r = g ^ n * s₁ * r, { simpa using hr₂ }, suffices : (s₂ * (x * f ^ n) - ((f * g) ^ n * (x * s₁))) * r = 0, { rw ← this, simp }, simp only [sub_mul, mul_pow, mul_assoc, mul_left_comm s₂, mul_comm r, mul_left_comm r, hr₂'], ring end lemma lemma_standard_covering₁ {f : γ → R} (h : (1 : R) ∈ span (↑(univ.image f) : set R)) : function.injective (α f) := @is_ring_hom.inj_of_kernel_eq_zero _ _ _ _ (α f) (@indexed_product.is_ring_hom _ _ _ _ _ (α f) (λ i, by unfold α; apply_instance)) begin assume x hx, replace hx := congr_fun hx, have : ∀ i, ∃ e : ℕ, f i ^ e * x = 0 := λ i, begin rcases (quotient.eq.1 (hx i)) with ⟨r, hr₁, hr₂⟩, cases hr₁ with e he, have : x * r = 0 := by simpa using hr₂, exact ⟨e, by rwa [mul_comm, he]⟩ end, let e : γ → ℕ := λ i, classical.some (this i), have he : ∀ i, f i ^ e i * x = 0 := λ i, some_spec (this i), cases exists_sum_iff_mem_span_image_finset.1 (one_mem_span_pow_of_mem_span e h) with r hr, rw [← one_mul x, hr, sum_mul, ← @sum_const_zero _ _ (univ : finset γ)], refine finset.sum_congr rfl (λ i _, _), rw [smul_eq_mul, mul_assoc, he, mul_zero], end lemma lemma_standard_covering₂ (f : γ → R) (H : (1:R) ∈ span (↑(univ.image f) : set R)) (s : Π i, loc R (powers (f i))) : β s = 0 ↔ ∃ r : R, α f r = s := ⟨λ h : β s = 0, let t := λ i, out (s i) in let r := λ i, some (t i).2.2 in have hst : ∀ i, s i = ⟦⟨(t i).1, (f i) ^ (r i), r i, rfl⟩⟧ := λ i, by simp [r, some_spec (t i).2.2], have hi : ∀ i, s i = ⟦⟨(t i).1, (t i).2.1, (t i).2.2⟩⟧ := λ i, by simp, have hβ : _ := λ i j, sub_eq_zero_iff_eq.1 $ show β s i j = 0, by rw h; refl, have hβ : ∀ i j, (⟦⟨(t i).1 * f j ^ r i, ⟨(f i * f j) ^ r i, r i, rfl⟩⟩⟧ : loc R (powers (f i * f j))) = ⟦⟨(t j).1 * f i ^ r j, ⟨(f i * f j) ^ r j, r j, rfl⟩⟩⟧ := by conv at hβ in (_ = _) {rw [hst, hst, localize_more_left_eq, localize_more_right_eq] }; exact hβ, have ∀ i j, ∃ n, ((f i * f j) ^ r i * ((t j).1 * f i ^ r j) - ((f i * f j) ^ r j * ((t i).1 * f j ^ r i))) * (f i * f j) ^ n = 0 := λ i j, let ⟨t, ⟨n, hn⟩, hnt⟩ := quotient.exact (hβ i j) in ⟨n, by rw hn; exact hnt⟩, let n := λ i j, some (this i j) + r i + r j in have hn : ∀ i j, (f i ^ r i * (t j).1 - f j ^ r j * (t i).1) * (f i * f j) ^ n i j = 0 := λ i j, by rw [← zero_mul (f i ^ r i), ← zero_mul (f j ^ r j), ← some_spec (this i j)]; simp [n, pow_add, mul_pow]; ring, let N := finset.sum (univ : finset (_ × _)) (λ ij, n ij.1 ij.2) in have Nlt : ∀ i j, n i j ≤ N := λ i j, @single_le_sum _ _ _ (λ h : γ × γ, n h.1 h.2) _ _ (λ _ _, nat.zero_le _) _ (mem_univ (i, j)), have hN : ∀ i j, (f i ^ r i * (t j).1 - f j ^ r j * (t i).1) * (f i * f j) ^ N = 0 := λ i j, begin rw [← nat.sub_add_cancel (Nlt i j), ← zero_mul ((f i * f j) ^ (N - n i j)), ← hn i j, pow_add _ (N - n i j), mul_pow, mul_pow], simp [mul_add, add_mul, mul_comm, mul_left_comm, mul_assoc], end, let ⟨a, ha⟩ := exists_sum_iff_mem_span_image_finset.1 (one_mem_span_pow_of_mem_span (λ i, N + r i) H) in ⟨univ.sum (λ j, a j * (f j) ^ N * (t j).1), funext (λ i, (hst i).symm ▸ quot.sound ⟨(f i) ^ N, ⟨N, rfl⟩, have (λ j, f i ^ r i * (a j * f j ^ N * (t j).fst) * f i ^ N) = (λ j, (a j • (f j) ^ (N + r j) * (t i).1) * (f i) ^ N) := funext (λ j, begin rw [← sub_eq_zero_iff_eq, smul_eq_mul], simp only [mul_assoc, mul_left_comm _ (a j)], rw [← mul_sub], suffices : (f i ^ r i * (f j ^ N * ((t j).fst * f i ^ N))) - (f j ^ (N + r j) * ((t i).fst * f i ^ N)) = 0, { rw [this, mul_zero] }, rw ← hN i j, simp [pow_add, mul_pow], ring, end), begin suffices : ((t i).fst - (f i ^ r i * sum univ (λ j, a j * f j ^ N * (t j).1))) * f i ^ N = 0, simpa using this, rw [mul_sum, sub_mul, sum_mul, this, ← sum_mul, ← sum_mul, ← ha, one_mul, sub_self] end⟩)⟩, λ ⟨r, hr⟩, hr ▸ show β (α f r) = λ i j, 0, from funext $ λ i, funext $ λ j, sub_eq_zero_iff_eq.2 $ loc_commutes _ _ _⟩
bb0a54b37c8f74e79cb7b28834e4fb9b5aca12d8
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/metric_space/cau_seq_filter.lean
05f615ea49ffe37fa471f9059deaa99bb9abd213
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
19,658
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Sébastien Gouëzel Characterize completeness of metric spaces in terms of Cauchy sequences. In particular, reconcile the filter notion of Cauchy-ness with the cau_seq notion on normed spaces. -/ import topology.uniform_space.basic analysis.normed_space.basic data.real.cau_seq analysis.specific_limits import tactic.linarith universes u v open set filter classical emetric open_locale topological_space variable {β : Type v} /- We show that a metric space in which all Cauchy sequences converge is complete, i.e., all Cauchy filters converge. For this, we approximate any Cauchy filter by a Cauchy sequence, taking advantage of the fact that there is a sequence tending to `0` in ℝ. The proof also gives a more precise result, that to get completeness it is enough to have the convergence of all sequence that are Cauchy in a fixed quantitative sense, for instance satisfying `dist (u n) (u m) < 2^{- min m n}`. The classical argument to obtain this criterion is to start from a Cauchy sequence, extract a subsequence that satisfies this property, deduce the convergence of the subsequence, and then the convergence of the original sequence. All this argument is completely bypassed by the following proof, which avoids any use of subsequences and is written partly in terms of filters. -/ namespace ennreal /-In this paragraph, we prove useful properties of the sequence `half_pow n := 2^{-n}` in ennreal. Some of them are instrumental in this file to get Cauchy sequences, but others are proved here only for use in further applications of the completeness criterion `emetric.complete_of_convergent_controlled_sequences` below. -/ /-- An auxiliary positive sequence that tends to `0` in `ennreal`, with good behavior. -/ noncomputable def half_pow (n : ℕ) : ennreal := ennreal.of_real ((1 / 2) ^ n) lemma half_pow_pos (n : ℕ) : 0 < half_pow n := begin have : (0 : real) < (1/2)^n := pow_pos (by norm_num) _, simpa [half_pow] using this end lemma half_pow_tendsto_zero : tendsto (λn, half_pow n) at_top (𝓝 0) := begin unfold half_pow, rw ← ennreal.of_real_zero, apply ennreal.tendsto_of_real, exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) end lemma half_pow_add_succ (n : ℕ) : half_pow (n+1) + half_pow (n+1) = half_pow n := begin have : (0 : real) ≤ (1/2)^(n+1) := (le_of_lt (pow_pos (by norm_num) _)), simp only [half_pow, eq.symm (ennreal.of_real_add this this)], apply congr_arg, simp only [pow_add, one_div_eq_inv, pow_one], ring, end lemma half_pow_mono (m k : ℕ) (h : m ≤ k) : half_pow k ≤ half_pow m := ennreal.of_real_le_of_real (pow_le_pow_of_le_one (by norm_num) (by norm_num) h) lemma edist_le_two_mul_half_pow [emetric_space β] {k l N : ℕ} (hk : N ≤ k) (hl : N ≤ l) {u : ℕ → β} (h : ∀n, edist (u n) (u (n+1)) ≤ half_pow n) : edist (u k) (u l) ≤ 2 * half_pow N := begin have ineq_rec : ∀m, ∀k≥m, half_pow k + edist (u m) (u (k+1)) ≤ 2 * half_pow m, { assume m, refine nat.le_induction _ (λk km hk, _), { calc half_pow m + edist (u m) (u (m+1)) ≤ half_pow m + half_pow m : add_le_add_left' (h m) ... = 2 * half_pow m : by simp [(mul_two _).symm, mul_comm] }, { calc half_pow (k + 1) + edist (u m) (u (k + 1 + 1)) ≤ half_pow (k+1) + (edist (u m) (u (k+1)) + edist (u (k+1)) (u (k+2))) : add_le_add_left' (edist_triangle _ _ _) ... ≤ half_pow (k+1) + (edist (u m) (u (k+1)) + half_pow (k+1)) : add_le_add_left' (add_le_add_left' (h (k+1))) ... = (half_pow(k+1) + half_pow(k+1)) + edist (u m) (u (k+1)) : by simp [add_comm] ... = half_pow k + edist (u m) (u (k+1)) : by rw half_pow_add_succ ... ≤ 2 * half_pow m : hk }}, have Imk : ∀m, ∀k≥m, edist (u m) (u k) ≤ 2 * half_pow m, { assume m k hk, by_cases h : m = k, { simp [h, le_of_lt (half_pow_pos k)] }, { have I : m < k := lt_of_le_of_ne hk h, have : 0 < k := lt_of_le_of_lt (nat.zero_le _) ‹m < k›, let l := nat.pred k, have : k = l+1 := (nat.succ_pred_eq_of_pos ‹0 < k›).symm, rw this, have : m ≤ l := begin rw this at I, apply nat.le_of_lt_succ I end, calc edist (u m) (u (l+1)) ≤ half_pow l + edist (u m) (u (l+1)) : le_add_left (le_refl _) ... ≤ 2 * half_pow m : ineq_rec m l ‹m ≤ l› }}, by_cases h : k ≤ l, { calc edist (u k) (u l) ≤ 2 * half_pow k : Imk k l h ... ≤ 2 * half_pow N : canonically_ordered_semiring.mul_le_mul (le_refl _) (half_pow_mono N k hk) }, { simp at h, calc edist (u k) (u l) = edist (u l) (u k) : edist_comm _ _ ... ≤ 2 * half_pow l : Imk l k (le_of_lt h) ... ≤ 2 * half_pow N : canonically_ordered_semiring.mul_le_mul (le_refl _) (half_pow_mono N l hl) } end lemma cauchy_seq_of_edist_le_half_pow [emetric_space β] {u : ℕ → β} (h : ∀n, edist (u n) (u (n+1)) ≤ half_pow n) : cauchy_seq u := begin refine emetric.cauchy_seq_iff_le_tendsto_0.2 ⟨λn:ℕ, 2 * half_pow n, ⟨_, _⟩⟩, { exact λk l N hk hl, edist_le_two_mul_half_pow hk hl h }, { have : tendsto (λn, 2 * half_pow n) at_top (𝓝 (2 * 0)) := ennreal.tendsto_mul_right half_pow_tendsto_zero (by simp), simpa using this } end end ennreal namespace sequentially_complete section /- We fix a cauchy filter `f`, and a bounding sequence `B` made of positive numbers. We will prove that, if all sequences satisfying `dist (u n) (u m) < B (min n m)` converge, then the cauchy filter `f` is converging. The idea is to construct from `f` a Cauchy sequence that satisfies this property, therefore converges, and then to deduce the convergence of `f` from this. We give the argument in the more general setting of emetric spaces, and specialize it to metric spaces at the end. -/ variables [emetric_space β] {f : filter β} (hf : cauchy f) (B : ℕ → ennreal) (hB : ∀n, 0 < B n) open ennreal /--Auxiliary sequence, which is bounded by `B`, positive, and tends to `0`.-/ noncomputable def B2 (B : ℕ → ennreal) (n : ℕ) := (half_pow n) ⊓ (B n) lemma B2_pos (hB : ∀n, 0 < B n) (n : ℕ) : 0 < B2 B n := by unfold B2; simp [half_pow_pos n, hB n] lemma B2_lim : tendsto (λn, B2 B n) at_top (𝓝 0) := begin have : ∀n, B2 B n ≤ half_pow n := λn, lattice.inf_le_left, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds half_pow_tendsto_zero (by simp) (by simp [this]) end /-- Define a decreasing sequence of sets in the filter `f`, of diameter bounded by `B2 n`. -/ def set_seq_of_cau_filter : ℕ → set β | 0 := some ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0)) | (n+1) := (set_seq_of_cau_filter n) ∩ some ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n + 1))) /-- These sets are in the filter. -/ lemma set_seq_of_cau_filter_mem_sets : ∀ n, set_seq_of_cau_filter hf B hB n ∈ f | 0 := some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0))) | (n+1) := inter_mem_sets (set_seq_of_cau_filter_mem_sets n) (some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n + 1))))) /-- These sets are nonempty. -/ lemma set_seq_of_cau_filter_inhabited (n : ℕ) : ∃ x, x ∈ set_seq_of_cau_filter hf B hB n := inhabited_of_mem_sets (emetric.cauchy_iff.1 hf).1 (set_seq_of_cau_filter_mem_sets hf B hB n) /-- By construction, their diameter is controlled by `B2 n`. -/ lemma set_seq_of_cau_filter_spec : ∀ n, ∀ {x y}, x ∈ set_seq_of_cau_filter hf B hB n → y ∈ set_seq_of_cau_filter hf B hB n → edist x y < B2 B n | 0 := some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0))) | (n+1) := λ x y hx hy, some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n+1)))) x y (mem_of_mem_inter_right hx) (mem_of_mem_inter_right hy) -- this must exist somewhere, no? private lemma mono_of_mono_succ_aux {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) (m : ℕ) : ∀ n, f (m + n) ≤ f m | 0 := le_refl _ | (k+1) := le_trans (h _) (mono_of_mono_succ_aux _) lemma mono_of_mono_succ {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) {m n : ℕ} (hmn : m ≤ n) : f n ≤ f m := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in by simpa [hk] using mono_of_mono_succ_aux f h m k lemma set_seq_of_cau_filter_monotone' (n : ℕ) : set_seq_of_cau_filter hf B hB (n+1) ⊆ set_seq_of_cau_filter hf B hB n := inter_subset_left _ _ /-- These sets are nested. -/ lemma set_seq_of_cau_filter_monotone {n k : ℕ} (hle : n ≤ k) : set_seq_of_cau_filter hf B hB k ⊆ set_seq_of_cau_filter hf B hB n := mono_of_mono_succ (set_seq_of_cau_filter hf B hB) (set_seq_of_cau_filter_monotone' hf B hB) hle /-- Define the approximating Cauchy sequence for the Cauchy filter `f`, obtained by taking a point in each set. -/ noncomputable def seq_of_cau_filter (n : ℕ) : β := some (set_seq_of_cau_filter_inhabited hf B hB n) /-- The approximating sequence indeed belong to our good sets. -/ lemma seq_of_cau_filter_mem_set_seq (n : ℕ) : seq_of_cau_filter hf B hB n ∈ set_seq_of_cau_filter hf B hB n := some_spec (set_seq_of_cau_filter_inhabited hf B hB n) /-- The distance between points in the sequence is bounded by `B2 N`. -/ lemma seq_of_cau_filter_bound {N n k : ℕ} (hn : N ≤ n) (hk : N ≤ k) : edist (seq_of_cau_filter hf B hB n) (seq_of_cau_filter hf B hB k) < B2 B N := set_seq_of_cau_filter_spec hf B hB N (set_seq_of_cau_filter_monotone hf B hB hn (seq_of_cau_filter_mem_set_seq hf B hB n)) (set_seq_of_cau_filter_monotone hf B hB hk (seq_of_cau_filter_mem_set_seq hf B hB k)) /-- The approximating sequence is indeed Cauchy as `B2 n` tends to `0` with `n`. -/ lemma seq_of_cau_filter_is_cauchy : cauchy_seq (seq_of_cau_filter hf B hB) := emetric.cauchy_seq_iff_le_tendsto_0.2 ⟨B2 B, λ n m N hn hm, le_of_lt (seq_of_cau_filter_bound hf B hB hn hm), B2_lim B⟩ /-- If the approximating Cauchy sequence is converging, to a limit `y`, then the original Cauchy filter `f` is also converging, to the same limit. Given `t1` in the filter `f` and `t2` a neighborhood of `y`, it suffices to show that `t1 ∩ t2` is nonempty. Pick `ε` so that the ε-eball around `y` is contained in `t2`. Pick `n` with `B2 n < ε/2`, and `n2` such that `dist(seq n2, y) < ε/2`. Let `N = max(n, n2)`. We defined `seq` by looking at a decreasing sequence of sets of `f` with shrinking radius. The Nth one has radius `< B2 N < ε/2`. This set is in `f`, so we can find an element `x` that's also in `t1`. `dist(x, seq N) < ε/2` since `seq N` is in this set, and `dist (seq N, y) < ε/2`, so `x` is in the ε-ball around `y`, and thus in `t2`. -/ lemma le_nhds_cau_filter_lim {y : β} (H : tendsto (seq_of_cau_filter hf B hB) at_top (𝓝 y)) : f ≤ 𝓝 y := begin refine (le_nhds_iff_adhp_of_cauchy hf).2 _, refine forall_sets_neq_empty_iff_neq_bot.1 (λs hs, _), rcases filter.mem_inf_sets.2 hs with ⟨t1, ht1, t2, ht2, ht1t2⟩, rcases emetric.mem_nhds_iff.1 ht2 with ⟨ε, hε, ht2'⟩, cases emetric.cauchy_iff.1 hf with hfb _, have : ε / 2 > 0 := ennreal.half_pos hε, rcases inhabited_of_mem_sets (by simp) ((tendsto_orderable.1 (B2_lim B)).2 _ this) with ⟨n, hnε⟩, simp only [set.mem_set_of_eq] at hnε, -- hnε : ε / 2 > B2 B hB n cases (emetric.tendsto_at_top _).1 H _ this with n2 hn2, let N := max n n2, have ht1sn : t1 ∩ set_seq_of_cau_filter hf B hB N ∈ f, from inter_mem_sets ht1 (set_seq_of_cau_filter_mem_sets hf B hB _), have hts1n_ne : t1 ∩ set_seq_of_cau_filter hf B hB N ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.2 hfb _ ht1sn, cases exists_mem_of_ne_empty hts1n_ne with x hx, -- x : β, hx : x ∈ t1 ∩ set_seq_of_cau_filter hf B hB N -- we still have to show that x ∈ t2, i.e., edist x y < ε have I1 : seq_of_cau_filter hf B hB N ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) (seq_of_cau_filter_mem_set_seq hf B hB N), have I2 : x ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) hx.2, have hdist1 : edist x (seq_of_cau_filter hf B hB N) < B2 B n := set_seq_of_cau_filter_spec hf B hB _ I2 I1, have hdist2 : edist (seq_of_cau_filter hf B hB N) y < ε / 2 := hn2 N (le_max_right _ _), have hdist : edist x y < ε := calc edist x y ≤ edist x (seq_of_cau_filter hf B hB N) + edist (seq_of_cau_filter hf B hB N) y : edist_triangle _ _ _ ... < B2 B n + ε/2 : ennreal.add_lt_add hdist1 hdist2 ... ≤ ε/2 + ε/2 : add_le_add_right' (le_of_lt hnε) ... = ε : ennreal.add_halves _, have hxt2 : x ∈ t2, from ht2' hdist, exact ne_empty_iff_exists_mem.2 ⟨x, ht1t2 (mem_inter hx.left hxt2)⟩ end end end sequentially_complete /-- An emetric space in which every Cauchy sequence converges is complete. -/ theorem complete_of_cauchy_seq_tendsto {α : Type u} [emetric_space α] (H : ∀u : ℕ → α, cauchy_seq u → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f` intros f hf, -- Introduce a sequence `u` approximating the filter `f`. We don't need the bound `B`, -- so take for instance `B n = 1` for all `n`. let u := sequentially_complete.seq_of_cau_filter hf (λn, 1) (λn, ennreal.zero_lt_one), -- It is Cauchy. have : cauchy_seq u := sequentially_complete.seq_of_cau_filter_is_cauchy hf (λn, 1) (λn, ennreal.zero_lt_one), -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf (λn, 1) (λn, ennreal.zero_lt_one) hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem emetric.complete_of_convergent_controlled_sequences {α : Type u} [emetric_space α] (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f`. intros f hf, -- Introduce a sequence `u` approximating the filter `f`. let u := sequentially_complete.seq_of_cau_filter hf B hB, -- It satisfies the required bound. have : ∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N := λN n m hn hm, calc edist (u n) (u m) < sequentially_complete.B2 B N : sequentially_complete.seq_of_cau_filter_bound hf B hB hn hm ... ≤ B N : lattice.inf_le_right, -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf B hB hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences {α : Type u} [metric_space α] (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, have Z := Hu N n m hn hm, rw [edist_dist, ennreal.of_real_lt_of_real_iff] at Z, exact Z, exact hB N } end section /- Now, we will apply these results to `cau_seq`, i.e., "Cauchy sequences" defined by a multiplicative absolute value on normed fields. -/ lemma tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)] (f : cau_seq β norm) [cau_seq.is_complete β norm] : tendsto f at_top (𝓝 f.lim) := _root_.tendsto_nhds.mpr begin intros s os lfs, suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this, rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩, cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN, existsi N, intros b hb, apply hεs, dsimp [metric.ball], rw [dist_comm, dist_eq_norm], solve_by_elim end variables [normed_field β] /- This section shows that if we have a uniform space generated by an absolute value, topological completeness and Cauchy sequence completeness coincide. The problem is that there isn't a good notion of "uniform space generated by an absolute value", so right now this is specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_field. This needs to be fixed, since it prevents showing that ℤ_[hp] is complete -/ instance normed_field.is_absolute_value : is_absolute_value (norm : β → ℝ) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_triangle, abv_mul := normed_field.norm_mul } open metric lemma cauchy_of_filter_cauchy (f : ℕ → β) (hf : cauchy_seq f) : is_cau_seq norm f := begin cases cauchy_iff.1 hf with hf1 hf2, intros ε hε, rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩, simp at ht, cases ht with N hN, existsi N, intros j hj, rw ←dist_eq_norm, apply @htsub (f j, f N), apply set.mk_mem_prod; solve_by_elim [le_refl] end lemma filter_cauchy_of_cauchy (f : cau_seq β norm) : cauchy_seq f := begin apply cauchy_iff.2, split, { exact map_ne_bot at_top_ne_bot }, { intros s hs, rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩, cases cau_seq.cauchy₂ f hε with N hN, existsi {n | n ≥ N}.image f, simp, split, { existsi N, intros b hb, existsi b, simp [hb] }, { rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩, dsimp at ha'1 ha'2 hb'1 hb'2, rw [←ha'2, ←hb'2], apply hεs, rw dist_eq_norm, apply hN; assumption }}, end /-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/ lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} : is_cau_seq norm u ↔ cauchy_seq u := ⟨λh, filter_cauchy_of_cauchy ⟨u, h⟩, λh, cauchy_of_filter_cauchy u h⟩ /-- A complete normed field is complete as a metric space, as Cauchy sequences converge by assumption and this suffices to characterize completeness. -/ instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β := begin apply complete_of_cauchy_seq_tendsto, assume u hu, have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu, existsi cau_seq.lim ⟨u, C⟩, rw metric.tendsto_at_top, assume ε εpos, cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN, existsi N, simpa [dist_eq_norm] using hN end end
675c09db42fa99790a84447db47e070b68c54d01
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/termParserAttr.lean
018c0b020fe27cb5841851dcf1fe6822d997946f
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,788
lean
import Init.Lean open Lean open Lean.Elab def run (input : String) (failIff : Bool := true) : MetaIO Unit := do env ← MetaIO.getEnv; opts ← MetaIO.getOptions; (env, messages) ← liftM $ process input env opts; messages.toList.forM $ fun msg => IO.println msg; when (failIff && messages.hasErrors) $ throw (IO.userError "errors have been found"); when (!failIff && !messages.hasErrors) $ throw (IO.userError "there are no errors"); pure () open Lean.Parser @[termParser] def tst := parser! "(|" >> termParser >> optional (symbolAux ", " >> termParser) >> "|)" @[termParser] def boo : ParserDescr := ParserDescr.node `boo (ParserDescr.andthen (ParserDescr.symbol "[|" (some 0)) (ParserDescr.andthen (ParserDescr.parser `term 0) (ParserDescr.symbol "|]" (some 0)))) open Lean.Elab.Term @[termElab tst] def elabTst : TermElab := adaptExpander $ fun stx => match_syntax stx with | `((| $e |)) => pure e | _ => throwUnsupportedSyntax @[termElab boo] def elabBoo : TermElab := fun stx expected? => elabTerm (stx.getArg 1) expected? #eval run "#check [| @id.{1} Nat |]" #eval run "#check (| id 1 |)" -- #eval run "#check (| id 1, id 1 |)" -- it will fail @[termElab tst] def elabTst2 : TermElab := adaptExpander $ fun stx => match_syntax stx with | `((| $e1, $e2 |)) => `(($e1, $e2)) | _ => throwUnsupportedSyntax -- Now both work #eval run "#check (| id 1 |)" #eval run "#check (| id 1, id 2 |)" new_frontend declare_syntax_cat foo syntax "⟨|" term "|⟩" : foo syntax term : foo syntax term ">>>" term : foo syntax [tst3] "FOO " foo : term macro_rules | `(FOO ⟨| $t |⟩) => `($t+1) | `(FOO $t) => `($t) | `(FOO $t >>> $r) => `($t * $r) #check FOO ⟨| id 1 |⟩ #check FOO 1 #check FOO 1 >>> 2
176486dbaba053caabec8ed8eea6c16bdd2fc1ba
74d9d5f45c6ce5c4f2faf215c04a68eab55fe525
/src/differentiability/continuity.lean
6e7a3df7abe3e3933a52dca85888803e5faa1eff
[]
no_license
joshpoll/differential_geometry
290bb8a934ca3b3b6b707d810e6d4b941710b710
57e00a7e37b7c4c73c847429171ff63d3a48def5
refs/heads/master
1,584,551,626,391
1,527,747,643,000
1,527,747,643,000
135,014,993
1
0
null
null
null
null
UTF-8
Lean
false
false
448
lean
import order.filter analysis.topology.continuity analysis.real .normed_space local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b) variables {k : Type*} [normed_field k] variables {E : Type*} [normed_space k E] variables {F : Type*} [normed_space k F] variables {G : Type*} [normed_space k G] include k def is_ptws_cont (f : E → F) (a : E) := f →_{a} (f a) -- TODO: pointwise continuous everywhere ↔ continuous
121cd93d87716f38b77859d5a1074ac90e464b57
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/meta6.lean
162708022c299a0d1d85611fa52ee35ba06ca89c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,523
lean
import Lean.Meta open Lean open Lean.Meta def print (msg : MessageData) : MetaM Unit := do trace[Meta.debug] msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def nat := mkConst `Nat def boolE := mkConst `Bool def succ := mkConst `Nat.succ def zero := mkConst `Nat.zero def add := mkConst `Nat.add def io := mkConst `IO def type := mkSort levelOne def mkArrow (d b : Expr) : Expr := mkForall `_ BinderInfo.default d b def tst1 : MetaM Unit := do print "----- tst1 -----"; let m1 ← mkFreshExprMVar (mkArrow nat nat); let lhs := mkApp m1 zero; let rhs := zero; checkM $ fullApproxDefEq $ isDefEq lhs rhs; pure () set_option pp.all true #eval tst1 set_option trace.Meta.debug true def tst2 : MetaM Unit := do print "----- tst2 -----"; let ps ← getParamNames `Or.casesOn; print (toString ps); let ps ← getParamNames `Iff.rec; print (toString ps); let ps ← getParamNames `checkM; print (toString ps); pure () #eval tst2 axiom t1 : [Unit] = [] axiom t2 : 0 > 5 def tst3 : MetaM Unit := do let env ← getEnv; let t2 ← getConstInfo `t2; let c ← mkNoConfusion t2.type (mkConst `t1); print c; check c; let cType ← inferType c; print cType; let lt ← mkLt (mkNatLit 10000000) (mkNatLit 20000000000); let ltPrf ← mkDecideProof lt; check ltPrf; let t ← inferType ltPrf; print t; pure () #eval tst3 inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n : Nat} : α → Vec α n → Vec α (n+1) def tst4 : MetaM Unit := withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let vType ← mkAppM `Vec #[nat, x]; withLocalDeclD `v vType fun v => do let m ← mkFreshExprSyntheticOpaqueMVar vType; let subgoals ← caseValues m.mvarId! x.fvarId! #[mkNatLit 2, mkNatLit 3, mkNatLit 5]; subgoals.forM fun s => do { print (MessageData.ofGoal s.mvarId); assumption s.mvarId }; let t ← instantiateMVars m; print t; check t; pure () #eval tst4 def tst5 : MetaM Unit := do let arrayNat ← mkAppM `Array #[nat]; withLocalDeclD `a arrayNat fun a => do withLocalDeclD `b arrayNat fun b => do let motiveType := _root_.mkArrow arrayNat (mkSort levelZero); withLocalDeclD `motive motiveType fun motive => do let mvarType := mkApp motive a; let mvar ← mkFreshExprSyntheticOpaqueMVar mvarType; let subgoals ← caseArraySizes mvar.mvarId! a.fvarId! #[1, 0, 4, 5]; subgoals.forM fun s => do { print (MessageData.ofGoal s.mvarId); pure () }; pure () set_option trace.Meta.synthInstance false #eval tst5
ee31154fce49fd63ead619ab879de148be4c6539
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/widget/interactive_expr.lean
223c569b5c4b4d4bf1779b1b018ea2d874da9788
[ "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
10,709
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ prelude import init.meta.widget.basic import init.meta.widget.tactic_component import init.meta.tagged_format import init.data.punit import init.meta.mk_dec_eq_instance meta def subexpr := (expr × expr.address) namespace widget open tagged_format open html attr namespace interactive_expression /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf meta def sf.repr : sf → format | (sf.tag_expr addr e a) := format.group $ format.nest 2 $ "(tag_expr " ++ to_fmt addr ++ format.line ++ "`(" ++ to_fmt e ++ ")" ++ format.line ++ a.repr ++ ")" | (sf.compose a b) := a.repr ++ format.line ++ b.repr | (sf.of_string s) := repr s meta instance : has_to_format sf := ⟨sf.repr⟩ meta instance : has_to_string sf := ⟨λ s, s.repr.to_string⟩ meta instance : has_repr sf := ⟨λ s, s.repr.to_string⟩ meta def sf.of_eformat : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ sf.of_eformat m | (group m) := sf.of_eformat m | (nest i m) := sf.of_eformat m | (highlight i m) := sf.of_eformat m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (sf.of_eformat x) (sf.of_eformat y) meta def sf.flatten : sf → sf | (sf.tag_expr e ea m) := (sf.tag_expr e ea $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := sf.of_string s meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), pure [tooltip $ h "div" [] [ h "button" [cn "fr pointer ba br3", on_click (λ _, action.on_close_tooltip)] ["x"], content ]] else pure [], let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_should_update (λ (x y : tactic_state × expr × expr.address), x.2.2 ≠ y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some g) | (action.on_close_tooltip) := ((none, sa), none) end ) (λ e ⟨ca, sa⟩, do ts ← tactic.read, let m : sf := sf.flatten $ sf.of_eformat $ tactic_state.pp_tagged ts e, let m : sf := sf.tag_expr [] e m, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [] [ h "div" [] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) /-- Group consecutive locals according to whether they have the same type -/ meta def to_local_collection : list local_collection → list expr → tactic (list local_collection) | acc [] := pure $ list.map (λ lc : local_collection, {locals := lc.locals.reverse, ..lc}) $ list.reverse $ acc | acc (l::ls) := do l_type ← infer_type l, (do (⟨k,ns,t⟩::acc) ← pure acc, is_def_eq t l_type, to_local_collection (⟨k,l::ns,t⟩::acc) ls) <|> (to_local_collection (⟨to_string $ expr.local_uniq_name $ l, [l], l_type⟩::acc) ls) /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, t ← get_tag g, let case_tag : list (html γ) := match interactive.case_tag.parse t with | some t := [h "li" [key "_case"] $ [h "span" [cn "goal-case b"] ["case"]] ++ (t.case_names.bind $ λ n, [" ", n])] | none := [] end, lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← to_local_collection [] lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, ns ← pure $ lc.locals.map (λ n, h "span" [cn "goal-hyp b pr2"] [html.of_name $ expr.local_pp_name n]), pure $ h "li" [key lc.key] (ns ++ [": ", h "span" [cn "goal-hyp-type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ case_tag ++ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message := if gs.length = 0 then "goals accomplished" else if gs.length = 1 then "1 goal" else to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, h "li" [className $ "lh-copy mt2", key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, pure [c] ) meta def tactic_render : tc unit empty := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component meta def tactic_state_widget : component tactic_state empty := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state empty := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget
4dbed7526f311a107d493ac26af48c4dbdcd7f33
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/def12.lean
43b1565e70a10c2ced20096f4e4789ad7e5d150b
[ "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
1,119
lean
new_frontend def diag : Bool → Bool → Bool → Nat | b, true, false => 1 | false, b, true => 2 | true, false, b => 3 | b1, b2, b3 => arbitrary Nat theorem diag1 (a : Bool) : diag a true false = 1 := match a with | true => rfl | false => rfl theorem diag2 (a : Bool) : diag false a true = 2 := by cases a; exact rfl; exact rfl theorem diag3 (a : Bool) : diag true false a = 3 := by cases a; exact rfl; exact rfl theorem diag4_1 : diag false false false = arbitrary Nat := rfl theorem diag4_2 : diag true true true = arbitrary Nat := rfl def f : Nat → Nat → Nat | n, 0 => 0 | 0, n => 1 | n, m => arbitrary Nat theorem f_zero_right : (a : Nat) → f a 0 = 0 | 0 => rfl | a+1 => rfl theorem f_zero_succ (a : Nat) : f 0 (a+1) = 1 := rfl theorem f_succ_succ (a b : Nat) : f (a+1) (b+1) = arbitrary Nat := rfl def app {α} : List α → List α → List α | [], l => l | h::t, l => h :: (app t l) theorem app_nil {α} (l : List α) : app [] l = l := rfl theorem app_cons {α} (h : α) (t l : List α) : app (h :: t) l = h :: (app t l) := rfl theorem ex : app [1, 2] [3,4,5] = [1,2,3,4,5] := rfl
c2a0576394328fd6edc1dd5367ed149b83a2f98f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic28.lean
611cef92c03a97d119c10df8924d0c7f2a0f950c
[ "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
521
lean
import logic data.num open tactic inhabited namespace foo inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited.destruct H (λ a, inhabited.mk (sum.inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited.destruct H (λ b, inhabited.mk (sum.inr A b)) theorem T : inhabited (sum false num) := inhabited.mk (sum.inr false 0) end foo
61cc0cd9a3fa75d949e6423aac0b8d2be1782282
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/948.lean
8658f3b21d2bbe59006fa671a63652d7f679e318
[ "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
490
lean
class Trait (X : Type) where R : Type class One (R : Type) where one : R attribute [reducible] Trait.R def add_one {X} [Trait X] [One (Trait.R X)] [HAdd X (Trait.R X) X] (x : X) : X := x + (One.one : (Trait.R X)) @[reducible] instance : Trait Int := ⟨Nat⟩ instance : One Nat := ⟨1⟩ instance : HAdd Int Nat Int := ⟨λ x y => x + y⟩ def add_one_to_one (x : Int) (h : x = 1) : add_one (x : Int) = (2 : Int) := by conv => pattern add_one _ trace_state rw [h]
75a1d8d198e23bb5979901580a8c2b968cd0f664
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/shapes/constructions/pullbacks.lean
652aeb874b30fd6c8d23b2340d244dcf96eeeb1d
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,865
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks universes v u /-! # Constructing pullbacks from binary products and equalizers If a category as binary products and equalizers, then it has pullbacks. Also, if a category has binary coproducts and coequalizers, then it has pushouts -/ open category_theory namespace category_theory.limits /-- If the product `X ⨯ Y` and the equalizer of `π₁ ≫ f` and `π₂ ≫ g` exist, then the pullback of `f` and `g` exists: It is given by composing the equalizer with the projections. -/ def has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair {C : Type u} [𝒞 : category.{v} C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (pair X Y)] [has_limit (parallel_pair (prod.fst ≫ f) (prod.snd ≫ g))] : has_limit (cospan f g) := let π₁ : X ⨯ Y ⟶ X := prod.fst, π₂ : X ⨯ Y ⟶ Y := prod.snd, e := equalizer.ι (π₁ ≫ f) (π₂ ≫ g) in { cone := pullback_cone.mk (e ≫ π₁) (e ≫ π₂) $ by simp only [category.assoc, equalizer.condition], is_limit := pullback_cone.is_limit.mk _ _ _ (λ s, equalizer.lift (prod.lift (s.π.app walking_cospan.left) (s.π.app walking_cospan.right)) $ by rw [←category.assoc, limit.lift_π, ←category.assoc, limit.lift_π]; exact pullback_cone.condition _) (by simp) (by simp) $ λ s m h₁ h₂, by { ext, { simpa using h₁ }, { simpa using h₂ } } } section local attribute [instance] has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair /-- If a category has all binary products and all equalizers, then it also has all pullbacks. As usual, this is not an instance, since there may be a more direct way to construct pullbacks. -/ def has_pullbacks_of_has_binary_products_of_has_equalizers (C : Type u) [𝒞 : category.{v} C] [has_binary_products C] [has_equalizers C] : has_pullbacks C := has_pullbacks_of_has_limit_cospan C end /-- If the coproduct `Y ⨿ Z` and the coequalizer of `f ≫ ι₁` and `g ≫ ι₂` exist, then the pushout of `f` and `g` exists: It is given by composing the inclusions with the coequalizer. -/ def has_colimit_span_of_has_colimit_pair_of_has_colimit_parallel_pair {C : Type u} [𝒞 : category.{v} C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (pair Y Z)] [has_colimit (parallel_pair (f ≫ coprod.inl) (g ≫ coprod.inr))] : has_colimit (span f g) := let ι₁ : Y ⟶ Y ⨿ Z := coprod.inl, ι₂ : Z ⟶ Y ⨿ Z := coprod.inr, c := coequalizer.π (f ≫ ι₁) (g ≫ ι₂) in { cocone := pushout_cocone.mk (ι₁ ≫ c) (ι₂ ≫ c) $ by rw [←category.assoc, ←category.assoc, coequalizer.condition], is_colimit := pushout_cocone.is_colimit.mk _ _ _ (λ s, coequalizer.desc (coprod.desc (s.ι.app walking_span.left) (s.ι.app walking_span.right)) $ by rw [category.assoc, colimit.ι_desc, category.assoc, colimit.ι_desc]; exact pushout_cocone.condition _) (by simp) (by simp) $ λ s m h₁ h₂, by { ext, { simpa using h₁ }, { simpa using h₂ } } } section local attribute [instance] has_colimit_span_of_has_colimit_pair_of_has_colimit_parallel_pair /-- If a category has all binary coproducts and all coequalizers, then it also has all pushouts. As usual, this is not an instance, since there may be a more direct way to construct pushouts. -/ def has_pushouts_of_has_binary_coproducts_of_has_coequalizers (C : Type u) [𝒞 : category.{v} C] [has_binary_coproducts C] [has_coequalizers C] : has_pushouts C := has_pushouts_of_has_colimit_span C end end category_theory.limits