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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
852047d935e40b35836758c828661078096174b8 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/analysis/complex/basic.lean | d3cb0d50054524c44d0584b12b54c2f1e232de2b | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,848 | lean | /-
Copyright (c) Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.times_cont_diff
import analysis.normed_space.finite_dimension
/-!
# Normed space structure on `ℂ`.
This file gathers basic facts on complex numbers of an analytic nature.
## Main results
This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives
tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`,
it defines functions:
* `continuous_linear_map.re`
* `continuous_linear_map.im`
* `continuous_linear_map.of_real`
They are bundled versions of the real part, the imaginary part, and the embedding of `ℝ` in `ℂ`,
as continuous `ℝ`-linear maps.
`has_deriv_at.real_of_complex` expresses that, if a function on `ℂ` is differentiable (over `ℂ`),
then its restriction to `ℝ` is differentiable over `ℝ`, with derivative the real part of the
complex derivative.
-/
noncomputable theory
namespace complex
instance : normed_field ℂ :=
{ norm := abs,
dist_eq := λ _ _, rfl,
norm_mul' := abs_mul,
.. complex.field }
instance : nondiscrete_normed_field ℂ :=
{ non_trivial := ⟨2, by simp [norm]; norm_num⟩ }
instance normed_algebra_over_reals : normed_algebra ℝ ℂ :=
{ norm_algebra_map_eq := abs_of_real,
..complex.algebra_over_reals }
@[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl
@[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _
@[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) :=
suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa,
by rw [norm_real, real.norm_eq_abs]
@[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _
@[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n :=
suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa,
by rw [norm_real, real.norm_eq_abs]
lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n :=
by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn
/-- Over the complex numbers, any finite-dimensional spaces is proper (and therefore complete).
We can register this as an instance, as it will not cause problems in instance resolution since
the properness of `ℂ` is already known and there is no metavariable. -/
instance finite_dimensional.proper
(E : Type) [normed_group E] [normed_space ℂ E] [finite_dimensional ℂ E] : proper_space E :=
finite_dimensional.proper ℂ E
attribute [instance, priority 900] complex.finite_dimensional.proper
/-- A complex normed vector space is also a real normed vector space. -/
@[priority 900]
instance normed_space.restrict_scalars_real (E : Type*) [normed_group E] [normed_space ℂ E] :
normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E
/-- The space of continuous linear maps over `ℝ`, from a real vector space to a complex vector
space, is a normed vector space over `ℂ`. -/
instance continuous_linear_map.real_smul_complex (E : Type*) [normed_group E] [normed_space ℝ E]
(F : Type*) [normed_group F] [normed_space ℂ F] :
normed_space ℂ (E →L[ℝ] F) :=
continuous_linear_map.normed_space_extend_scalars
/-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/
def continuous_linear_map.re : ℂ →L[ℝ] ℝ :=
linear_map.re.mk_continuous 1 $ λx, begin
change _root_.abs (x.re) ≤ 1 * abs x,
rw one_mul,
exact abs_re_le_abs x
end
@[simp] lemma continuous_linear_map.re_coe :
(coe (continuous_linear_map.re) : ℂ →ₗ[ℝ] ℝ) = linear_map.re := rfl
@[simp] lemma continuous_linear_map.re_apply (z : ℂ) :
(continuous_linear_map.re : ℂ → ℝ) z = z.re := rfl
@[simp] lemma continuous_linear_map.re_norm :
∥continuous_linear_map.re∥ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
calc 1 = ∥continuous_linear_map.re (1 : ℂ)∥ : by simp
... ≤ ∥continuous_linear_map.re∥ : by { apply continuous_linear_map.unit_le_op_norm, simp }
end
/-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/
def continuous_linear_map.im : ℂ →L[ℝ] ℝ :=
linear_map.im.mk_continuous 1 $ λx, begin
change _root_.abs (x.im) ≤ 1 * abs x,
rw one_mul,
exact complex.abs_im_le_abs x
end
@[simp] lemma continuous_linear_map.im_coe :
(coe (continuous_linear_map.im) : ℂ →ₗ[ℝ] ℝ) = linear_map.im := rfl
@[simp] lemma continuous_linear_map.im_apply (z : ℂ) :
(continuous_linear_map.im : ℂ → ℝ) z = z.im := rfl
@[simp] lemma continuous_linear_map.im_norm :
∥continuous_linear_map.im∥ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
calc 1 = ∥continuous_linear_map.im (I : ℂ)∥ : by simp
... ≤ ∥continuous_linear_map.im∥ :
by { apply continuous_linear_map.unit_le_op_norm, rw ← abs_I, exact le_refl _ }
end
/-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/
def continuous_linear_map.of_real : ℝ →L[ℝ] ℂ :=
linear_map.of_real.mk_continuous 1 $ λx, by simp
@[simp] lemma continuous_linear_map.of_real_coe :
(coe (continuous_linear_map.of_real) : ℝ →ₗ[ℝ] ℂ) = linear_map.of_real := rfl
@[simp] lemma continuous_linear_map.of_real_apply (x : ℝ) :
(continuous_linear_map.of_real : ℝ → ℂ) x = x := rfl
@[simp] lemma continuous_linear_map.of_real_norm :
∥continuous_linear_map.of_real∥ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
calc 1 = ∥continuous_linear_map.of_real (1 : ℝ)∥ : by simp
... ≤ ∥continuous_linear_map.of_real∥ :
by { apply continuous_linear_map.unit_le_op_norm, simp }
end
lemma continuous_linear_map.of_real_isometry :
isometry continuous_linear_map.of_real :=
continuous_linear_map.isometry_iff_norm_image_eq_norm.2 (λx, by simp)
end complex
section real_deriv_of_complex
/-! ### Differentiability of the restriction to `ℝ` of complex functions -/
open complex
variables {e : ℂ → ℂ} {e' : ℂ} {z : ℝ}
/-- If a complex function is differentiable at a real point, then the induced real function is also
differentiable at this point, with a derivative equal to the real part of the complex derivative. -/
theorem has_deriv_at.real_of_complex (h : has_deriv_at e e' z) :
has_deriv_at (λx:ℝ, (e x).re) e'.re z :=
begin
have A : has_fderiv_at continuous_linear_map.of_real continuous_linear_map.of_real z :=
continuous_linear_map.of_real.has_fderiv_at,
have B : has_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ)
(continuous_linear_map.of_real z) :=
(has_deriv_at_iff_has_fderiv_at.1 h).restrict_scalars ℝ,
have C : has_fderiv_at continuous_linear_map.re continuous_linear_map.re
(e (continuous_linear_map.of_real z)) := continuous_linear_map.re.has_fderiv_at,
simpa using has_fderiv_at_iff_has_deriv_at.1 (C.comp z (B.comp z A)),
end
theorem times_cont_diff_at.real_of_complex {n : with_top ℕ} (h : times_cont_diff_at ℂ n e z) :
times_cont_diff_at ℝ n (λ x : ℝ, (e x).re) z :=
begin
have A : times_cont_diff_at ℝ n continuous_linear_map.of_real z,
from continuous_linear_map.of_real.times_cont_diff.times_cont_diff_at,
have B : times_cont_diff_at ℝ n e z := h.restrict_scalars ℝ,
have C : times_cont_diff_at ℝ n continuous_linear_map.re (e z),
from continuous_linear_map.re.times_cont_diff.times_cont_diff_at,
exact C.comp z (B.comp z A)
end
theorem times_cont_diff.real_of_complex {n : with_top ℕ} (h : times_cont_diff ℂ n e) :
times_cont_diff ℝ n (λ x : ℝ, (e x).re) :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ x,
h.times_cont_diff_at.real_of_complex
end real_deriv_of_complex
|
29d758804758b08a68ffb8135d57ee82716a74a1 | 8e2026ac8a0660b5a490dfb895599fb445bb77a0 | /tests/lean/assertion1.lean | b14428f2367f7d156fbe3adc9f93b8e0832afa3f | [
"Apache-2.0"
] | permissive | pcmoritz/lean | 6a8575115a724af933678d829b4f791a0cb55beb | 35eba0107e4cc8a52778259bb5392300267bfc29 | refs/heads/master | 1,607,896,326,092 | 1,490,752,175,000 | 1,490,752,175,000 | 86,612,290 | 0 | 0 | null | 1,490,809,641,000 | 1,490,809,641,000 | null | UTF-8 | Lean | false | false | 1,266 | lean | universe variables u v
structure Category :=
(Obj : Type u)
(Hom : Obj → Obj → Type v)
universe variables u1 v1 u2 v2
structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) :=
(onObjects : C^.Obj → D^.Obj)
@[reducible] definition ProductCategory (C : Category) (D : Category) :
Category :=
{
Obj := C^.Obj × D^.Obj,
Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd))
}
namespace ProductCategory
notation C `×` D := ProductCategory C D
end ProductCategory
@[reducible] definition TensorProduct ( C: Category ) := Functor ( C × C ) C
structure MonoidalCategory
extends carrier : Category :=
(tensor : TensorProduct carrier)
instance MonoidalCategory_coercion : has_coe MonoidalCategory Category :=
⟨MonoidalCategory.to_Category⟩
-- Convenience methods which take two arguments, rather than a pair. (This seems to often help the elaborator avoid getting stuck on `prod.mk`.)
@[reducible] definition MonoidalCategory.tensorObjects { C : MonoidalCategory } ( X Y : C^.Obj ) : C^.Obj := C^.tensor^.onObjects (X, Y)
definition tensor_on_left { C: MonoidalCategory.{u v} } ( Z: C^.Obj ) : Functor.{u v u v} C C :=
{
onObjects := λ X, C^.tensorObjects Z X
}
|
a56f9503bdb8b0ac12a6b53f88684f473c9f2761 | 82e44445c70db0f03e30d7be725775f122d72f3e | /archive/100-theorems-list/57_herons_formula.lean | 22d93abc0f33f9bb82697afc34518f3842556329 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 2,835 | lean | /-
Copyright (c) 2021 Matt Kempster. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Matt Kempster
-/
import geometry.euclidean.triangle
import analysis.special_functions.trigonometric
/-!
# Freek № 57: Heron's Formula
This file proves Theorem 57 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/),
also known as Heron's formula, which gives the area of a triangle based only on its three sides'
lengths.
## References
* https://en.wikipedia.org/wiki/Herons_formula
-/
open real euclidean_geometry
open_locale real euclidean_geometry
local notation `√` := real.sqrt
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- **Heron's formula**: The area of a triangle with side lengths `a`, `b`, and `c` is
`√(s * (s - a) * (s - b) * (s - c))` where `s = (a + b + c) / 2` is the semiperimeter.
We show this by equating this formula to `a * b * sin γ`, where `γ` is the angle opposite
the side `c`.
-/
theorem heron {p1 p2 p3 : P} (h1 : p1 ≠ p2) (h2 : p3 ≠ p2) :
let a := dist p1 p2, b := dist p3 p2, c := dist p1 p3, s := (a + b + c) / 2 in
1/2 * a * b * sin (∠ p1 p2 p3) = √(s * (s - a) * (s - b) * (s - c)) :=
begin
intros a b c s,
let γ := ∠ p1 p2 p3,
obtain := ⟨(dist_pos.mpr h1).ne', (dist_pos.mpr h2).ne'⟩,
have cos_rule : cos γ = (a * a + b * b - c * c) / (2 * a * b) := by field_simp [mul_comm, a,
dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle p1 p2 p3],
let numerator := (2*a*b)^2 - (a*a + b*b - c*c)^2,
let denominator := (2*a*b)^2,
have split_to_frac : 1 - cos γ ^ 2 = numerator / denominator := by field_simp [cos_rule],
have numerator_nonneg : 0 ≤ numerator,
{ have frac_nonneg: 0 ≤ numerator / denominator := by linarith [split_to_frac, cos_sq_le_one γ],
cases div_nonneg_iff.mp frac_nonneg,
{ exact h.left },
{ simpa [h1, h2] using le_antisymm h.right (sq_nonneg _) } },
have ab2_nonneg : 0 ≤ (2 * a * b) := by norm_num [mul_nonneg, dist_nonneg],
calc 1/2 * a * b * sin γ
= 1/2 * a * b * (√numerator / √denominator) : by rw [sin_eq_sqrt_one_sub_cos_sq,
split_to_frac, sqrt_div numerator_nonneg];
simp [angle_nonneg, angle_le_pi]
... = 1/4 * √((2*a*b)^2 - (a*a + b*b - c*c)^2) : by { field_simp [ab2_nonneg], ring }
... = 1/4 * √(s * (s-a) * (s-b) * (s-c) * 4^2) : by { simp only [s], ring_nf }
... = √(s * (s-a) * (s-b) * (s-c)) : by rw [sqrt_mul', sqrt_sq, div_mul_eq_mul_div,
one_mul, mul_div_cancel];
norm_num,
end
|
797b24bacd544216b8e97ef1c37ea59ee06808d4 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/lean/semantics/util.lean | 0c766c6018f16fd6776024fb5fd59b590e90ce77 | [
"Apache-2.0"
] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 15,663 | lean | import field_theory.finite.basic
import data.bitvec.basic
import algebra.group_with_zero
import tactic.omega
open_locale big_operators
/-
bool
-/
attribute [simp] bool.to_nat
/-
int
-/
namespace int
lemma abs_le_of_dvd {i j : int} (h : i ∣ j) (h' : 0 < j) : abs i ≤ j :=
int.le_of_dvd h' ((abs_dvd _ _).mpr h)
theorem modeq_iff_sub_mod_eq_zero {i j m : ℤ} : i ≡ j [ZMOD m] ↔ (i - j) % m = 0 :=
by rw [int.modeq_iff_dvd, ←neg_sub, dvd_neg, int.dvd_iff_mod_eq_zero]
theorem modeq_zero_iff {i m : ℤ} : i ≡ 0 [ZMOD m] ↔ i % m = 0 :=
by rw [modeq_iff_sub_mod_eq_zero, sub_zero]
end int
/-
For casts from `nat` to `int`, `push_neg` does not always do the right thing on
large numbers. This is a more restricted version.
-/
mk_simp_attribute int_cast_simps "rules for pushing integer casts downwards"
attribute [int_cast_simps] int.coe_nat_zero int.coe_nat_one int.coe_nat_bit0 int.coe_nat_bit1
int.coe_nat_add int.coe_nat_pow
int.cast_add int.cast_mul int.cast_sub int.cast_bit0 int.cast_bit1 int.cast_zero int.cast_one
meta def simp_int_casts : tactic unit := `[ simp only with int_cast_simps ]
/-
option
-/
namespace option
def agrees {α : Type*} : option α → α → Prop
| (some a) b := a = b
| none _ := true
def fn_extends {α β : Type*} (f : α → β) (f' : α → option β) : Prop :=
∀ x, (f' x).agrees (f x)
theorem eq_of_fn_extends {α β : Type*} {f : α → β} {f' : α → option β}
(h : fn_extends f f') {a : α} {b : β} (h' : f' a = some b) : f a = b :=
by { symmetry, have := h a, rwa h' at this }
end option
/-
vector
-/
namespace vector
variables {α : Type*}
theorem reverse_cons {n : ℕ} (a : α) (v : vector α n) :
reverse (cons a v) = append (reverse v) (cons a nil) :=
by { apply to_list_injective, simp [reverse] }
theorem append_nil {n : ℕ} (v : vector α n) :
append v nil = v :=
by { apply to_list_injective, simp }
end vector
/-
fin
-/
namespace fin
theorem eq_cast_succ_or_eq_last {n : ℕ} (i : fin (n + 1)) :
(∃ j, i = cast_succ j) ∨ i = last n :=
begin
cases (lt_or_eq_of_le (le_last i)) with h h,
{ use ⟨i.1, h⟩, ext, refl },
right, exact h
end
lemma exists_fin_cast_succ {n : ℕ} {P : fin (n + 1) → Prop} :
(∃ i, P i) ↔ ((∃ i : fin n, P i.cast_succ) ∨ P (fin.last n)) :=
begin
split,
{ rintros ⟨i, hi⟩,
rcases eq_cast_succ_or_eq_last i with ⟨j, rfl⟩ | rfl,
{ left, use j, assumption },
right, assumption },
rintros (⟨i, h⟩ | h); exact exists.intro _ h
end
@[simp] def rev {n : ℕ} : fin n → fin n
| ⟨i, h⟩ := ⟨n - i.succ, by omega⟩
@[simp] theorem rev_rev {n : ℕ} (i : fin n) : rev (rev i) = i :=
by { cases i with i h, unfold rev, ext, dsimp, omega }
@[simp] theorem coe_rev {n : ℕ} (i : fin n) : (i.rev : ℕ) = n - i.succ :=
by { cases i with i h, refl }
@[simp] theorem rev_zero {n : ℕ} : (0 : fin (n + 1)).rev = last n :=
by refl
@[simp] theorem rev_last {n : ℕ} : (last n).rev = 0 :=
by { rw [←rev_zero, rev_rev] }
theorem cast_succ_add_one_rev {n : ℕ} {i : fin n} :
(cast_succ i + 1).rev + 1 = (cast_succ i).rev :=
begin
cases i with i' h',
ext,
simp [coe_add, coe_rev, coe_one'],
rw [@nat.mod_eq_of_lt (i' + 1), nat.mod_eq_of_lt]; omega
end
theorem cast_succ_rev {n : ℕ} (i : fin n) :
i.rev.cast_succ = i.succ.rev :=
by { cases i with i' h', ext, simp }
theorem rev_cast_succ {n : ℕ} (i : fin n) :
i.cast_succ.rev = i.rev.succ :=
by conv { to_lhs, rw [← rev_rev i, cast_succ_rev, rev_rev] }
theorem rev_lt_rev_iff {n : ℕ} (i j : fin n) : rev i < rev j ↔ j < i :=
begin
cases i with i ih, cases j with j jh, rw [rev, rev],
transitivity,
apply tsub_lt_tsub_iff_left_of_le (nat.succ_le_of_lt ih),
exact ⟨nat.lt_of_succ_lt_succ, nat.succ_lt_succ⟩
end
theorem rev_le_rev_iff {n : ℕ} (i j : fin n) : rev i ≤ rev j ↔ j ≤ i :=
begin
cases i with i ih, cases j with j jh, rw [rev, rev],
transitivity,
apply tsub_le_tsub_iff_left (nat.succ_le_of_lt jh),
apply nat.succ_le_succ_iff
end
theorem add_one_le_of_lt {n : ℕ} {i j : fin (n + 1)} (h : i < j) : i + 1 ≤ j :=
begin
cases i with i hi,
cases j with j hj,
simp [fin.le_def, fin.coe_add, fin.coe_one'],
rw nat.mod_eq_of_lt,
{ apply nat.succ_le_of_lt h },
apply lt_of_le_of_lt (nat.succ_le_of_lt h) hj
end
theorem eq_zero_of_le_zero {n : ℕ} {i : fin (n + 1)} (h : i ≤ 0) : i = 0 :=
by { cases i, ext, apply nat.eq_zero_of_le_zero h }
theorem of_le_succ {n : ℕ} {i : fin (n + 1)} {j : fin n} (h : i ≤ j.succ) :
i ≤ j.cast_succ ∨ i = j.succ :=
begin
cases i, cases j,
simp [fin.succ] at *,
exact nat.of_le_succ h
end
theorem le_of_lt_succ {n : ℕ} {i : fin (n + 1)} {j : fin n} (h : i < j.succ) : i ≤ j.cast_succ :=
by { cases i, cases j, exact nat.le_of_lt_succ h}
theorem cast_succ_lt_succ_iff {n : ℕ} (i j : fin n) :
i.cast_succ < j.succ ↔ i.cast_succ ≤ j.cast_succ :=
by { cases i, cases j, apply nat.lt_succ_iff }
@[simp] theorem cast_succ_le_cast_succ_iff {n : ℕ} (i j : fin n) :
i.cast_succ ≤ j.cast_succ ↔ i ≤ j :=
by { cases i, cases j, refl }
theorem one_eq_succ_zero {n : ℕ} : (1 : fin (n + 2)) = fin.succ 0 := rfl
theorem le_zero_iff {n : ℕ} (i : fin (n + 1)) : i ≤ 0 ↔ i = 0 :=
by { rw [fin.ext_iff, fin.le_def], cases i, apply le_zero_iff }
lemma last_zero : fin.last 0 = 0 :=
by { ext, refl }
/-- This lemma is useful for rewriting `fin (n + 1)` as `fin (m + j + 1)`,
given `i : fin (n + 1)` and `m = ↑i`. -/
lemma exists_eq_add {n : ℕ} (i : fin (n + 1)) : ∃ m j, m = ↑i ∧ n = m + j :=
begin
cases nat.exists_eq_add_of_le (nat.le_of_lt_succ i.2) with j hj,
use [↑i, j, rfl, hj]
end
def cast_offset {n : ℕ} (m : ℕ) (i : fin n) : fin (m + n) :=
⟨m + ↑i, add_lt_add_left i.is_lt _⟩
def cast_offset' {n : ℕ} (m : ℕ) (j : fin (n + 1)) : fin (m + n + 1) :=
@cast_offset (n + 1) m j
theorem cast_succ_cast_offset {n m : ℕ} (i : fin n) :
fin.cast_offset m i.cast_succ = (fin.cast_offset m i).cast_succ :=
by { cases i, refl }
theorem succ_cast_offset {n m : ℕ} (i : fin n) :
fin.cast_offset m i.succ = (fin.cast_offset m i).succ :=
by {cases i, refl }
section
variable {n : ℕ}
def range (i : fin (n + 1)) : finset (fin n) :=
finset.univ.filter (λ j, j.cast_succ < i)
@[simp] theorem mem_range (i : fin n) (j : fin (n + 1)) : i ∈ range j ↔ i.cast_succ < j :=
by simp [range]
@[simp] theorem range_zero : range (0 : fin (n + 1)) = ∅ :=
by { ext i, simp [range, fin.zero_le] }
@[simp] theorem range_one : range (1 : fin (n + 2)) = {(0 : fin (n + 1))} :=
begin
ext i,
rw [mem_range, finset.mem_singleton, one_eq_succ_zero, cast_succ_lt_succ_iff,
cast_succ_le_cast_succ_iff, le_zero_iff]
end
theorem range_succ (i : fin n) : range i.succ = insert i (range i.cast_succ) :=
begin
ext j,
rw [mem_range, finset.mem_insert, mem_range, cast_succ_lt_succ_iff, le_iff_lt_or_eq,
cast_succ_inj, or.comm]
end
theorem range_last : range (fin.last n) = finset.univ :=
by { ext i, simp [mem_range, cast_succ_lt_last] }
@[simp] theorem not_mem_range_self (i : fin n) : i ∉ range i.cast_succ :=
by { rw mem_range, apply lt_irrefl }
@[simp] theorem self_mem_range_succ (i: fin n) : i ∈ range (i.succ) :=
by { rw mem_range, apply cast_succ_lt_succ }
@[simp] theorem range_subset {i j : fin (n + 1)} : range i ⊆ range j ↔ i ≤ j :=
begin
rw [finset.subset_iff], split,
{ intro h,
by_cases h' : i = 0, { rw h', apply zero_le },
have : i.pred h' ∈ range i,
{ rw mem_range, conv {to_rhs, rw ←succ_pred i h'},
rw cast_succ_lt_succ_iff },
specialize h this,
rwa [mem_range, cast_succ_lt_iff_succ_le, succ_pred i h'] at h },
intros h k,
rw [mem_range, mem_range],
intro h',
exact lt_of_lt_of_le h' h
end
section
variables {β : Type*} [comm_monoid β]
lemma prod_range_zero (f : fin n → β) :
(∏ k in range 0, f k) = 1 :=
by rw [range_zero, finset.prod_empty]
lemma sum_range_zero {β : Type*} [add_comm_monoid β] (f : fin n → β) :
(∑ k in range 0, f k) = 0 :=
by rw [range_zero, finset.sum_empty]
@[to_additive]
lemma prod_range_one (f : fin (n + 1) → β) :
(∏ k in range 1, f k) = f 0 :=
by { rw [range_one], rw finset.prod_singleton }
@[to_additive]
lemma prod_range_succ (f : fin n → β) (i : fin n) :
(∏ x in range i.succ, f x) = f i * (∏ x in range i.cast_succ, f x) :=
by rw [range_succ, finset.prod_insert (not_mem_range_self i)]
lemma prod_range_succ' (f : fin (n + 1) → β) (i : fin (n + 1)) :
(∏ k in range i.succ, f k) = (∏ k in range i, f k.succ) * f 0 :=
begin
apply fin.induction_on i,
{ rw [prod_range_succ, cast_succ_zero, prod_range_zero, prod_range_zero, mul_comm] },
intros i' ih,
rw [prod_range_succ (λ k, f (k.succ)), mul_assoc, ←ih, succ_cast_succ, prod_range_succ]
end
lemma sum_range_succ' {β : Type*} [add_comm_monoid β] (f : fin (n + 1) → β) (i : fin (n + 1)) :
(∑ k in range i.succ, f k) = (∑ k in range i, f k.succ) + f 0 :=
begin
apply fin.induction_on i,
{ rw [sum_range_succ, cast_succ_zero, sum_range_zero, sum_range_zero, add_comm] },
intros i' ih,
rw [sum_range_succ (λ k, f (k.succ)), add_assoc, ←ih, succ_cast_succ, sum_range_succ]
end
end
/- currently not used, but maybe useful?
theorem add_one_eq_of_lt_last {n : ℕ} {i : fin (n + 1)} (h : i < last n) :
i + 1 = ⟨i.1 + 1, nat.succ_lt_succ h⟩ :=
begin
cases i with i' h', ext,
simp [fin.coe_add, fin.coe_one'],
apply nat.mod_eq_of_lt,
apply nat.succ_lt_succ,
apply h
end
theorem lt_of_add_one_le {n : ℕ} {i j : fin (n + 1)} (h : i < last n) (h' : i + 1 ≤ j) :
i < j :=
begin
cases i with i hi,
cases j with j hj,
simp [fin.le_def, fin.coe_add, fin.coe_one'],
rw add_one_eq_of_lt_last h at h',
apply nat.lt_of_succ_le h'
end
theorem add_one_rev_lt_last {n : ℕ} {i : fin (n + 1)} (h : i < fin.last n) :
(i + 1).rev < fin.last n :=
begin
rw [add_one_eq_of_lt_last h, rev, lt_def],
dsimp [fin.last],
rw nat.succ_sub_succ,
apply nat.sub_lt,
{ apply lt_of_le_of_lt (nat.zero_le _) h },
apply nat.zero_lt_succ
end
-/
end
end fin
/-
bitvec
-/
namespace bitvec
variables {n : ℕ} (b : bitvec n)
/-- bitvec's `to_nat` has bit 0 as msb, but the Cairo convention is the reverse. -/
def to_natr : ℕ := bitvec.to_nat b.reverse
def to_biased_16 : ℤ := (b.to_natr : int) - 2^15
theorem to_natr_lt : b.to_natr < 2^n := to_nat_lt _
theorem to_nat_le : b.to_nat ≤ 2^n - 1 :=
begin
apply le_tsub_of_add_le_right,
apply nat.succ_le_of_lt,
apply to_nat_lt
end
theorem to_natr_le : b.to_natr ≤ 2^n - 1 := to_nat_le _
theorem to_nat_inj {n : ℕ} {b1 b2 : bitvec n} (h : b1.to_nat = b2.to_nat) : b1 = b2 :=
by rw [←of_nat_to_nat b1, h, of_nat_to_nat b2]
theorem to_natr_inj {n : ℕ} {b1 b2 : bitvec n} (h : b1.to_natr = b2.to_natr) : b1 = b2 :=
begin
suffices : b1.reverse.reverse = b2.reverse.reverse,
by rwa [vector.reverse_reverse, vector.reverse_reverse] at this,
rw to_nat_inj h,
end
def of_natr (n k : ℕ) : bitvec n := (bitvec.of_nat n k).reverse
theorem to_natr_of_natr {k n : ℕ} : (bitvec.of_natr k n).to_natr = n % 2 ^ k :=
by rw [of_natr, to_natr, vector.reverse_reverse, to_nat_of_nat]
theorem singleton_to_nat (u : bool) : bitvec.to_nat (u ::ᵥ vector.nil) = u.to_nat :=
by simp [bitvec.to_nat, bits_to_nat, add_lsb]
end bitvec
/-
Casting nat and int to a ring with positive characteristic.
-/
namespace nat
variables {R : Type*} [ring R]
theorem cast_inj_of_lt_char' {a b : ℕ} (hlt : a ≤ b) (h : b < ring_char R)
(h : (a : R) = (b : R)) : a = b :=
begin
suffices : b - a = 0,
{ apply le_antisymm hlt, rwa ←nat.sub_eq_zero_iff_le },
have h1 : ((b - a : ℕ) : R) = 0,
{ rw [nat.cast_sub hlt, h, sub_self] },
rw [ring_char.spec] at h1,
suffices : ¬ b - a > 0, linarith,
assume : b - a > 0,
have : ring_char R ≤ b - a, from nat.le_of_dvd this h1,
have : b - a ≤ b, from tsub_le_self,
linarith
end
theorem cast_inj_of_lt_char {a b : ℕ} (ha : a < ring_char R) (hb : b < ring_char R)
(h : (a : R) = (b : R)) : a = b :=
begin
wlog h' : a ≤ b,
exact cast_inj_of_lt_char' h' hb h
end
end nat
namespace int
theorem cast_ne_zero_of_abs_lt_char {R : Type*} [ring R]
{x : ℤ} (h0 : abs x ≠ 0) (h1 : abs x < ring_char R) :
(x : R) ≠ 0 :=
begin
have h3 : (abs x).to_nat < ring_char R,
{ rwa [←int.to_nat_of_nonneg (abs_nonneg x), int.coe_nat_lt_coe_nat_iff] at h1 },
intro h, apply h0,
suffices : (abs x).to_nat = 0,
{ rw [←int.to_nat_of_nonneg (abs_nonneg x), this], refl },
apply nat.cast_inj_of_lt_char h3 (lt_of_le_of_lt (nat.zero_le _) h3),
have : ((abs x).to_nat : R) = (((abs x).to_nat : ℤ) : R), by simp [-int.to_nat_of_nonneg],
apply eq.trans this,
rw [int.to_nat_of_nonneg (abs_nonneg x)],
cases (le_or_gt 0 x) with h4 h4,
{ rw [abs_of_nonneg h4, h, nat.cast_zero] },
rw abs_of_neg h4, simp [h]
end
lemma cast_inj_of_lt_char {R : Type*} [ring R] {i j : ℤ} {p : ℕ}
(charR : char_p R p) (h : (i : R) = (j : R)) (h' : abs (j - i) < p) : i = j :=
begin
symmetry,
apply eq_of_sub_eq_zero,
rw ←abs_eq_zero,
by_contradiction nez,
apply not_le_of_lt h',
apply int.le_of_dvd,
apply lt_of_le_of_ne (abs_nonneg _) (ne.symm nez),
rw dvd_abs,
have: (↑(j - i) : R) = 0, by simp [h],
exact (char_p.int_cast_eq_zero_iff R p _).mp this
end
lemma cast_eq_zero_of_lt_char (R : Type*) [ring R] {i : ℤ} (p : ℕ)
[charR : char_p R p] (h : (i : R) = 0) (h' : abs i < p) : i = 0 :=
begin
have := @int.cast_inj_of_lt_char _ _ i 0 p charR,
simp at this,
apply this; assumption
end
end int
/-
Ring theory.
-/
open finset polynomial
section
variables {R : Type*} [comm_semiring R]
@[simp] lemma eval_multiset_prod (m : multiset (polynomial R)) (z : R) :
eval z m.prod = (m.map (eval z)).prod :=
(@multiset.prod_hom _ R _ _ m _ _ (eval_ring_hom z)).symm
lemma nat_degree_add (p q : polynomial R) :
nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) :=
begin
by_cases hp : p = 0, { simp [hp] },
by_cases hq : q = 0, { simp [hq] },
by_cases hpq : p + q = 0, { simp [hpq] },
have := degree_add_le p q,
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq, degree_eq_nat_degree hpq] at this,
simp only [with_bot.coe_le_coe, le_max_iff] at this ⊢,
exact this
end
end
section
variables {R : Type*} [comm_ring R] [is_domain R]
private lemma multiset_prod_X_sub_C_aux (m : multiset R) :
(m.map (λ r, X - C r)).prod ≠ 0 ∧ (m.map (λ r, X - C r)).prod.nat_degree = m.card :=
begin
apply multiset.induction_on m, { simp },
intros a m ih,
have h : X - C a ≠ 0 := X_sub_C_ne_zero a,
rw [multiset.map_cons, multiset.prod_cons, multiset.card_cons],
split, { exact mul_ne_zero h ih.1 },
rw [nat_degree_mul h ih.1, ih.2], simp [add_comm]
end
lemma multiset_prod_X_sub_C_ne_zero (m : multiset R) :
(m.map (λ r, X - C r)).prod ≠ 0
:= (multiset_prod_X_sub_C_aux m).1
lemma nat_degree_multiset_prod_X_sub_C (m : multiset R) :
(m.map (λ r, X - C r)).prod.nat_degree = m.card
:= (multiset_prod_X_sub_C_aux m).2
lemma degree_multiset_prod_X_sub_C_ne_zero (m : multiset R) :
(m.map (λ r, X - C r)).prod.degree = m.card :=
by { rw [degree_eq_nat_degree (multiset_prod_X_sub_C_ne_zero m),
(nat_degree_multiset_prod_X_sub_C m)] }
lemma multiset_prod_X_sub_C_roots (m : multiset R) : (m.map (λ r, X - C r)).prod.roots = m :=
begin
have h' : (0 : polynomial R) ∉ multiset.map (λ (r : R), X - C r) m,
{ rw [multiset.mem_map], rintros ⟨r, _, h''⟩, apply X_sub_C_ne_zero _ h'' },
rw [roots_multiset_prod _ h', multiset.bind, multiset.join], simp
end
end
|
351dd733c65cf3f3cce69ee62656b0937af474d1 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/hash_map.lean | c8e74a0a1b01b6f572613ca2e799c10f29337fb4 | [] | 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 | 19,355 | 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, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.pnat.basic
import Mathlib.data.list.range
import Mathlib.data.array.lemmas
import Mathlib.algebra.group.default
import Mathlib.data.sigma.basic
import Mathlib.PostPort
universes u v w l u_1
namespace Mathlib
/-!
# Hash maps
Defines a hash map data structure, representing a finite key-value map
with a value type that may depend on the key type. The structure
requires a `nat`-valued hash function to associate keys to buckets.
## Main definitions
* `hash_map`: constructed with `mk_hash_map`.
## Implementation details
A hash map with key type `α` and (dependent) value type `β : α → Type*`
consists of an array of *buckets*, which are lists containing
key/value pairs for that bucket. The hash function is taken modulo `n`
to assign keys to their respective bucket. Because of this, some care
should be put into the hash function to ensure it evenly distributes
keys.
The bucket array is an `array`. These have special VM support for
in-place modification if there is only ever one reference to them. If
one takes special care to never keep references to old versions of a
hash map alive after updating it, then the hash map will be modified
in-place. In this documentation, when we say a hash map is modified
in-place, we are assuming the API is being used in this manner.
When inserting (`hash_map.insert`), if the number of stored pairs (the
*size*) is going to exceed the number of buckets, then a new hash map
is first created with double the number of buckets and everything in
the old hash map is reinserted along with the new key/value pair.
Otherwise, the bucket array is modified in-place. The amortized
running time of inserting $$n$$ elements into a hash map is $$O(n)$$.
When removing (`hash_map.erase`), the hash map is modified in-place.
The implementation does not reduce the number of buckets in the hash
map if the size gets too low.
## Tags
hash map
-/
/-- `bucket_array α β` is the underlying data type for `hash_map α β`,
an array of linked lists of key-value pairs. -/
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array (↑n) (List (sigma fun (a : α) => β a))
/-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/
def hash_map.mk_idx (n : ℕ+) (i : ℕ) : fin ↑n :=
{ val := i % ↑n, property := sorry }
namespace bucket_array
protected instance inhabited {α : Type u} {β : α → Type v} {n : ℕ+} : Inhabited (bucket_array α β n) :=
{ default := mk_array ↑n [] }
/-- Read the bucket corresponding to an element -/
def read {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n) (a : α) : List (sigma fun (a : α) => β a) :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.read data bidx
/-- Write the bucket corresponding to an element -/
def write {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n) (a : α) (l : List (sigma fun (a : α) => β a)) : bucket_array α β n :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.write data bidx l
/-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/
def modify {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n) (a : α) (f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)) : bucket_array α β n :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.write data bidx (f (array.read data bidx))
/-- The list of all key-value pairs in the bucket list -/
def as_list {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) : List (sigma fun (a : α) => β a) :=
list.join (array.to_list data)
theorem mem_as_list {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) {a : sigma fun (a : α) => β a} : a ∈ as_list data ↔ ∃ (i : fin ↑n), a ∈ array.read data i := sorry
/-- Fold a function `f` over the key-value pairs in the bucket list -/
def foldl {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) {δ : Type w} (d : δ) (f : δ → (a : α) → β a → δ) : δ :=
array.foldl data d
fun (b : List (sigma fun (a : α) => β a)) (d : δ) =>
list.foldl (fun (r : δ) (a : sigma fun (a : α) => β a) => f r (sigma.fst a) (sigma.snd a)) d b
theorem foldl_eq {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) {δ : Type w} (d : δ) (f : δ → (a : α) → β a → δ) : foldl data d f =
list.foldl (fun (r : δ) (a : sigma fun (a : α) => β a) => f r (sigma.fst a) (sigma.snd a)) d (as_list data) := sorry
end bucket_array
namespace hash_map
/-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array
(without checking for duplication) -/
def reinsert_aux {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
bucket_array.modify hash_fn data a fun (l : List (sigma fun (a : α) => β a)) => sigma.mk a b :: l
theorem mk_as_list {α : Type u} {β : α → Type v} (n : ℕ+) : bucket_array.as_list (mk_array ↑n []) = [] := sorry
/-- Search a bucket for a key `a` and return the value -/
def find_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) : List (sigma fun (a : α) => β a) → Option (β a) :=
sorry
theorem find_aux_iff {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a} {l : List (sigma fun (a : α) => β a)} : list.nodup (list.map sigma.fst l) → (find_aux a l = some b ↔ sigma.mk a b ∈ l) := sorry
/-- Returns `tt` if the bucket `l` contains the key `a` -/
def contains_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (l : List (sigma fun (a : α) => β a)) : Bool :=
option.is_some (find_aux a l)
theorem contains_aux_iff {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {l : List (sigma fun (a : α) => β a)} (nd : list.nodup (list.map sigma.fst l)) : ↥(contains_aux a l) ↔ a ∈ list.map sigma.fst l := sorry
/-- Modify a bucket to replace a value in the list. Leaves the list
unchanged if the key is not found. -/
def replace_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a) :=
sorry
/-- Modify a bucket to remove a key, if it exists. -/
def erase_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a) :=
sorry
/-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map`
invariants: There are exactly `sz` elements in it, every pair is in the
bucket determined by its key and the hash function, and no key appears
multiple times in the list. -/
structure valid {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} (bkts : bucket_array α β n) (sz : ℕ)
where
len : list.length (bucket_array.as_list bkts) = sz
idx : ∀ {i : fin ↑n} {a : sigma fun (a : α) => β a}, a ∈ array.read bkts i → mk_idx n (hash_fn (sigma.fst a)) = i
nodup : ∀ (i : fin ↑n), list.nodup (list.map sigma.fst (array.read bkts i))
theorem valid.idx_enum {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {i : ℕ} {l : List (sigma fun (a : α) => β a)} (he : (i, l) ∈ list.enum (array.to_list bkts)) {a : α} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ (h : i < ↑n), mk_idx n (hash_fn a) = { val := i, property := h } := sorry
theorem valid.idx_enum_1 {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {i : ℕ} {l : List (sigma fun (a : α) => β a)} (he : (i, l) ∈ list.enum (array.to_list bkts)) {a : α} {b : β a} (hl : sigma.mk a b ∈ l) : subtype.val (mk_idx n (hash_fn a)) = i := sorry
theorem valid.as_list_nodup {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) : list.nodup (list.map sigma.fst (bucket_array.as_list bkts)) := sorry
theorem mk_valid {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] (n : ℕ+) : valid hash_fn (mk_array ↑n []) 0 := sorry
theorem valid.find_aux_iff {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {a : α} {b : β a} : find_aux a (bucket_array.read hash_fn bkts a) = some b ↔ sigma.mk a b ∈ bucket_array.as_list bkts := sorry
theorem valid.contains_aux_iff {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) (a : α) : ↥(contains_aux a (bucket_array.read hash_fn bkts a)) ↔ a ∈ list.map sigma.fst (bucket_array.as_list bkts) := sorry
theorem append_of_modify {α : Type u} {β : α → Type v} [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin ↑n} {f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)} (u : List (sigma fun (a : α) => β a)) (v1 : List (sigma fun (a : α) => β a)) (v2 : List (sigma fun (a : α) => β a)) (w : List (sigma fun (a : α) => β a)) (hl : array.read bkts bidx = u ++ v1 ++ w) (hfl : f (array.read bkts bidx) = u ++ v2 ++ w) : ∃ (u' : List (sigma fun (a : α) => β a)),
∃ (w' : List (sigma fun (a : α) => β a)),
bucket_array.as_list bkts = u' ++ v1 ++ w' ∧ bucket_array.as_list bkts' = u' ++ v2 ++ w' := sorry
theorem valid.modify {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin ↑n} {f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)} (u : List (sigma fun (a : α) => β a)) (v1 : List (sigma fun (a : α) => β a)) (v2 : List (sigma fun (a : α) => β a)) (w : List (sigma fun (a : α) => β a)) (hl : array.read bkts bidx = u ++ v1 ++ w) (hfl : f (array.read bkts bidx) = u ++ v2 ++ w) (hvnd : list.nodup (list.map sigma.fst v2)) (hal : ∀ (a : sigma fun (a : α) => β a), a ∈ v2 → mk_idx n (hash_fn (sigma.fst a)) = bidx) (djuv : list.disjoint (list.map sigma.fst u) (list.map sigma.fst v2)) (djwv : list.disjoint (list.map sigma.fst w) (list.map sigma.fst v2)) {sz : ℕ} (v : valid hash_fn bkts sz) : list.length v1 ≤ sz + list.length v2 ∧ valid hash_fn bkts' (sz + list.length v2 - list.length v1) := sorry
theorem valid.replace_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) (l : List (sigma fun (a : α) => β a)) : a ∈ list.map sigma.fst l →
∃ (u : List (sigma fun (a : α) => β a)),
∃ (w : List (sigma fun (a : α) => β a)),
∃ (b' : β a), l = u ++ [sigma.mk a b'] ++ w ∧ replace_aux a b l = u ++ [sigma.mk a b] ++ w := sorry
theorem valid.replace {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : ↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) : valid hash_fn (bucket_array.modify hash_fn bkts a (replace_aux a b)) sz := sorry
theorem valid.insert {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) : valid hash_fn (reinsert_aux hash_fn bkts a b) (sz + 1) := sorry
theorem valid.erase_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (l : List (sigma fun (a : α) => β a)) : a ∈ list.map sigma.fst l →
∃ (u : List (sigma fun (a : α) => β a)),
∃ (w : List (sigma fun (a : α) => β a)), ∃ (b : β a), l = u ++ [sigma.mk a b] ++ w ∧ erase_aux a l = u ++ [] ++ w := sorry
theorem valid.erase {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (Hc : ↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) : valid hash_fn (bucket_array.modify hash_fn bkts a (erase_aux a)) (sz - 1) := sorry
end hash_map
/-- A hash map data structure, representing a finite key-value map
with key type `α` and value type `β` (which may depend on `α`). -/
structure hash_map (α : Type u) [DecidableEq α] (β : α → Type v)
where
hash_fn : α → ℕ
size : ℕ
nbuckets : ℕ+
buckets : bucket_array α β nbuckets
is_valid : hash_map.valid hash_fn buckets size
/-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/
def mk_hash_map {α : Type u} [DecidableEq α] {β : α → Type v} (hash_fn : α → ℕ) (nbuckets : optParam ℕ (bit0 (bit0 (bit0 1)))) : hash_map α β :=
let n : optParam ℕ (bit0 (bit0 (bit0 1))) := ite (nbuckets = 0) (bit0 (bit0 (bit0 1))) nbuckets;
let nz : n > 0 := sorry;
hash_map.mk hash_fn 0 { val := n, property := nz } (mk_array n []) sorry
namespace hash_map
/-- Return the value corresponding to a key, or `none` if not found -/
def find {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : Option (β a) :=
find_aux a (bucket_array.read (hash_fn m) (buckets m) a)
/-- Return `tt` if the key exists in the map -/
def contains {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : Bool :=
option.is_some (find m a)
protected instance has_mem {α : Type u} {β : α → Type v} [DecidableEq α] : has_mem α (hash_map α β) :=
has_mem.mk fun (a : α) (m : hash_map α β) => ↥(contains m a)
/-- Fold a function over the key-value pairs in the map -/
def fold {α : Type u} {β : α → Type v} [DecidableEq α] {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → (a : α) → β a → δ) : δ :=
bucket_array.foldl (buckets m) d f
/-- The list of key-value pairs in the map -/
def entries {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) : List (sigma fun (a : α) => β a) :=
bucket_array.as_list (buckets m)
/-- The list of keys in the map -/
def keys {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) : List α :=
list.map sigma.fst (entries m)
theorem find_iff {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (b : β a) : find m a = some b ↔ sigma.mk a b ∈ entries m :=
valid.find_aux_iff (hash_fn m) (is_valid m)
theorem contains_iff {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : ↥(contains m a) ↔ a ∈ keys m :=
valid.contains_aux_iff (hash_fn m) (is_valid m) a
theorem entries_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) (n : optParam ℕ (bit0 (bit0 (bit0 1)))) : entries (mk_hash_map hash_fn n) = [] :=
mk_as_list (nbuckets (mk_hash_map hash_fn n))
theorem keys_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) (n : optParam ℕ (bit0 (bit0 (bit0 1)))) : keys (mk_hash_map hash_fn n) = [] := sorry
theorem find_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) (n : optParam ℕ (bit0 (bit0 (bit0 1)))) (a : α) : find (mk_hash_map hash_fn n) a = none := sorry
theorem not_contains_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) (n : optParam ℕ (bit0 (bit0 (bit0 1)))) (a : α) : ¬↥(contains (mk_hash_map hash_fn n) a) := sorry
theorem insert_lemma {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) {n : ℕ+} {n' : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) : valid hash_fn (bucket_array.foldl bkts (mk_array ↑n' []) (reinsert_aux hash_fn)) sz := sorry
/-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/
def insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (b : β a) : hash_map α β :=
sorry
theorem mem_insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (b : β a) (a' : α) (b' : β a') : sigma.mk a' b' ∈ entries (insert m a b) ↔ ite (a = a') (b == b') (sigma.mk a' b' ∈ entries m) := sorry
theorem find_insert_eq {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (b : β a) : find (insert m a b) a = some b :=
iff.mpr (find_iff (insert m a b) a b)
(iff.mpr (mem_insert m a b a b)
(eq.mpr (id (Eq._oldrec (Eq.refl (ite (a = a) (b == b) (sigma.mk a b ∈ entries m))) (if_pos rfl))) (HEq.refl b)))
theorem find_insert_ne {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (a' : α) (b : β a) (h : a ≠ a') : find (insert m a b) a' = find m a' := sorry
theorem find_insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a' : α) (a : α) (b : β a) : find (insert m a b) a' = dite (a = a') (fun (h : a = a') => some (eq.rec_on h b)) fun (h : ¬a = a') => find m a' := sorry
/-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/
def insert_all {α : Type u} {β : α → Type v} [DecidableEq α] (l : List (sigma fun (a : α) => β a)) (m : hash_map α β) : hash_map α β :=
list.foldl (fun (m : hash_map α β) (_x : sigma fun (a : α) => β a) => sorry) m l
/-- Construct a hash map from a list of key-value pairs. -/
def of_list {α : Type u} {β : α → Type v} [DecidableEq α] (l : List (sigma fun (a : α) => β a)) (hash_fn : α → ℕ) : hash_map α β :=
insert_all l (mk_hash_map hash_fn (bit0 1 * list.length l))
/-- Remove a key from the map. (Modifies `m` in-place when applicable) -/
def erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : hash_map α β :=
sorry
theorem mem_erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (a' : α) (b' : β a') : sigma.mk a' b' ∈ entries (erase m a) ↔ a ≠ a' ∧ sigma.mk a' b' ∈ entries m := sorry
theorem find_erase_eq {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : find (erase m a) a = none := sorry
theorem find_erase_ne {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (a' : α) (h : a ≠ a') : find (erase m a) a' = find m a' := sorry
theorem find_erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a' : α) (a : α) : find (erase m a) a' = ite (a = a') none (find m a') := sorry
protected instance has_to_string {α : Type u} {β : α → Type v} [DecidableEq α] [has_to_string α] [(a : α) → has_to_string (β a)] : has_to_string (hash_map α β) :=
has_to_string.mk to_string
/-- `hash_map` with key type `nat` and value type that may vary. -/
protected instance inhabited {β : ℕ → Type u_1} : Inhabited (hash_map ℕ β) :=
{ default := mk_hash_map id }
|
d805969900ab78c51e07fa666a6a5e12ecae685a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/pfunctor/univariate/M.lean | 3090f1d746cf8521f2376ff444a4e03873755bd4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 22,106 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.pfunctor.univariate.basic
/-!
# M-types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
M types are potentially infinite tree-like structures. They are defined
as the greatest fixpoint of a polynomial functor.
-/
universes u v w
open nat function list (hiding head')
variables (F : pfunctor.{u})
local prefix `♯`:0 := cast (by simp [*] <|> cc <|> solve_by_elim)
namespace pfunctor
namespace approx
/-- `cofix_a F n` is an `n` level approximation of a M-type -/
inductive cofix_a : ℕ → Type u
| continue : cofix_a 0
| intro {n} : ∀ a, (F.B a → cofix_a n) → cofix_a (succ n)
/-- default inhabitant of `cofix_a` -/
protected def cofix_a.default [inhabited F.A] : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro default $ λ _, cofix_a.default n
instance [inhabited F.A] {n} : inhabited (cofix_a F n) := ⟨ cofix_a.default F n ⟩
lemma cofix_a_eq_zero : ∀ x y : cofix_a F 0, x = y
| cofix_a.continue cofix_a.continue := rfl
variables {F}
/--
The label of the root of the tree for a non-trivial
approximation of the cofix of a pfunctor.
-/
def head' : Π {n}, cofix_a F (succ n) → F.A
| n (cofix_a.intro i _) := i
/-- for a non-trivial approximation, return all the subtrees of the root -/
def children' : Π {n} (x : cofix_a F (succ n)), F.B (head' x) → cofix_a F n
| n (cofix_a.intro a f) := f
lemma approx_eta {n : ℕ} (x : cofix_a F (n+1)) :
x = cofix_a.intro (head' x) (children' x) :=
by cases x; refl
/-- Relation between two approximations of the cofix of a pfunctor
that state they both contain the same data until one of them is truncated -/
inductive agree : ∀ {n : ℕ}, cofix_a F n → cofix_a F (n+1) → Prop
| continue (x : cofix_a F 0) (y : cofix_a F 1) : agree x y
| intro {n} {a} (x : F.B a → cofix_a F n) (x' : F.B a → cofix_a F (n+1)) :
(∀ i : F.B a, agree (x i) (x' i)) →
agree (cofix_a.intro a x) (cofix_a.intro a x')
/--
Given an infinite series of approximations `approx`,
`all_agree approx` states that they are all consistent with each other.
-/
def all_agree (x : Π n, cofix_a F n) :=
∀ n, agree (x n) (x (succ n))
@[simp]
lemma agree_trival {x : cofix_a F 0} {y : cofix_a F 1} :
agree x y :=
by { constructor }
lemma agree_children {n : ℕ} (x : cofix_a F (succ n)) (y : cofix_a F (succ n+1))
{i j} (h₀ : i == j) (h₁ : agree x y) :
agree (children' x i) (children' y j) :=
begin
cases h₁ with _ _ _ _ _ _ hagree, cases h₀,
apply hagree,
end
/-- `truncate a` turns `a` into a more limited approximation -/
def truncate : ∀ {n : ℕ}, cofix_a F (n+1) → cofix_a F n
| 0 (cofix_a.intro _ _) := cofix_a.continue
| (succ n) (cofix_a.intro i f) := cofix_a.intro i $ truncate ∘ f
lemma truncate_eq_of_agree {n : ℕ} (x : cofix_a F n) (y : cofix_a F (succ n)) (h : agree x y) :
truncate y = x :=
begin
induction n generalizing x y; cases x; cases y,
{ refl },
{ cases h with _ _ _ _ _ h₀ h₁,
cases h,
simp only [truncate, function.comp, true_and, eq_self_iff_true, heq_iff_eq],
ext y, apply n_ih,
apply h₁ }
end
variables {X : Type w}
variables (f : X → F.obj X)
/-- `s_corec f i n` creates an approximation of height `n`
of the final coalgebra of `f` -/
def s_corec : Π (i : X) n, cofix_a F n
| _ 0 := cofix_a.continue
| j (succ n) := cofix_a.intro (f j).1 (λ i, s_corec ((f j).2 i) _)
lemma P_corec (i : X) (n : ℕ) : agree (s_corec f i n) (s_corec f i (succ n)) :=
begin
induction n with n generalizing i,
constructor,
cases h : f i with y g,
constructor,
introv,
apply n_ih,
end
/-- `path F` provides indices to access internal nodes in `corec F` -/
def path (F : pfunctor.{u}) := list F.Idx
instance path.inhabited : inhabited (path F) := ⟨ [] ⟩
open list nat
instance : subsingleton (cofix_a F 0) :=
⟨ by { intros, casesm* cofix_a F 0, refl } ⟩
lemma head_succ' (n m : ℕ) (x : Π n, cofix_a F n) (Hconsistent : all_agree x) :
head' (x (succ n)) = head' (x (succ m)) :=
begin
suffices : ∀ n, head' (x (succ n)) = head' (x 1),
{ simp [this] },
clear m n, intro,
cases h₀ : x (succ n) with _ i₀ f₀,
cases h₁ : x 1 with _ i₁ f₁,
dsimp only [head'],
induction n with n,
{ rw h₁ at h₀, cases h₀, trivial },
{ have H := Hconsistent (succ n),
cases h₂ : x (succ n) with _ i₂ f₂,
rw [h₀,h₂] at H,
apply n_ih (truncate ∘ f₀),
rw h₂,
cases H with _ _ _ _ _ _ hagree,
congr, funext j, dsimp only [comp_app],
rw truncate_eq_of_agree,
apply hagree }
end
end approx
open approx
/-- Internal definition for `M`. It is needed to avoid name clashes
between `M.mk` and `M.cases_on` and the declarations generated for
the structure -/
structure M_intl :=
(approx : ∀ n, cofix_a F n)
(consistent : all_agree approx)
/-- For polynomial functor `F`, `M F` is its final coalgebra -/
def M := M_intl F
lemma M.default_consistent [inhabited F.A] :
Π n, agree (default : cofix_a F n) default
| 0 := agree.continue _ _
| (succ n) := agree.intro _ _ $ λ _, M.default_consistent n
instance M.inhabited [inhabited F.A] : inhabited (M F) :=
⟨ { approx := default,
consistent := M.default_consistent _ } ⟩
instance M_intl.inhabited [inhabited F.A] : inhabited (M_intl F) :=
show inhabited (M F), by apply_instance
namespace M
lemma ext' (x y : M F) (H : ∀ i : ℕ, x.approx i = y.approx i) : x = y :=
by { cases x, cases y, congr' with n, apply H }
variables {X : Type*}
variables (f : X → F.obj X)
variables {F}
/-- Corecursor for the M-type defined by `F`. -/
protected def corec (i : X) : M F :=
{ approx := s_corec f i,
consistent := P_corec _ _ }
variables {F}
/-- given a tree generated by `F`, `head` gives us the first piece of data
it contains -/
def head (x : M F) :=
head' (x.1 1)
/-- return all the subtrees of the root of a tree `x : M F` -/
def children (x : M F) (i : F.B (head x)) : M F :=
let H := λ n : ℕ, @head_succ' _ n 0 x.1 x.2 in
{ approx := λ n, children' (x.1 _) (cast (congr_arg _ $ by simp only [head,H]; refl) i),
consistent :=
begin
intro,
have P' := x.2 (succ n),
apply agree_children _ _ _ P',
transitivity i,
apply cast_heq,
symmetry,
apply cast_heq,
end }
/-- select a subtree using a `i : F.Idx` or return an arbitrary tree if
`i` designates no subtree of `x` -/
def ichildren [inhabited (M F)] [decidable_eq F.A] (i : F.Idx) (x : M F) : M F :=
if H' : i.1 = head x
then children x (cast (congr_arg _ $ by simp only [head,H']; refl) i.2)
else default
lemma head_succ (n m : ℕ) (x : M F) :
head' (x.approx (succ n)) = head' (x.approx (succ m)) :=
head_succ' n m _ x.consistent
lemma head_eq_head' : Π (x : M F) (n : ℕ),
head x = head' (x.approx $ n+1)
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma head'_eq_head : Π (x : M F) (n : ℕ),
head' (x.approx $ n+1) = head x
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma truncate_approx (x : M F) (n : ℕ) :
truncate (x.approx $ n+1) = x.approx n :=
truncate_eq_of_agree _ _ (x.consistent _)
/-- unfold an M-type -/
def dest : M F → F.obj (M F)
| x := ⟨head x,λ i, children x i ⟩
namespace approx
/-- generates the approximations needed for `M.mk` -/
protected def s_mk (x : F.obj $ M F) : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro x.1 (λ i, (x.2 i).approx n)
protected lemma P_mk (x : F.obj $ M F)
: all_agree (approx.s_mk x)
| 0 := by { constructor }
| (succ n) := by { constructor, introv,
apply (x.2 i).consistent }
end approx
/-- constructor for M-types -/
protected def mk (x : F.obj $ M F) : M F :=
{ approx := approx.s_mk x,
consistent := approx.P_mk x }
/-- `agree' n` relates two trees of type `M F` that
are the same up to dept `n` -/
inductive agree' : ℕ → M F → M F → Prop
| trivial (x y : M F) : agree' 0 x y
| step {n : ℕ} {a} (x y : F.B a → M F) {x' y'} :
x' = M.mk ⟨a,x⟩ →
y' = M.mk ⟨a,y⟩ →
(∀ i, agree' n (x i) (y i)) →
agree' (succ n) x' y'
@[simp]
lemma dest_mk (x : F.obj $ M F) :
dest (M.mk x) = x :=
begin
funext i,
dsimp only [M.mk,dest],
cases x with x ch, congr' with i,
cases h : ch i,
simp only [children,M.approx.s_mk,children',cast_eq],
dsimp only [M.approx.s_mk,children'],
congr, rw h,
end
@[simp] lemma mk_dest (x : M F) :
M.mk (dest x) = x :=
begin
apply ext', intro n,
dsimp only [M.mk],
induction n with n,
{ apply subsingleton.elim },
dsimp only [approx.s_mk,dest,head],
cases h : x.approx (succ n) with _ hd ch,
have h' : hd = head' (x.approx 1),
{ rw [← head_succ' n,h,head'], apply x.consistent },
revert ch, rw h', intros, congr,
{ ext a, dsimp only [children],
generalize hh : cast _ a = a'',
rw cast_eq_iff_heq at hh,
revert a'',
rw h, intros, cases hh, refl },
end
lemma mk_inj {x y : F.obj $ M F}
(h : M.mk x = M.mk y) : x = y :=
by rw [← dest_mk x,h,dest_mk]
/-- destructor for M-types -/
protected def cases {r : M F → Sort w}
(f : ∀ (x : F.obj $ M F), r (M.mk x)) (x : M F) : r x :=
suffices r (M.mk (dest x)),
by { haveI := classical.prop_decidable,
haveI := inhabited.mk x,
rw [← mk_dest x], exact this },
f _
/-- destructor for M-types -/
protected def cases_on {r : M F → Sort w}
(x : M F) (f : ∀ (x : F.obj $ M F), r (M.mk x)) : r x :=
M.cases f x
/-- destructor for M-types, similar to `cases_on` but also
gives access directly to the root and subtrees on an M-type -/
protected def cases_on' {r : M F → Sort w}
(x : M F) (f : ∀ a f, r (M.mk ⟨a,f⟩)) : r x :=
M.cases_on x (λ ⟨a,g⟩, f a _)
lemma approx_mk (a : F.A) (f : F.B a → M F) (i : ℕ) :
(M.mk ⟨a, f⟩).approx (succ i) = cofix_a.intro a (λ j, (f j).approx i) :=
rfl
@[simp] lemma agree'_refl {n : ℕ} (x : M F) :
agree' n x x :=
by { induction n generalizing x; induction x using pfunctor.M.cases_on';
constructor; try { refl }, intros, apply n_ih }
lemma agree_iff_agree' {n : ℕ} (x y : M F) :
agree (x.approx n) (y.approx $ n+1) ↔ agree' n x y :=
begin
split; intros h,
{ induction n generalizing x y, constructor,
{ induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk] at h, cases h with _ _ _ _ _ _ hagree,
constructor; try { refl },
intro i, apply n_ih, apply hagree } },
{ induction n generalizing x y, constructor,
{ cases h,
induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk],
have h_a_1 := mk_inj ‹M.mk ⟨x_a, x_f⟩ = M.mk ⟨h_a, h_x⟩›, cases h_a_1,
replace h_a_2 := mk_inj ‹M.mk ⟨y_a, y_f⟩ = M.mk ⟨h_a, h_y⟩›, cases h_a_2,
constructor, intro i, apply n_ih, simp * } },
end
@[simp]
lemma cases_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π (x : F.obj $ M F), r (M.mk x)) :
pfunctor.M.cases f (M.mk x) = f x :=
begin
dsimp only [M.mk,pfunctor.M.cases,dest,head,approx.s_mk,head'],
cases x, dsimp only [approx.s_mk],
apply eq_of_heq,
apply rec_heq_of_heq, congr' with x,
dsimp only [children,approx.s_mk,children'],
cases h : x_snd x, dsimp only [head],
congr' with n, change (x_snd (x)).approx n = _, rw h
end
@[simp]
lemma cases_on_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π x : F.obj $ M F, r (M.mk x)) :
pfunctor.M.cases_on (M.mk x) f = f x :=
cases_mk x f
@[simp]
lemma cases_on_mk'
{r : M F → Sort*} {a} (x : F.B a → M F) (f : Π a (f : F.B a → M F), r (M.mk ⟨a,f⟩)) :
pfunctor.M.cases_on' (M.mk ⟨a,x⟩) f = f a x :=
cases_mk ⟨_,x⟩ _
/-- `is_path p x` tells us if `p` is a valid path through `x` -/
inductive is_path : path F → M F → Prop
| nil (x : M F) : is_path [] x
| cons (xs : path F) {a} (x : M F) (f : F.B a → M F) (i : F.B a) :
x = M.mk ⟨a,f⟩ →
is_path xs (f i) →
is_path (⟨a,i⟩ :: xs) x
lemma is_path_cons {xs : path F} {a a'} {f : F.B a → M F} {i : F.B a'} :
is_path (⟨a',i⟩ :: xs) (M.mk ⟨a,f⟩) → a = a' :=
begin
generalize h : (M.mk ⟨a,f⟩) = x,
rintro (_ | ⟨_, _, _, _, rfl, _⟩),
cases mk_inj h,
refl
end
lemma is_path_cons' {xs : path F} {a} {f : F.B a → M F} {i : F.B a} :
is_path (⟨a,i⟩ :: xs) (M.mk ⟨a,f⟩) → is_path xs (f i) :=
begin
generalize h : (M.mk ⟨a,f⟩) = x,
rintro (_ | ⟨_, _, _, _, rfl, hp⟩),
cases mk_inj h,
exact hp
end
/-- follow a path through a value of `M F` and return the subtree
found at the end of the path if it is a valid path for that value and
return a default tree -/
def isubtree [decidable_eq F.A] [inhabited (M F)] : path F → M F → M F
| [] x := x
| (⟨a, i⟩ :: ps) x :=
pfunctor.M.cases_on' x (λ a' f,
(if h : a = a' then isubtree ps (f $ cast (by rw h) i)
else default : (λ x, M F) (M.mk ⟨a',f⟩)))
/-- similar to `isubtree` but returns the data at the end of the path instead
of the whole subtree -/
def iselect [decidable_eq F.A] [inhabited (M F)] (ps : path F) : M F → F.A :=
λ (x : M F), head $ isubtree ps x
lemma iselect_eq_default [decidable_eq F.A] [inhabited (M F)] (ps : path F) (x : M F)
(h : ¬ is_path ps x) :
iselect ps x = head default :=
begin
induction ps generalizing x,
{ exfalso, apply h, constructor },
{ cases ps_hd with a i,
induction x using pfunctor.M.cases_on',
simp only [iselect,isubtree] at ps_ih ⊢,
by_cases h'' : a = x_a, subst x_a,
{ simp only [dif_pos, eq_self_iff_true, cases_on_mk'],
rw ps_ih, intro h', apply h,
constructor; try { refl }, apply h' },
{ simp * } }
end
@[simp] lemma head_mk (x : F.obj (M F)) :
head (M.mk x) = x.1 :=
eq.symm $
calc x.1
= (dest (M.mk x)).1 : by rw dest_mk
... = head (M.mk x) : by refl
lemma children_mk {a} (x : F.B a → (M F)) (i : F.B (head (M.mk ⟨a,x⟩))) :
children (M.mk ⟨a,x⟩) i = x (cast (by rw head_mk) i) :=
by apply ext'; intro n; refl
@[simp]
lemma ichildren_mk [decidable_eq F.A] [inhabited (M F)] (x : F.obj (M F)) (i : F.Idx) :
ichildren i (M.mk x) = x.iget i :=
by { dsimp only [ichildren,pfunctor.obj.iget],
congr' with h, apply ext',
dsimp only [children',M.mk,approx.s_mk],
intros, refl }
@[simp]
lemma isubtree_cons
[decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i : F.B a} :
isubtree (⟨_,i⟩ :: ps) (M.mk ⟨a,f⟩) = isubtree ps (f i) :=
by simp only [isubtree,ichildren_mk,pfunctor.obj.iget,dif_pos,isubtree,M.cases_on_mk']; refl
@[simp]
lemma iselect_nil [decidable_eq F.A] [inhabited (M F)] {a} (f : F.B a → M F) :
iselect nil (M.mk ⟨a,f⟩) = a :=
by refl
@[simp]
lemma iselect_cons [decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i} :
iselect (⟨a,i⟩ :: ps) (M.mk ⟨a,f⟩) = iselect ps (f i) :=
by simp only [iselect,isubtree_cons]
lemma corec_def {X} (f : X → F.obj X) (x₀ : X) :
M.corec f x₀ = M.mk (M.corec f <$> f x₀) :=
begin
dsimp only [M.corec,M.mk],
congr' with n,
cases n with n,
{ dsimp only [s_corec,approx.s_mk], refl, },
{ dsimp only [s_corec,approx.s_mk], cases h : (f x₀),
dsimp only [(<$>),pfunctor.map],
congr, }
end
lemma ext_aux [inhabited (M F)] [decidable_eq F.A] {n : ℕ} (x y z : M F)
(hx : agree' n z x)
(hy : agree' n z y)
(hrec : ∀ (ps : path F),
n = ps.length →
iselect ps x = iselect ps y) :
x.approx (n+1) = y.approx (n+1) :=
begin
induction n with n generalizing x y z,
{ specialize hrec [] rfl,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
simp only [iselect_nil] at hrec, subst hrec,
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
apply subsingleton.elim },
{ cases hx, cases hy,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
subst z,
iterate 3 { have := mk_inj ‹_›, repeat { cases this } },
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
ext i, apply n_ih,
{ solve_by_elim },
{ solve_by_elim },
introv h, specialize hrec (⟨_,i⟩ :: ps) (congr_arg _ h),
simp only [iselect_cons] at hrec, exact hrec }
end
open pfunctor.approx
variables {F}
local attribute [instance, priority 0] classical.prop_decidable
lemma ext [inhabited (M F)]
(x y : M F)
(H : ∀ (ps : path F), iselect ps x = iselect ps y) :
x = y :=
begin
apply ext', intro i,
induction i with i,
{ cases x.approx 0, cases y.approx 0, constructor },
{ apply ext_aux x y x,
{ rw ← agree_iff_agree', apply x.consistent },
{ rw [← agree_iff_agree',i_ih], apply y.consistent },
introv H',
dsimp only [iselect] at H,
cases H',
apply H ps }
end
section bisim
variable (R : M F → M F → Prop)
local infix ` ~ `:50 := R
/-- Bisimulation is the standard proof technique for equality between
infinite tree-like structures -/
structure is_bisimulation : Prop :=
(head : ∀ {a a'} {f f'}, M.mk ⟨a,f⟩ ~ M.mk ⟨a',f'⟩ → a = a')
(tail : ∀ {a} {f f' : F.B a → M F},
M.mk ⟨a,f⟩ ~ M.mk ⟨a,f'⟩ →
(∀ (i : F.B a), f i ~ f' i) )
theorem nth_of_bisim [inhabited (M F)] (bisim : is_bisimulation R) (s₁ s₂) (ps : path F) :
s₁ ~ s₂ →
is_path ps s₁ ∨ is_path ps s₂ →
iselect ps s₁ = iselect ps s₂ ∧
∃ a (f f' : F.B a → M F),
isubtree ps s₁ = M.mk ⟨a,f⟩ ∧
isubtree ps s₂ = M.mk ⟨a,f'⟩ ∧
∀ (i : F.B a), f i ~ f' i :=
begin
intros h₀ hh,
induction s₁ using pfunctor.M.cases_on' with a f,
induction s₂ using pfunctor.M.cases_on' with a' f',
obtain rfl : a = a' := bisim.head h₀,
induction ps with i ps generalizing a f f',
{ existsi [rfl,a,f,f',rfl,rfl],
apply bisim.tail h₀ },
cases i with a' i,
obtain rfl : a = a',
{ cases hh; cases is_path_cons hh; refl },
dsimp only [iselect] at ps_ih ⊢,
have h₁ := bisim.tail h₀ i,
induction h : (f i) using pfunctor.M.cases_on' with a₀ f₀,
induction h' : (f' i) using pfunctor.M.cases_on' with a₁ f₁,
simp only [h,h',isubtree_cons] at ps_ih ⊢,
rw [h,h'] at h₁,
obtain rfl : a₀ = a₁ := bisim.head h₁,
apply (ps_ih _ _ _ h₁),
rw [← h,← h'], apply or_of_or_of_imp_of_imp hh is_path_cons' is_path_cons'
end
theorem eq_of_bisim [nonempty (M F)] (bisim : is_bisimulation R) : ∀ s₁ s₂, s₁ ~ s₂ → s₁ = s₂ :=
begin
inhabit (M F),
introv Hr, apply ext,
introv,
by_cases h : is_path ps s₁ ∨ is_path ps s₂,
{ have H := nth_of_bisim R bisim _ _ ps Hr h,
exact H.left },
{ rw not_or_distrib at h, cases h with h₀ h₁,
simp only [iselect_eq_default,*,not_false_iff] }
end
end bisim
universes u' v'
/-- corecursor for `M F` with swapped arguments -/
def corec_on {X : Type*} (x₀ : X) (f : X → F.obj X) : M F :=
M.corec f x₀
variables {P : pfunctor.{u}} {α : Type u}
lemma dest_corec (g : α → P.obj α) (x : α) :
M.dest (M.corec g x) = M.corec g <$> g x :=
by rw [corec_def,dest_mk]
lemma bisim (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
begin
introv h',
haveI := inhabited.mk x.head,
apply eq_of_bisim R _ _ _ h', clear h' x y,
split; introv ih;
rcases h _ _ ih with ⟨ a'', g, g', h₀, h₁, h₂ ⟩; clear h,
{ replace h₀ := congr_arg sigma.fst h₀,
replace h₁ := congr_arg sigma.fst h₁,
simp only [dest_mk] at h₀ h₁,
rw [h₀,h₁], },
{ simp only [dest_mk] at h₀ h₁,
cases h₀, cases h₁,
apply h₂, },
end
theorem bisim' {α : Type*} (Q : α → Prop) (u v : α → M P)
(h : ∀ x, Q x → ∃ a f f',
M.dest (u x) = ⟨a, f⟩ ∧
M.dest (v x) = ⟨a, f'⟩ ∧
∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x :=
λ x Qx,
let R := λ w z : M P, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in
@M.bisim P R
(λ x y ⟨x', Qx', xeq, yeq⟩,
let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx' in
⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩)
_ _ ⟨x, Qx, rfl, rfl⟩
-- for the record, show M_bisim follows from _bisim'
theorem bisim_equiv (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
λ x y Rxy,
let Q : M P × M P → Prop := λ p, R p.fst p.snd in
bisim' Q prod.fst prod.snd
(λ p Qp,
let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp in
⟨a, f, f', hx, hy, λ i, ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩)
⟨x, y⟩ Rxy
theorem corec_unique (g : α → P.obj α) (f : α → M P)
(hyp : ∀ x, M.dest (f x) = f <$> (g x)) :
f = M.corec g :=
begin
ext x,
apply bisim' (λ x, true) _ _ _ _ trivial,
clear x,
intros x _,
cases gxeq : g x with a f',
have h₀ : M.dest (f x) = ⟨a, f ∘ f'⟩,
{ rw [hyp, gxeq, pfunctor.map_eq] },
have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩,
{ rw [dest_corec, gxeq, pfunctor.map_eq], },
refine ⟨_, _, _, h₀, h₁, _⟩,
intro i,
exact ⟨f' i, trivial, rfl, rfl⟩
end
/-- corecursor where the state of the computation can be sent downstream
in the form of a recursive call -/
def corec₁ {α : Type u} (F : Π X, (α → X) → α → P.obj X) : α → M P :=
M.corec (F _ id)
/-- corecursor where it is possible to return a fully formed value at any point
of the computation -/
def corec' {α : Type u} (F : Π {X : Type u}, (α → X) → α → M P ⊕ P.obj X) (x : α) : M P :=
corec₁
(λ X rec (a : M P ⊕ α),
let y := a >>= F (rec ∘ sum.inr) in
match y with
| sum.inr y := y
| sum.inl y := (rec ∘ sum.inl) <$> M.dest y
end )
(@sum.inr (M P) _ x)
end M
end pfunctor
|
b051d688f5df28e91d20570029a0bebc7f52e57f | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/monad/basic.lean | bf381046a61ad54a8ae02d92fc9abeed3ad4292f | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,306 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta, Adam Topaz
-/
import category_theory.functor_category
import category_theory.fully_faithful
namespace category_theory
open category
universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes].
variables (C : Type u₁) [category.{v₁} C]
/--
The data of a monad on C consists of an endofunctor T together with natural transformations
η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations:
- T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity)
- η_(TX) ≫ μ_X = 1_X (left unit)
- Tη_X ≫ μ_X = 1_X (right unit)
-/
structure monad extends C ⥤ C :=
(η' [] : 𝟭 _ ⟶ to_functor)
(μ' [] : to_functor ⋙ to_functor ⟶ to_functor)
(assoc' : ∀ X, to_functor.map (nat_trans.app μ' X) ≫ μ'.app _ = μ'.app _ ≫ μ'.app _ . obviously)
(left_unit' : ∀ X : C, η'.app (to_functor.obj X) ≫ μ'.app _ = 𝟙 _ . obviously)
(right_unit' : ∀ X : C, to_functor.map (η'.app X) ≫ μ'.app _ = 𝟙 _ . obviously)
/--
The data of a comonad on C consists of an endofunctor G together with natural transformations
ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations:
- δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity)
- δ_X ≫ ε_(GX) = 1_X (left counit)
- δ_X ≫ G ε_X = 1_X (right counit)
-/
structure comonad extends C ⥤ C :=
(ε' [] : to_functor ⟶ 𝟭 _)
(δ' [] : to_functor ⟶ to_functor ⋙ to_functor)
(coassoc' : ∀ X, nat_trans.app δ' _ ≫ to_functor.map (δ'.app X) = δ'.app _ ≫ δ'.app _ . obviously)
(left_counit' : ∀ X : C, δ'.app X ≫ ε'.app (to_functor.obj X) = 𝟙 _ . obviously)
(right_counit' : ∀ X : C, δ'.app X ≫ to_functor.map (ε'.app X) = 𝟙 _ . obviously)
variables {C} (T : monad C) (G : comonad C)
instance coe_monad : has_coe (monad C) (C ⥤ C) := ⟨λ T, T.to_functor⟩
instance coe_comonad : has_coe (comonad C) (C ⥤ C) := ⟨λ G, G.to_functor⟩
@[simp] lemma monad_to_functor_eq_coe : T.to_functor = T := rfl
@[simp] lemma comonad_to_functor_eq_coe : G.to_functor = G := rfl
/-- The unit for the monad `T`. -/
def monad.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η'
/-- The multiplication for the monad `T`. -/
def monad.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ T := T.μ'
/-- The counit for the comonad `G`. -/
def comonad.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε'
/-- The comultiplication for the comonad `G`. -/
def comonad.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ G := G.δ'
/-- A custom simps projection for the functor part of a monad, as a coercion. -/
def monad.simps.to_functor := (T : C ⥤ C)
/-- A custom simps projection for the unit of a monad, in simp normal form. -/
def monad.simps.η' : 𝟭 _ ⟶ (T : C ⥤ C) := T.η
/-- A custom simps projection for the multiplication of a monad, in simp normal form. -/
def monad.simps.μ' : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ (T : C ⥤ C) := T.μ
/-- A custom simps projection for the functor part of a comonad, as a coercion. -/
def comonad.simps.to_functor := (G : C ⥤ C)
/-- A custom simps projection for the counit of a comonad, in simp normal form. -/
def comonad.simps.ε' : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε
/-- A custom simps projection for the comultiplication of a comonad, in simp normal form. -/
def comonad.simps.δ' : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ (G : C ⥤ C) := G.δ
initialize_simps_projections category_theory.monad (to_functor → coe, η' → η, μ' → μ)
initialize_simps_projections category_theory.comonad (to_functor → coe, ε' → ε, δ' → δ)
@[reassoc]
lemma monad.assoc (T : monad C) (X : C) :
(T : C ⥤ C).map (T.μ.app X) ≫ T.μ.app _ = T.μ.app _ ≫ T.μ.app _ :=
T.assoc' X
@[simp, reassoc] lemma monad.left_unit (T : monad C) (X : C) :
T.η.app ((T : C ⥤ C).obj X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) :=
T.left_unit' X
@[simp, reassoc] lemma monad.right_unit (T : monad C) (X : C) :
(T : C ⥤ C).map (T.η.app X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) :=
T.right_unit' X
@[reassoc]
lemma comonad.coassoc (G : comonad C) (X : C) :
G.δ.app _ ≫ (G : C ⥤ C).map (G.δ.app X) = G.δ.app _ ≫ G.δ.app _ :=
G.coassoc' X
@[simp, reassoc] lemma comonad.left_counit (G : comonad C) (X : C) :
G.δ.app X ≫ G.ε.app ((G : C ⥤ C).obj X) = 𝟙 ((G : C ⥤ C).obj X) :=
G.left_counit' X
@[simp, reassoc] lemma comonad.right_counit (G : comonad C) (X : C) :
G.δ.app X ≫ (G : C ⥤ C).map (G.ε.app X) = 𝟙 ((G : C ⥤ C).obj X) :=
G.right_counit' X
/-- A morphism of monads is a natural transformation compatible with η and μ. -/
@[ext]
structure monad_hom (T₁ T₂ : monad C) extends nat_trans (T₁ : C ⥤ C) T₂ :=
(app_η' : ∀ {X}, T₁.η.app X ≫ app X = T₂.η.app X . obviously)
(app_μ' : ∀ {X}, T₁.μ.app X ≫ app X = ((T₁ : C ⥤ C).map (app X) ≫ app _) ≫ T₂.μ.app X . obviously)
/-- A morphism of comonads is a natural transformation compatible with ε and δ. -/
@[ext]
structure comonad_hom (M N : comonad C) extends nat_trans (M : C ⥤ C) N :=
(app_ε' : ∀ {X}, app X ≫ N.ε.app X = M.ε.app X . obviously)
(app_δ' : ∀ {X}, app X ≫ N.δ.app X = M.δ.app X ≫ app (M.obj X) ≫ N.map (app X) . obviously)
restate_axiom monad_hom.app_η'
restate_axiom monad_hom.app_μ'
attribute [simp, reassoc] monad_hom.app_η monad_hom.app_μ
restate_axiom comonad_hom.app_ε'
restate_axiom comonad_hom.app_δ'
attribute [simp, reassoc] comonad_hom.app_ε comonad_hom.app_δ
instance : category (monad C) :=
{ hom := monad_hom,
id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) },
comp := λ _ _ _ f g,
{ to_nat_trans := { app := λ X, f.app X ≫ g.app X } } }
instance : category (comonad C) :=
{ hom := comonad_hom,
id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) },
comp := λ M N L f g,
{ to_nat_trans := { app := λ X, f.app X ≫ g.app X } } }
instance {T : monad C} : inhabited (monad_hom T T) := ⟨𝟙 T⟩
@[simp] lemma monad_hom.id_to_nat_trans (T : monad C) :
(𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) :=
rfl
@[simp] lemma monad_hom.comp_to_nat_trans {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) :
(f ≫ g).to_nat_trans =
((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) :=
rfl
instance {G : comonad C} : inhabited (comonad_hom G G) := ⟨𝟙 G⟩
@[simp] lemma comonad_hom.id_to_nat_trans (T : comonad C) :
(𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) :=
rfl
@[simp] lemma comp_to_nat_trans {T₁ T₂ T₃ : comonad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) :
(f ≫ g).to_nat_trans =
((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) :=
rfl
variable (C)
/--
The forgetful functor from the category of monads to the category of endofunctors.
-/
@[simps]
def monad_to_functor : monad C ⥤ (C ⥤ C) :=
{ obj := λ T, T,
map := λ M N f, f.to_nat_trans }
instance : faithful (monad_to_functor C) := {}.
/--
The forgetful functor from the category of comonads to the category of endofunctors.
-/
@[simps]
def comonad_to_functor : comonad C ⥤ (C ⥤ C) :=
{ obj := λ G, G,
map := λ M N f, f.to_nat_trans }
instance : faithful (comonad_to_functor C) := {}.
variable {C}
/--
An isomorphism of monads gives a natural isomorphism of the underlying functors.
-/
@[simps {rhs_md := semireducible}]
def monad_iso.to_nat_iso {M N : monad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N :=
(monad_to_functor C).map_iso h
/--
An isomorphism of comonads gives a natural isomorphism of the underlying functors.
-/
@[simps {rhs_md := semireducible}]
def comonad_iso.to_nat_iso {M N : comonad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N :=
(comonad_to_functor C).map_iso h
variable (C)
namespace monad
/-- The identity monad. -/
@[simps]
def id : monad C :=
{ to_functor := 𝟭 C,
η' := 𝟙 (𝟭 C),
μ' := 𝟙 (𝟭 C) }
instance : inhabited (monad C) := ⟨monad.id C⟩
end monad
namespace comonad
/-- The identity comonad. -/
@[simps]
def id : comonad C :=
{ to_functor := 𝟭 _,
ε' := 𝟙 (𝟭 C),
δ' := 𝟙 (𝟭 C) }
instance : inhabited (comonad C) := ⟨comonad.id C⟩
end comonad
end category_theory
|
cc20999345e6f624ae5f833c9ee263fdb6d0dda1 | 4e0d7c3132ce31edc5829849735dd25db406b144 | /lean/love11_logical_foundations_of_mathematics_exercise_sheet.lean | fceab15391ba0ff5d794c806220c80738516b03d | [] | no_license | gonzalgu/logical_verification_2020 | a0013a6c22ea254e9f4d245f2948f0f4d44df4bb | 724d0457dff2c3ff10f9ab2170388f4c5e958b75 | refs/heads/master | 1,660,886,374,533 | 1,589,859,641,000 | 1,589,859,641,000 | 256,069,971 | 0 | 0 | null | 1,586,997,430,000 | 1,586,997,429,000 | null | UTF-8 | Lean | false | false | 3,142 | lean | import .love11_logical_foundations_of_mathematics_demo
/-! # LoVe Exercise 11: Logical Foundations of Mathematics -/
set_option pp.beta true
namespace LoVe
/-! ## Question 1: Vectors as Subtypes
Recall the definition of vectors from the demo: -/
#check vector
/-! The following function adds two lists of integers elementwise. If one
function is longer than the other, the tail of the longer function is
truncated. -/
def list.add : list ℤ → list ℤ → list ℤ
| [] [] := []
| (x :: xs) (y :: ys) := (x + y) :: list.add xs ys
| [] (y :: ys) := []
| (x :: xs) [] := []
/-! 1.1. Show that if the lists have the same length, the resulting list also
has that length. -/
lemma list.length_add :
∀(xs : list ℤ) (ys : list ℤ) (h : list.length xs = list.length ys),
list.length (list.add xs ys) = list.length xs
| [] [] :=
begin
simp,
refl,
end
| (x :: xs) (y :: ys) :=
begin
simp,
intro h,
rw list.add,
rw list.length,
simp,
apply list.length_add,
exact h,
end
| [] (y :: ys) :=
begin
simp,
intro h,
refl,
end
| (x :: xs) [] :=
begin
simp,
end
/-! 1.2. Define componentwise addition on vectors using `list.add` and
`length.length_add`. -/
def vector.add {n : ℕ} : vector ℤ n → vector ℤ n → vector ℤ n :=
λ v1 v2, subtype.mk (list.add (subtype.val v1) (subtype.val v2))
begin
have hl1 : (list.length v1.val) = n :=
begin
apply subtype.property v1,
end,
have hl2 : (list.length v2.val) = n :=
begin
apply subtype.property v2,
end,
rw list.length_add,
{
assumption,
},
{
cc,
}
end
/-! 1.3. Show that `list.add` and `vector.add` are commutative. -/
lemma list.add.comm :
∀(xs : list ℤ) (ys : list ℤ), list.add xs ys = list.add ys xs
| [] [] :=
begin
refl,
end
| (x::xs) [] :=
begin
repeat { rw list.add},
end
| [] (y::ys) :=
begin
repeat { rw list.add},
end
| (x::xs) (y::ys) :=
begin
rw list.add,
rw list.add,
rw add_comm,
simp,
apply list.add.comm,
end
lemma vector.add.comm {n : ℕ} (x y : vector ℤ n) :
vector.add x y = vector.add y x :=
begin
apply subtype.eq,
simp [vector.add],
apply list.add.comm,
end
/-! ## Question 2: Integers as Quotients
Recall the construction of integers from the lecture, not to be confused with
Lean's predefined type `int` (= `ℤ`): -/
#check int.rel
#check int.rel_iff
#check int
/-! 2.1. Define negation on these integers. -/
def int.neg : int → int :=
quotient.lift (λ p : ℕ × ℕ, ⟦ (p.snd, p.fst)⟧)
begin
intros a b,
intro h,
apply quotient.sound,
rw int.rel_iff at *,
simp,
rw h,
end
/-! 2.2. Prove the following lemmas about negation. -/
lemma int.neg_eq (p n : ℕ) :
int.neg ⟦(p, n)⟧ = ⟦(n, p)⟧ :=
begin
simp [int.neg],
end
lemma int.neg_neg (a : int) :
int.neg (int.neg a) = a :=
begin
apply quotient.induction_on a,
intro pn,
cases pn with p n,
rw int.neg_eq,
rw int.neg_eq,
end
end LoVe
|
1d751ec5d127fa4fce362c693f91d9865db4878b | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/sharecommon.lean | 3e8117d79679a03bea976ff8af7c22207eaa65d3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 3,913 | lean | import Std.ShareCommon
open Std
def check (b : Bool) : ShareCommonT IO Unit := do
unless b do throw $ IO.userError "check failed"
unsafe def tst1 : ShareCommonT IO Unit := do
let x := [1]
let y := [0].map (fun x => x + 1)
check $ ptrAddrUnsafe x != ptrAddrUnsafe y
let x ← shareCommonM x
let y ← shareCommonM y
check $ ptrAddrUnsafe x == ptrAddrUnsafe y
let z ← shareCommonM [2]
let x ← shareCommonM x
check $ ptrAddrUnsafe x == ptrAddrUnsafe y
check $ ptrAddrUnsafe x != ptrAddrUnsafe z
IO.println x
IO.println y
IO.println z
#eval tst1.run
unsafe def tst2 : ShareCommonT IO Unit := do
let x := [1, 2]
let y := [0, 1].map (fun x => x + 1)
check $ ptrAddrUnsafe x != ptrAddrUnsafe y
let x ← shareCommonM x
let y ← shareCommonM y
check $ ptrAddrUnsafe x == ptrAddrUnsafe y
let z ← shareCommonM [2]
let x ← shareCommonM x
check $ ptrAddrUnsafe x == ptrAddrUnsafe y
check $ ptrAddrUnsafe x != ptrAddrUnsafe z
IO.println x
IO.println y
IO.println z
#eval tst2.run
structure Foo :=
(x : Nat)
(y : Bool)
(z : Bool)
@[noinline] def mkFoo1 (x : Nat) (z : Bool) : Foo := { x := x, y := true, z := z }
@[noinline] def mkFoo2 (x : Nat) (z : Bool) : Foo := { x := x, y := true, z := z }
unsafe def tst3 : ShareCommonT IO Unit := do
let o1 := mkFoo1 10 true
let o2 := mkFoo2 10 true
let o3 := mkFoo2 10 false
check $ ptrAddrUnsafe o1 != ptrAddrUnsafe o2
check $ ptrAddrUnsafe o1 != ptrAddrUnsafe o3
let o1 ← shareCommonM o1
let o2 ← shareCommonM o2
let o3 ← shareCommonM o3
check $
o1.x == 10 && o1.y == true &&
o1.z == true && o3.z == false &&
ptrAddrUnsafe o1 == ptrAddrUnsafe o2 &&
ptrAddrUnsafe o1 != ptrAddrUnsafe o3
IO.println o1.x
pure ()
#eval tst3.run
unsafe def tst4 : ShareCommonT IO Unit := do
let x := ["hello"]
let y := ["ello"].map (fun x => "h" ++ x)
check $ ptrAddrUnsafe x != ptrAddrUnsafe y
let x ← shareCommonM x
let y ← shareCommonM y
check $ ptrAddrUnsafe x == ptrAddrUnsafe y
let z ← shareCommonM ["world"]
let x ← shareCommonM x
check $
ptrAddrUnsafe x == ptrAddrUnsafe y &&
ptrAddrUnsafe x != ptrAddrUnsafe z
IO.println x
IO.println y
IO.println z
#eval tst4.run
@[noinline] def mkList1 (x : Nat) : List Nat := List.replicate x x
@[noinline] def mkList2 (x : Nat) : List Nat := List.replicate x x
@[noinline] def mkArray1 (x : Nat) : Array (List Nat) :=
#[ mkList1 x, mkList2 x, mkList2 (x+1) ]
@[noinline] def mkArray2 (x : Nat) : Array (List Nat) :=
mkArray1 x
unsafe def tst5 : ShareCommonT IO Unit := do
let a := mkArray1 3
let b := mkArray2 3
let c := mkArray2 4
IO.println a
IO.println b
IO.println c
check $
ptrAddrUnsafe a != ptrAddrUnsafe b &&
ptrAddrUnsafe a != ptrAddrUnsafe c &&
ptrAddrUnsafe a[0] != ptrAddrUnsafe a[1] &&
ptrAddrUnsafe a[0] != ptrAddrUnsafe a[2] &&
ptrAddrUnsafe b[0] != ptrAddrUnsafe b[1] &&
ptrAddrUnsafe c[0] != ptrAddrUnsafe c[1]
let a ← shareCommonM a
let b ← shareCommonM b
let c ← shareCommonM c
check $
ptrAddrUnsafe a == ptrAddrUnsafe b &&
ptrAddrUnsafe a != ptrAddrUnsafe c &&
ptrAddrUnsafe a[0] == ptrAddrUnsafe a[1] &&
ptrAddrUnsafe a[0] != ptrAddrUnsafe a[2] &&
ptrAddrUnsafe b[0] == ptrAddrUnsafe b[1] &&
ptrAddrUnsafe c[0] == ptrAddrUnsafe c[1]
pure ()
#eval tst5.run
@[noinline] def mkByteArray1 (x : Nat) : ByteArray :=
let r := ByteArray.empty
let r := r.push x.toUInt8
let r := r.push (x+(1:Nat)).toUInt8
let r := r.push (x+(2:Nat)).toUInt8
r
@[noinline] def mkByteArray2 (x : Nat) : ByteArray :=
mkByteArray1 x
unsafe def tst6 (x : Nat) : ShareCommonT IO Unit := do
let a := [mkByteArray1 x]
let b := [mkByteArray2 x]
let c := [mkByteArray2 (x+1)]
IO.println a
IO.println b
IO.println c
check $ ptrAddrUnsafe a != ptrAddrUnsafe b
check $ ptrAddrUnsafe a != ptrAddrUnsafe c
let a ← shareCommonM a
let b ← shareCommonM b
let c ← shareCommonM c
check $ ptrAddrUnsafe a == ptrAddrUnsafe b
check $ ptrAddrUnsafe a != ptrAddrUnsafe c
pure ()
#eval (tst6 2).run
|
c9c9143f764c78d58fc93101ca95958cd4b5984b | 274748215b6d042f0d9c9a505f9551fa8e0c5f38 | /src/affine_algebraic_set/basic.lean | 3b7def334df27fba4b05b8aecebe96999197e51d | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/M4P33 | 878ecb515c77d20cc799ff1ebd78f1bf4fd65c12 | 1a179372db71ad6802d11eacbc1f02f327d55f8f | refs/heads/master | 1,607,519,867,193 | 1,583,344,297,000 | 1,583,344,297,000 | 233,316,107 | 59 | 4 | Apache-2.0 | 1,579,285,778,000 | 1,578,788,367,000 | Lean | UTF-8 | Lean | false | false | 4,764 | lean | /-
Copyright (c) 2020 Kevin Buzzard
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, and whoever else wants to join in.
-/
import data.mv_polynomial
-- We want to be able to talk about V ⊆ W if V and W are affine algebraic sets
-- We will need import order.lattice at some point I guess
import affine_algebraic_set.V_and_I
/-!
# Affine algebraic sets
This file defines affine algebraic subsets of affine n-space and proves basic properties
about them.
## Important definitions
* `affine_algebraic_set k n` -- the type of affine algebraic subsets of kⁿ.
## Notation
None as yet -- do we need 𝔸ⁿ for affine n-space?
## Implementation notes
None yet.
## References
Martin Orr's lecture notes https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/
## Tags
algebraic geometry, algebraic variety
-/
-- let k be a commutative ring (or even a semiring like ℕ)
variables {k : Type*} [comm_semiring k]
-- and let σ be any set -- but think of it as {1,2,3,...,n}. It's the set
-- which indexes the variables of the polynomial ring we're thinking about.
variable {σ : Type*}
-- In Lean, the multivariable polynomial ring k[X₁, X₂, ..., Xₙ] is
-- denoted `mv_polynomial σ k`. We could use better notation.
-- The set 𝔸ⁿ or kⁿ is denoted `σ → k` (which means maps from {1,2,...,n} to k).
-- We use local notation for this.
local notation `𝔸ⁿ` := σ → k
-- We now make some definitions which we'll need in the course.
namespace mv_polynomial -- means "multivariable polynomial"
/-- The set of zeros in kⁿ of a function f ∈ k[X₁, X₂, ..., Xₙ] -/
def zeros (f : mv_polynomial σ k) : set (σ → k) :=
{x | f.eval x = 0} -- I just want to write f(x) = 0 really
/-- x is in the zeros of f iff f(x) = 0 -/
@[simp] lemma mem_zeros (f : mv_polynomial σ k) (x : σ → k) :
x ∈ f.zeros ↔ f.eval x = 0 := iff.rfl
-- note that the next result needs that k is a field.
/-- The zeros of f * g are the union of the zeros of f and of g -/
lemma zeros_mul {k : Type*} [discrete_field k] (f g : mv_polynomial σ k) :
zeros (f * g) = zeros f ∪ zeros g :=
begin
-- two sets are equal if they have the same elements
ext,
-- and now it's not hard to prove using `mem_zeros` and other
-- equalities known to Lean's simplifier.
simp, -- TODO -- should I give the full proof here?
end
end mv_polynomial
open mv_polynomial
/-- An affine algebraic subset of kⁿ is the common zeros of a set of polynomials -/
structure affine_algebraic_set (k : Type*) [comm_semiring k] (σ : Type*) :=
-- imagine σ = {1,2,3,...,n}, the general case is no different.
-- Maps σ → k are another way of thinking about kⁿ.
-- To give an affine algebraic set is to give two things: the set itself
-- (called `carrier` in Lean) and the proof that it's in the image of 𝕍.
-- carrier ⊆ kⁿ
(carrier : set (σ → k))
-- proof that there's a set S of polynomials such that the carrier is equal to the
-- intersection of the zeros of the polynomials in the set.
(is_algebraic' : ∃ S : set (mv_polynomial σ k), carrier = 𝕍 S)
namespace affine_algebraic_set
-- this is invisible notation so mathematicians don't need to understand the definition
/-- An affine algebraic set can be regarded as a subset of 𝔸ⁿ -/
instance : has_coe_to_fun (affine_algebraic_set k σ) :=
{ F := λ _, _,
coe := carrier
}
-- use `is_algebraic'` not `is_alegbraic` because the notation's right -- no "carrier".
def is_algebraic (V : affine_algebraic_set k σ) :
∃ S : set (mv_polynomial σ k), (V : set _) = 𝕍 S :=
affine_algebraic_set.is_algebraic' V
-- Now some basic facts about affine algebraic subsets.
/-- Two affine algebraic subsets with the same carrier are equal! -/
lemma ext {V W : affine_algebraic_set k σ} : (V : set _) = W → V = W :=
begin
intro h,
cases V,
cases W,
simpa, -- TODO -- why no debugging output?
end
/-- We can talk about elements of affine algebraic subsets of kⁿ -/
instance foo : has_mem 𝔸ⁿ (affine_algebraic_set k σ) :=
⟨λ x V, x ∈ V.carrier⟩
-- Computer scientists insist on using ≤ for any order relation such as ⊆ .
-- It is some sort of problem with notation I think.
instance : has_le (affine_algebraic_set k σ) :=
⟨λ V W, (V : set 𝔸ⁿ) ⊆ W⟩
instance : partial_order (affine_algebraic_set k σ) :=
{ le := (≤),
le_refl := λ _ _, id,
le_trans := λ _ _ _, set.subset.trans,
le_antisymm := λ U V hUV hVU, ext (set.subset.antisymm hUV hVU)
}
/-- Mathematicians want to talk about affine algebraic subsets of kⁿ
being subsets of one another -/
instance : has_subset (affine_algebraic_set k σ) :=
⟨affine_algebraic_set.has_le.le⟩
end affine_algebraic_set
|
55bae8f4e962bc266628bd34ed48a4e5e90474e4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/geometry/manifold/algebra/smooth_functions.lean | 47e08e8c88e995b8d129001184a345a37951a9ec | [
"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,489 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.algebra.structures
/-!
# Algebraic structures over smooth functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we define instances of algebraic structures over smooth functions.
-/
noncomputable theory
open_locale manifold
open topological_space
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{N : Type*} [topological_space N] [charted_space H N]
{E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''}
{N' : Type*} [topological_space N'] [charted_space H'' N']
namespace smooth_map
@[to_additive]
instance has_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G]
[has_smooth_mul I' G] :
has_mul C^∞⟮I, N; I', G⟯ :=
⟨λ f g, ⟨f * g, f.smooth.mul g.smooth⟩⟩
@[simp, to_additive]
lemma coe_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G]
[has_smooth_mul I' G] (f g : C^∞⟮I, N; I', G⟯) :
⇑(f * g) = f * g := rfl
@[simp, to_additive] lemma mul_comp {G : Type*} [has_mul G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] (f g : C^∞⟮I'', N'; I', G⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(f * g).comp h = (f.comp h) * (g.comp h) :=
by ext; simp only [cont_mdiff_map.comp_apply, coe_mul, pi.mul_apply]
@[to_additive]
instance has_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] :
has_one C^∞⟮I, N; I', G⟯ :=
⟨cont_mdiff_map.const (1 : G)⟩
@[simp, to_additive]
lemma coe_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] :
⇑(1 : C^∞⟮I, N; I', G⟯) = 1 := rfl
section group_structure
/-!
### Group structure
In this section we show that smooth functions valued in a Lie group inherit a group structure
under pointwise multiplication.
-/
@[to_additive]
instance semigroup {G : Type*} [semigroup G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
semigroup C^∞⟮I, N; I', G⟯ :=
{ mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _,
..smooth_map.has_mul}
@[to_additive]
instance monoid {G : Type*} [monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
monoid C^∞⟮I, N; I', G⟯ :=
{ one_mul := λ a, by ext; exact one_mul _,
mul_one := λ a, by ext; exact mul_one _,
..smooth_map.semigroup,
..smooth_map.has_one }
/-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/
@[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.",
simps]
def coe_fn_monoid_hom {G : Type*} [monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] : C^∞⟮I, N; I', G⟯ →* (N → G) :=
{ to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul }
variables (I N)
/-- For a manifold `N` and a smooth homomorphism `φ` between Lie groups `G'`, `G''`, the
'left-composition-by-`φ`' group homomorphism from `C^∞⟮I, N; I', G'⟯` to `C^∞⟮I, N; I'', G''⟯`. -/
@[to_additive "For a manifold `N` and a smooth homomorphism `φ` between additive Lie groups `G'`,
`G''`, the 'left-composition-by-`φ`' group homomorphism from `C^∞⟮I, N; I', G'⟯` to
`C^∞⟮I, N; I'', G''⟯`."]
def comp_left_monoid_hom
{G' : Type*} [monoid G'] [topological_space G'] [charted_space H' G'] [has_smooth_mul I' G']
{G'' : Type*} [monoid G''] [topological_space G''] [charted_space H'' G'']
[has_smooth_mul I'' G''] (φ : G' →* G'') (hφ : smooth I' I'' φ) :
C^∞⟮I, N; I', G'⟯ →* C^∞⟮I, N; I'', G''⟯ :=
{ to_fun := λ f, ⟨φ ∘ f, λ x, (hφ.smooth _).comp x (f.cont_mdiff x)⟩,
map_one' := by ext x; show φ 1 = 1; simp,
map_mul' := λ f g, by ext x; show φ (f x * g x) = φ (f x) * φ (g x); simp }
variables (I') {N}
/-- For a Lie group `G` and open sets `U ⊆ V` in `N`, the 'restriction' group homomorphism from
`C^∞⟮I, V; I', G⟯` to `C^∞⟮I, U; I', G⟯`. -/
@[to_additive "For an additive Lie group `G` and open sets `U ⊆ V` in `N`, the 'restriction' group
homomorphism from `C^∞⟮I, V; I', G⟯` to `C^∞⟮I, U; I', G⟯`."]
def restrict_monoid_hom
(G : Type*) [monoid G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G]
{U V : opens N} (h : U ≤ V) :
C^∞⟮I, V; I', G⟯ →* C^∞⟮I, U; I', G⟯ :=
{ to_fun := λ f, ⟨f ∘ set.inclusion h, f.smooth.comp (smooth_inclusion h)⟩,
map_one' := rfl,
map_mul' := λ f g, rfl }
variables {I N I' N'}
@[to_additive]
instance comm_monoid {G : Type*} [comm_monoid G] [topological_space G]
[charted_space H' G] [has_smooth_mul I' G] :
comm_monoid C^∞⟮I, N; I', G⟯ :=
{ mul_comm := λ a b, by ext; exact mul_comm _ _,
..smooth_map.monoid,
..smooth_map.has_one }
@[to_additive]
instance group {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] :
group C^∞⟮I, N; I', G⟯ :=
{ inv := λ f, ⟨λ x, (f x)⁻¹, f.smooth.inv⟩,
mul_left_inv := λ a, by ext; exact mul_left_inv _,
div := λ f g, ⟨f / g, f.smooth.div g.smooth⟩,
div_eq_mul_inv := λ f g, by ext; exact div_eq_mul_inv _ _,
.. smooth_map.monoid }
@[simp, to_additive]
lemma coe_inv {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] (f : C^∞⟮I, N; I', G⟯) :
⇑f⁻¹ = f⁻¹ := rfl
@[simp, to_additive]
lemma coe_div {G : Type*} [group G] [topological_space G]
[charted_space H' G] [lie_group I' G] (f g : C^∞⟮I, N; I', G⟯) :
⇑(f / g) = f / g :=
rfl
@[to_additive]
instance comm_group {G : Type*} [comm_group G] [topological_space G]
[charted_space H' G] [lie_group I' G] :
comm_group C^∞⟮I, N; I', G⟯ :=
{ ..smooth_map.group,
..smooth_map.comm_monoid }
end group_structure
section ring_structure
/-!
### Ring stucture
In this section we show that smooth functions valued in a smooth ring `R` inherit a ring structure
under pointwise multiplication.
-/
instance semiring {R : Type*} [semiring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
semiring C^∞⟮I, N; I', R⟯ :=
{ left_distrib := λ a b c, by ext; exact left_distrib _ _ _,
right_distrib := λ a b c, by ext; exact right_distrib _ _ _,
zero_mul := λ a, by ext; exact zero_mul _,
mul_zero := λ a, by ext; exact mul_zero _,
..smooth_map.add_comm_monoid,
..smooth_map.monoid }
instance ring {R : Type*} [ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map.semiring,
..smooth_map.add_comm_group, }
instance comm_ring {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] :
comm_ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map.semiring,
..smooth_map.add_comm_group,
..smooth_map.comm_monoid,}
variables (I N)
/-- For a manifold `N` and a smooth homomorphism `φ` between smooth rings `R'`, `R''`, the
'left-composition-by-`φ`' ring homomorphism from `C^∞⟮I, N; I', R'⟯` to `C^∞⟮I, N; I'', R''⟯`. -/
def comp_left_ring_hom
{R' : Type*} [ring R'] [topological_space R'] [charted_space H' R'] [smooth_ring I' R']
{R'' : Type*} [ring R''] [topological_space R''] [charted_space H'' R''] [smooth_ring I'' R'']
(φ : R' →+* R'') (hφ : smooth I' I'' φ) :
C^∞⟮I, N; I', R'⟯ →+* C^∞⟮I, N; I'', R''⟯ :=
{ to_fun := λ f, ⟨φ ∘ f, λ x, (hφ.smooth _).comp x (f.cont_mdiff x)⟩,
.. smooth_map.comp_left_monoid_hom I N φ.to_monoid_hom hφ,
.. smooth_map.comp_left_add_monoid_hom I N φ.to_add_monoid_hom hφ }
variables (I') {N}
/-- For a "smooth ring" `R` and open sets `U ⊆ V` in `N`, the "restriction" ring homomorphism from
`C^∞⟮I, V; I', R⟯` to `C^∞⟮I, U; I', R⟯`. -/
def restrict_ring_hom
(R : Type*) [ring R] [topological_space R] [charted_space H' R] [smooth_ring I' R]
{U V : opens N} (h : U ≤ V) :
C^∞⟮I, V; I', R⟯ →+* C^∞⟮I, U; I', R⟯ :=
{ to_fun := λ f, ⟨f ∘ set.inclusion h, f.smooth.comp (smooth_inclusion h)⟩,
.. smooth_map.restrict_monoid_hom I I' R h,
.. smooth_map.restrict_add_monoid_hom I I' R h }
variables {I N I' N'}
/-- Coercion to a function as a `ring_hom`. -/
@[simps]
def coe_fn_ring_hom {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] : C^∞⟮I, N; I', R⟯ →+* (N → R) :=
{ to_fun := coe_fn,
..(coe_fn_monoid_hom : C^∞⟮I, N; I', R⟯ →* _),
..(coe_fn_add_monoid_hom : C^∞⟮I, N; I', R⟯ →+ _) }
/-- `function.eval` as a `ring_hom` on the ring of smooth functions. -/
def eval_ring_hom {R : Type*} [comm_ring R] [topological_space R]
[charted_space H' R] [smooth_ring I' R] (n : N) : C^∞⟮I, N; I', R⟯ →+* R :=
(pi.eval_ring_hom _ n : (N → R) →+* R).comp smooth_map.coe_fn_ring_hom
end ring_structure
section module_structure
/-!
### Semiodule stucture
In this section we show that smooth functions valued in a vector space `M` over a normed
field `𝕜` inherit a vector space structure.
-/
instance has_smul {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] :
has_smul 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ r f, ⟨r • f, smooth_const.smul f.smooth⟩⟩
@[simp]
lemma coe_smul {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V]
(r : 𝕜) (f : C^∞⟮I, N; 𝓘(𝕜, V), V⟯) :
⇑(r • f) = r • f := rfl
@[simp] lemma smul_comp {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V]
(r : 𝕜) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(r • g).comp h = r • (g.comp h) := rfl
instance module {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] :
module 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
function.injective.module 𝕜 coe_fn_add_monoid_hom cont_mdiff_map.coe_inj coe_smul
/-- Coercion to a function as a `linear_map`. -/
@[simps]
def coe_fn_linear_map {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] :
C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →ₗ[𝕜] (N → V) :=
{ to_fun := coe_fn,
map_smul' := coe_smul,
..(coe_fn_add_monoid_hom : C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →+ _) }
end module_structure
section algebra_structure
/-!
### Algebra structure
In this section we show that smooth functions valued in a normed algebra `A` over a normed field `𝕜`
inherit an algebra structure.
-/
variables {A : Type*} [normed_ring A] [normed_algebra 𝕜 A] [smooth_ring 𝓘(𝕜, A) A]
/-- Smooth constant functions as a `ring_hom`. -/
def C : 𝕜 →+* C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ to_fun := λ c : 𝕜, ⟨λ x, ((algebra_map 𝕜 A) c), smooth_const⟩,
map_one' := by ext x; exact (algebra_map 𝕜 A).map_one,
map_mul' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_mul _ _,
map_zero' := by ext x; exact (algebra_map 𝕜 A).map_zero,
map_add' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_add _ _ }
instance algebra : algebra 𝕜 C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ smul := λ r f,
⟨r • f, smooth_const.smul f.smooth⟩,
to_ring_hom := smooth_map.C,
commutes' := λ c f, by ext x; exact algebra.commutes' _ _,
smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _,
..smooth_map.semiring }
/-- Coercion to a function as an `alg_hom`. -/
@[simps]
def coe_fn_alg_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →ₐ[𝕜] (N → A) :=
{ to_fun := coe_fn,
commutes' := λ r, rfl,
-- `..(smooth_map.coe_fn_ring_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →+* _)` times out for some reason
map_zero' := smooth_map.coe_zero,
map_one' := smooth_map.coe_one,
map_add' := smooth_map.coe_add,
map_mul' := smooth_map.coe_mul }
end algebra_structure
section module_over_continuous_functions
/-!
### Structure as module over scalar functions
If `V` is a module over `𝕜`, then we show that the space of smooth functions from `N` to `V`
is naturally a vector space over the ring of smooth functions from `N` to `𝕜`. -/
instance has_smul' {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] :
has_smul C^∞⟮I, N; 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ f g, ⟨λ x, (f x) • (g x), (smooth.smul f.2 g.2)⟩⟩
@[simp] lemma smul_comp' {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V]
(f : C^∞⟮I'', N'; 𝕜⟯) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) :
(f • g).comp h = (f.comp h) • (g.comp h) := rfl
instance module' {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] :
module C^∞⟮I, N; 𝓘(𝕜), 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x),
one_smul := λ f, by ext x; exact one_smul 𝕜 (f x),
zero_smul := λ f, by ext x; exact zero_smul _ _,
smul_zero := λ r, by ext x; exact smul_zero _, }
end module_over_continuous_functions
end smooth_map
|
c3a50e1b6cda6b4cbb5a2629461b406d34648a32 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/measure_theory/giry_monad.lean | 0e16bb4b9a0aa0e95e204b5288ca22dfba99e451 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,205 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import measure_theory.integration
/-!
# The Giry monad
Let X be a measurable space. The collection of all measures on X again
forms a measurable space. This construction forms a monad on
measurable spaces and measurable functions, called the Giry monad.
Note that most sources use the term "Giry monad" for the restriction
to *probability* measures. Here we include all measures on X.
See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level
monad to an honest monad of the functor `Measure : Meas ⥤ Meas`.
## References
* <https://ncatlab.org/nlab/show/Giry+monad>
## Tags
giry monad
-/
noncomputable theory
open_locale classical big_operators
open classical set filter
variables {α β γ δ ε : Type*}
namespace measure_theory
namespace measure
variables [measurable_space α] [measurable_space β]
/-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/
instance : measurable_space (measure α) :=
⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s)
lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) :=
measurable.of_comap_le $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _
lemma measurable_of_measurable_coe (f : β → measure α)
(h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) :
measurable f :=
measurable.of_le_map $ supr_le $ assume s, supr_le $ assume hs, measurable_space.comap_le_iff_le_map.2 $
by rw [measurable_space.map_comp]; exact h s hs
lemma measurable_measure {μ : α → measure β} :
measurable μ ↔ ∀(s : set β) (hs : is_measurable s), measurable (λb, μ b s) :=
⟨λ hμ s hs, (measurable_coe hs).comp hμ, measurable_of_measurable_coe μ⟩
lemma measurable_map (f : α → β) (hf : measurable f) :
measurable (λμ : measure α, map f μ) :=
measurable_of_measurable_coe _ $ assume s hs,
suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)),
by simpa [map_apply, hs, hf],
measurable_coe (hf hs)
lemma measurable_dirac :
measurable (measure.dirac : α → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
begin
simp only [dirac_apply, hs],
exact measurable_one.indicator hs
end
lemma measurable_lintegral {f : α → ennreal} (hf : measurable f) :
measurable (λμ : measure α, ∫⁻ x, f x ∂μ) :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, simple_func.lintegral],
refine measurable_supr (λ n, finset.measurable_sum _ (λ i, _)),
refine measurable_const.ennreal_mul _,
exact measurable_coe ((simple_func.eapprox f n).is_measurable_preimage _)
end
/-- Monadic join on `measure` in the category of measurable spaces and measurable
functions. -/
def join (m : measure (measure α)) : measure α :=
measure.of_measurable
(λs hs, ∫⁻ μ, μ s ∂m)
(by simp)
begin
assume f hf h,
simp [measure_Union h hf],
apply lintegral_tsum,
assume i, exact measurable_coe (hf i)
end
@[simp] lemma join_apply {m : measure (measure α)} :
∀{s : set α}, is_measurable s → join m s = ∫⁻ μ, μ s ∂m :=
measure.of_measurable_apply
lemma measurable_join : measurable (join : measure (measure α) → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
by simp only [join_apply hs]; exact measurable_lintegral (measurable_coe hs)
lemma lintegral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) :
∫⁻ x, f x ∂(join m) = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m :=
begin
rw [lintegral_eq_supr_eapprox_lintegral hf],
have : ∀n x,
join m (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) =
∫⁻ μ, μ ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x})) ∂m :=
assume n x, join_apply (simple_func.is_measurable_preimage _ _),
simp only [simple_func.lintegral, this],
transitivity,
have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal)
(hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)),
(⨆n:ℕ, ∑ r in s n, r * ∫⁻ μ, f n r μ ∂m) =
∫⁻ μ, ⨆n:ℕ, ∑ r in s n, r * f n r μ ∂m,
{ assume s f hf hm,
symmetry,
transitivity,
apply lintegral_supr,
{ assume n,
exact finset.measurable_sum _ (assume r, measurable_const.ennreal_mul (hf _ _)) },
{ exact hm },
congr, funext n,
transitivity,
apply lintegral_finset_sum,
{ assume r, exact measurable_const.ennreal_mul (hf _ _) },
congr, funext r,
apply lintegral_const_mul,
exact hf _ _ },
specialize this (λn, simple_func.range (simple_func.eapprox f n)),
specialize this
(λn r μ, μ (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})),
refine this _ _; clear this,
{ assume n r,
apply measurable_coe,
exact simple_func.is_measurable_preimage _ _ },
{ change monotone (λn μ, (simple_func.eapprox f n).lintegral μ),
assume n m h μ,
refine simple_func.lintegral_mono _ (le_refl _),
apply simple_func.monotone_eapprox,
assumption },
congr, funext μ,
symmetry,
apply lintegral_eq_supr_eapprox_lintegral,
exact hf
end
/-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable
functions. When the function `f` is not measurable the result is not well defined. -/
def bind (m : measure α) (f : α → measure β) : measure β := join (map f m)
@[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β}
(hs : is_measurable s) (hf : measurable f) :
bind m f s = ∫⁻ a, f a s ∂m :=
by rw [bind, join_apply hs, lintegral_map (measurable_coe hs) hf]
lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) :=
measurable_join.comp (measurable_map _ hg)
lemma lintegral_bind {m : measure α} {μ : α → measure β} {f : β → ennreal}
(hμ : measurable μ) (hf : measurable f) :
∫⁻ x, f x ∂ (bind m μ) = ∫⁻ a, ∫⁻ x, f x ∂(μ a) ∂m:=
(lintegral_join hf).trans (lintegral_map (measurable_lintegral hf) hμ)
lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ}
(hf : measurable f) (hg : measurable g) :
bind (bind m f) g = bind m (λa, bind (f a) g) :=
measure.ext $ assume s hs,
begin
rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), lintegral_bind hf],
{ congr, funext a,
exact (bind_apply hs hg).symm },
exact (measurable_coe hs).comp hg
end
lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a :=
measure.ext $ assume s hs, by rw [bind_apply hs hf, lintegral_dirac a ((measurable_coe hs).comp hf)]
lemma dirac_bind {m : measure α} : bind m dirac = m :=
measure.ext $ assume s hs,
by simp [bind_apply hs measurable_dirac, dirac_apply _ hs, lintegral_indicator 1 hs]
lemma map_dirac {f : α → β} (hf : measurable f) (a : α) :
map f (dirac a) = dirac (f a) :=
measure.ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply]
lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id :=
by rw [bind, map_id]
lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) :
join (map (map f) μ) = map f (join μ) :=
measure.ext $ assume s hs,
begin
rw [join_apply hs, map_apply hf hs, join_apply,
lintegral_map (measurable_coe hs) (measurable_map f hf)],
{ congr, funext ν, exact map_apply hf hs },
exact hf hs
end
lemma join_map_join (μ : measure (measure (measure α))) :
join (map join μ) = join (join μ) :=
begin
show bind μ join = join (join μ),
rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id],
apply congr_arg (bind μ),
funext ν,
exact join_eq_bind ν
end
lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ :=
dirac_bind
lemma join_dirac (μ : measure α) : join (dirac μ) = μ :=
eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _)
end measure
end measure_theory
|
1649e11355bb60bad429f610853c3dbcfc003469 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/meta/transfer.lean | a60883e6b972fec978489218826c8298e0d20bbf | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 7,529 | 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 (CMU)
-/
prelude
import init.meta.tactic init.meta.match_tactic init.relator init.meta.mk_dec_eq_instance
import init.data.list.instances
namespace transfer
open tactic expr list monad
/- Transfer rules are of the shape:
rel_t : {u} Πx, R t₁ t₂
where `u` is a list of universe parameters, `x` is a list of dependent variables, and `R` is a
relation. Then this rule will translate `t₁` (depending on `u` and `x`) into `t₂`. `u` and `x`
will be called parameters. When `R` is a relation on functions lifted from `S` and `R` the variables
bound by `S` are called arguments. `R` is generally constructed using `⇒` (i.e. `relator.lift_fun`).
As example:
rel_eq : (R ⇒ R ⇒ iff) eq t
transfer will match this rule when it sees:
(@eq α a b) and transfer it to (t a b)
Here `α` is a parameter and `a` and `b` are arguments.
TODO: add trace statements
TODO: currently the used relation must be fixed by the matched rule or through type class
inference. Maybe we want to replace this by type inference similar to Isabelle's transfer.
-/
private meta structure rel_data :=
(in_type : expr)
(out_type : expr)
(relation : expr)
meta instance has_to_tactic_format_rel_data : has_to_tactic_format rel_data :=
⟨λr, do
R ← pp r.relation,
α ← pp r.in_type,
β ← pp r.out_type,
return format!"({R}: rel ({α}) ({β}))" ⟩
private meta structure rule_data :=
(pr : expr)
(uparams : list name) -- levels not in pat
(params : list (expr × bool)) -- fst : local constant, snd = tt → param appears in pattern
(uargs : list name) -- levels not in pat
(args : list (expr × rel_data)) -- fst : local constant
(pat : pattern) -- `R c`
(out : expr) -- right-hand side `d` of rel equation `R c d`
meta instance has_to_tactic_format_rule_data : has_to_tactic_format rule_data :=
⟨λr, do
pr ← pp r.pr,
up ← pp r.uparams,
mp ← pp r.params,
ua ← pp r.uargs,
ma ← pp r.args,
pat ← pp r.pat.target,
out ← pp r.out,
return format!"{{ ⟨{pat}⟩ pr: {pr} → {out}, {up} {mp} {ua} {ma} }" ⟩
private meta def get_lift_fun : expr → tactic (list rel_data × expr)
| e :=
do {
guardb (is_constant_of (get_app_fn e) ``relator.lift_fun),
[α, β, γ, δ, R, S] ← return $ get_app_args e,
(ps, r) ← get_lift_fun S,
return (rel_data.mk α β R :: ps, r)} <|>
return ([], e)
private meta def mark_occurences (e : expr) : list expr → list (expr × bool)
| [] := []
| (h :: t) := let xs := mark_occurences t in
(h, occurs h e || any xs (λ⟨e, oc⟩, oc && occurs h e)) :: xs
private meta def analyse_rule (u' : list name) (pr : expr) : tactic rule_data := do
t ← infer_type pr,
(params, app (app r f) g) ← mk_local_pis t,
(arg_rels, R) ← get_lift_fun r,
args ← monad.for (enum arg_rels) (λ⟨n, a⟩,
prod.mk <$> mk_local_def (mk_simple_name ("a_" ++ to_string n)) a.in_type <*> pure a),
a_vars ← return $ prod.fst <$> args,
p ← head_beta (app_of_list f a_vars),
p_data ← return $ mark_occurences (app R p) params,
p_vars ← return $ list.map prod.fst (list.filter (λx, ↑x.2) p_data),
u ← return $ collect_univ_params (app R p) ∩ u',
pat ← mk_pattern (level.param <$> u) (p_vars ++ a_vars) (app R p) (level.param <$> u) (p_vars ++ a_vars),
return $ rule_data.mk pr (list.remove_all u' u) p_data u args pat g
private meta def analyse_decls : list name → tactic (list rule_data) :=
monad.mapm (λn, do
d ← get_decl n,
c ← return d.univ_params.length,
ls ← monad.for (range c) (λ_, mk_fresh_name),
analyse_rule ls (const n (ls.map level.param)))
private meta def split_params_args : list (expr × bool) → list expr → list (expr × option expr) × list expr
| ((lc, tt) :: ps) (e :: es) := let (ps', es') := split_params_args ps es in ((lc, some e) :: ps', es')
| ((lc, ff) :: ps) es := let (ps', es') := split_params_args ps es in ((lc, none) :: ps', es')
| _ es := ([], es)
private meta def param_substitutions (ctxt : list expr) :
list (expr × option expr) → tactic (list (name × expr) × list expr)
| (((local_const n _ bi t), s) :: ps) := do
(e, m) ← match s with
| (some e) := return (e, [])
| none :=
let ctxt' := list.filter (λv, occurs v t) ctxt in
let ty := pis ctxt' t in
if bi = binder_info.inst_implicit then do
guard (bi = binder_info.inst_implicit),
e ← instantiate_mvars ty >>= mk_instance,
return (e, [])
else do
mv ← mk_meta_var ty,
return (app_of_list mv ctxt', [mv])
end,
sb ← return $ instantiate_local n e,
ps ← return $ (prod.map sb (has_map.map sb)) <$> ps,
(ms, vs) ← param_substitutions ps,
return ((n, e) :: ms, m ++ vs)
| _ := return ([], [])
/- input expression a type `R a`, it finds a type `b`, s.t. there is a proof of the type `R a b`.
It return (`a`, pr : `R a b`) -/
meta def compute_transfer : list rule_data → list expr → expr → tactic (expr × expr × list expr)
| rds ctxt e := do
-- Select matching rule
(i, ps, args, ms, rd) ← first (rds.for (λrd, do
(l, m) ← match_pattern_core semireducible rd.pat e,
level_map ← monad.for rd.uparams (λl, prod.mk l <$> mk_meta_univ),
inst_univ ← return $ (λe, instantiate_univ_params e (level_map ++ zip rd.uargs l)),
(ps, args) ← return $ split_params_args (list.map (prod.map inst_univ id) rd.params) m,
(ps, ms) ← param_substitutions ctxt ps, /- this checks type class parameters -/
return (instantiate_locals ps ∘ inst_univ, ps, args, ms, rd))) <|>
(do trace e, fail "no matching rule"),
(bs, hs, mss) ← monad.for (zip rd.args args) (λ⟨⟨_, d⟩, e⟩, do
-- Argument has function type
(args, r) ← get_lift_fun (i d.relation),
((a_vars, b_vars), (R_vars, bnds)) ← monad.for (enum args) (λ⟨n, arg⟩, do
a ← mk_local_def sformat!"a{n}" arg.in_type,
b ← mk_local_def sformat!"b{n}" arg.out_type,
R ← mk_local_def sformat!"R{n}" (arg.relation a b),
return ((a, b), (R, [a, b, R]))) >>= (return ∘ prod.map unzip unzip ∘ unzip),
rds' ← monad.for R_vars (analyse_rule []),
-- Transfer argument
a ← return $ i e,
a' ← head_beta (app_of_list a a_vars),
(b, pr, ms) ← compute_transfer (rds ++ rds') (ctxt ++ a_vars) (app r a'),
b' ← head_eta (lambdas b_vars b),
return (b', [a, b', lambdas (list.join bnds) pr], ms)) >>= (return ∘ prod.map id unzip ∘ unzip),
-- Combine
b ← head_beta (app_of_list (i rd.out) bs),
pr ← return $ app_of_list (i rd.pr) (prod.snd <$> ps ++ list.join hs),
return (b, pr, ms ++ list.join mss)
meta def transfer (ds : list name) : tactic unit := do
rds ← analyse_decls ds,
tgt ← target,
(guard (¬ tgt.has_meta_var) <|>
fail "Target contains (universe) meta variables. This is not supported by transfer."),
(new_tgt, pr, ms) ← compute_transfer rds [] ((const `iff [] : expr) tgt),
new_pr ← mk_meta_var new_tgt,
/- Setup final tactic state -/
exact ((const `iff.mpr [] : expr) tgt new_tgt pr new_pr),
ms ← monad.for ms (λm, (get_assignment m >> return []) <|> return [m]),
gs ← get_goals,
set_goals (list.join ms ++ new_pr :: gs)
end transfer
|
512aee7143e74806a4dd9ca7629a3209a87fc8bb | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/tactic/tidy.lean | 979ab8907238eb9268a7bc7a27071b46af70efe4 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 3,619 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.ext
import tactic.auto_cases
import tactic.chain
import tactic.solve_by_elim
import tactic.interactive
namespace tactic
namespace tidy
meta def tidy_attribute : user_attribute := {
name := `tidy,
descr := "A tactic that should be called by `tidy`."
}
run_cmd attribute.register ``tidy_attribute
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> pure n.to_string)
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail "invalid type for @[tidy] tactic"
meta def run_tactics : tactic string :=
do names ← attribute.get_instances `tidy,
first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded"
meta def ext1_wrapper : tactic string :=
do ng ← num_goals,
ext1 [] {apply_cfg . new_goals := new_goals.all},
ng' ← num_goals,
return $ if ng' > ng then
"tactic.ext1 [] {new_goals := tactic.new_goals.all}"
else "ext1"
meta def default_tactics : list (tactic string) :=
[ reflexivity >> pure "refl",
`[exact dec_trivial] >> pure "exact dec_trivial",
propositional_goal >> assumption >> pure "assumption",
intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))),
auto_cases,
`[apply_auto_param] >> pure "apply_auto_param",
`[dsimp at *] >> pure "dsimp at *",
`[simp at *] >> pure "simp at *",
ext1_wrapper,
fsplit >> pure "fsplit",
injections_and_clear >> pure "injections_and_clear",
propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim",
`[unfold_coes] >> pure "unfold_coes",
`[unfold_aux] >> pure "unfold_aux",
tidy.run_tactics ]
meta structure cfg :=
(trace_result : bool := ff)
(trace_result_prefix : string := "/- `tidy` says -/ ")
(tactics : list (tactic string) := default_tactics)
declare_trace tidy
meta def core (cfg : cfg := {}) : tactic (list string) :=
do
results ← chain cfg.tactics,
when (cfg.trace_result ∨ is_trace_enabled_for `tidy) $
trace (cfg.trace_result_prefix ++ (", ".intercalate results)),
return results
end tidy
meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip
namespace interactive
open lean.parser interactive
/-- Use a variety of conservative tactics to solve goals.
`tidy?` reports back the tactic script it found.
The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.
This list can be overridden using `tidy { tactics := ... }`.
(The list must be a `list` of `tactic string`, so that `tidy?`
can report a usable tactic script.)
Tactics can also be added to the list by tagging them (locally) with the
`[tidy]` attribute. -/
meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) :=
tactic.tidy { trace_result := trace.is_some, ..cfg }
end interactive
@[hole_command] meta def tidy_hole_cmd : hole_command :=
{ name := "tidy",
descr := "Use `tidy` to complete the goal.",
action := λ _, do script ← tidy.core, return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] }
end tactic
|
31443891b1a33b2c5012bd4f83da6781cff8dc75 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1790.lean | c27e48df951672e448a4af8fa39025069e27ddd7 | [
"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 | 125 | lean | universes u
def foo (α : Type u) : unit → unit
| unit.star := unit.star
def foo2 (α : Type u) : unit → unit
| s := s
|
01505b4a29560f8ed822287c7c8c3d29aa4cf489 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/quaternion.lean | 8b481c51f1ec1c6d320a01617ae76a219759e5cd | [
"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 | 21,078 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import tactic.ring_exp
import algebra.algebra.basic
import algebra.opposites
import data.equiv.ring
/-!
# Quaternions
In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some
algebraic structures on `ℍ[R]`.
## Main definitions
* `quaternion_algebra R a b`, `ℍ[R, a, b]` :
[quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b`
* `quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`;
* `quaternion.norm_sq` : square of the norm of a quaternion;
* `quaternion.conj` : conjugate of a quaternion;
We also define the following algebraic structures on `ℍ[R]`:
* `ring ℍ[R, a, b]` and `algebra R ℍ[R, a, b]` : for any commutative ring `R`;
* `ring ℍ[R]` and `algebra R ℍ[R]` : for any commutative ring `R`;
* `domain ℍ[R]` : for a linear ordered commutative ring `R`;
* `division_algebra ℍ[R]` : for a linear ordered field `R`.
## Notation
The following notation is available with `open_locale quaternion`.
* `ℍ[R, c₁, c₂]` : `quaternion_algebra R c₁ c₂`
* `ℍ[R]` : quaternions over `R`.
## Implementation notes
We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer
or rational quaternions without using real numbers. In particular, all definitions in this file
are computable.
## Tags
quaternion
-/
/-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$.
Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/
@[nolint unused_arguments, ext]
structure quaternion_algebra (R : Type*) (a b : R) :=
mk {} :: (re : R) (im_i : R) (im_j : R) (im_k : R)
localized "notation `ℍ[` R`,` a`,` b `]` := quaternion_algebra R a b" in quaternion
namespace quaternion_algebra
@[simp] lemma mk.eta {R : Type*} {c₁ c₂} : ∀ a : ℍ[R, c₁, c₂], mk a.1 a.2 a.3 a.4 = a
| ⟨a₁, a₂, a₃, a₄⟩ := rfl
variables {R : Type*} [comm_ring R] {c₁ c₂ : R} (r x y z : R) (a b c : ℍ[R, c₁, c₂])
instance : has_coe_t R (ℍ[R, c₁, c₂]) := ⟨λ x, ⟨x, 0, 0, 0⟩⟩
@[simp] lemma coe_re : (x : ℍ[R, c₁, c₂]).re = x := rfl
@[simp] lemma coe_im_i : (x : ℍ[R, c₁, c₂]).im_i = 0 := rfl
@[simp] lemma coe_im_j : (x : ℍ[R, c₁, c₂]).im_j = 0 := rfl
@[simp] lemma coe_im_k : (x : ℍ[R, c₁, c₂]).im_k = 0 := rfl
lemma coe_injective : function.injective (coe : R → ℍ[R, c₁, c₂]) :=
λ x y h, congr_arg re h
@[simp] lemma coe_inj {x y : R} : (x : ℍ[R, c₁, c₂]) = y ↔ x = y := coe_injective.eq_iff
@[simps] instance : has_zero ℍ[R, c₁, c₂] := ⟨⟨0, 0, 0, 0⟩⟩
@[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R, c₁, c₂]) = 0 := rfl
instance : inhabited ℍ[R, c₁, c₂] := ⟨0⟩
@[simps] instance : has_one ℍ[R, c₁, c₂] := ⟨⟨1, 0, 0, 0⟩⟩
@[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R, c₁, c₂]) = 1 := rfl
@[simps] instance : has_add ℍ[R, c₁, c₂] :=
⟨λ a b, ⟨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4⟩⟩
@[simp] lemma mk_add_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) + mk b₁ b₂ b₃ b₄ = mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) :=
rfl
@[simps] instance : has_neg ℍ[R, c₁, c₂] := ⟨λ a, ⟨-a.1, -a.2, -a.3, -a.4⟩⟩
@[simp] lemma neg_mk (a₁ a₂ a₃ a₄ : R) : -(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨-a₁, -a₂, -a₃, -a₄⟩ :=
rfl
@[simps] instance : has_sub ℍ[R, c₁, c₂] :=
⟨λ a b, ⟨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4⟩⟩
@[simp] lemma mk_sub_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) - mk b₁ b₂ b₃ b₄ = mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) :=
rfl
/-- Multiplication is given by
* `1 * x = x * 1 = x`;
* `i * i = c₁`;
* `j * j = c₂`;
* `i * j = k`, `j * i = -k`;
* `k * k = -c₁ * c₂`;
* `i * k = c₁ * j`, `k * i = `-c₁ * j`;
* `j * k = -c₂ * i`, `k * j = c₂ * i`. -/
@[simps] instance : has_mul ℍ[R, c₁, c₂] := ⟨λ a b,
⟨a.1 * b.1 + c₁ * a.2 * b.2 + c₂ * a.3 * b.3 - c₁ * c₂ * a.4 * b.4,
a.1 * b.2 + a.2 * b.1 - c₂ * a.3 * b.4 + c₂ * a.4 * b.3,
a.1 * b.3 + c₁ * a.2 * b.4 + a.3 * b.1 - c₁ * a.4 * b.2,
a.1 * b.4 + a.2 * b.3 - a.3 * b.2 + a.4 * b.1⟩⟩
@[simp] lemma mk_mul_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) * mk b₁ b₂ b₃ b₄ =
⟨a₁ * b₁ + c₁ * a₂ * b₂ + c₂ * a₃ * b₃ - c₁ * c₂ * a₄ * b₄,
a₁ * b₂ + a₂ * b₁ - c₂ * a₃ * b₄ + c₂ * a₄ * b₃,
a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ - c₁ * a₄ * b₂,
a₁ * b₄ + a₂ * b₃ - a₃ * b₂ + a₄ * b₁⟩ := rfl
instance : ring ℍ[R, c₁, c₂] :=
by refine_struct
{ add := (+),
zero := (0 : ℍ[R, c₁, c₂]),
neg := has_neg.neg,
sub := has_sub.sub,
mul := (*),
one := 1 };
intros; ext; simp; ring_exp
instance : algebra R ℍ[R, c₁, c₂] :=
{ smul := λ r a, ⟨r * a.1, r * a.2, r * a.3, r * a.4⟩,
to_fun := coe,
map_one' := rfl,
map_zero' := rfl,
map_mul' := λ x y, by ext; simp,
map_add' := λ x y, by ext; simp,
smul_def' := λ r x, by ext; simp,
commutes' := λ r x, by ext; simp [mul_comm] }
@[simp] lemma smul_re : (r • a).re = r • a.re := rfl
@[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl
@[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl
@[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl
@[norm_cast, simp] lemma coe_add : ((x + y : R) : ℍ[R, c₁, c₂]) = x + y :=
(algebra_map R ℍ[R, c₁, c₂]).map_add x y
@[norm_cast, simp] lemma coe_sub : ((x - y : R) : ℍ[R, c₁, c₂]) = x - y :=
(algebra_map R ℍ[R, c₁, c₂]).map_sub x y
@[norm_cast, simp] lemma coe_neg : ((-x : R) : ℍ[R, c₁, c₂]) = -x :=
(algebra_map R ℍ[R, c₁, c₂]).map_neg x
@[norm_cast, simp] lemma coe_mul : ((x * y : R) : ℍ[R, c₁, c₂]) = x * y :=
(algebra_map R ℍ[R, c₁, c₂]).map_mul x y
lemma coe_commutes : ↑r * a = a * r := algebra.commutes r a
lemma coe_commute : commute ↑r a := coe_commutes r a
lemma coe_mul_eq_smul : ↑r * a = r • a := (algebra.smul_def r a).symm
lemma mul_coe_eq_smul : a * r = r • a :=
by rw [← coe_commutes, coe_mul_eq_smul]
@[norm_cast, simp] lemma coe_algebra_map : ⇑(algebra_map R ℍ[R, c₁, c₂]) = coe := rfl
lemma smul_coe : x • (y : ℍ[R, c₁, c₂]) = ↑(x * y) := by rw [coe_mul, coe_mul_eq_smul]
/-- Quaternion conjugate. -/
def conj : ℍ[R, c₁, c₂] ≃ₗ[R] ℍ[R, c₁, c₂] :=
linear_equiv.of_involutive
{ to_fun := λ a, ⟨a.1, -a.2, -a.3, -a.4⟩,
map_add' := λ a b, by ext; simp [neg_add],
map_smul' := λ r a, by ext; simp } $
λ a, by simp
@[simp] lemma re_conj : (conj a).re = a.re := rfl
@[simp] lemma im_i_conj : (conj a).im_i = - a.im_i := rfl
@[simp] lemma im_j_conj : (conj a).im_j = - a.im_j := rfl
@[simp] lemma im_k_conj : (conj a).im_k = - a.im_k := rfl
@[simp] lemma conj_conj : a.conj.conj = a := ext _ _ rfl (neg_neg _) (neg_neg _) (neg_neg _)
lemma conj_add : (a + b).conj = a.conj + b.conj := conj.map_add a b
@[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := by ext; simp; ring_exp
lemma conj_conj_mul : (a.conj * b).conj = b.conj * a :=
by rw [conj_mul, conj_conj]
lemma conj_mul_conj : (a * b.conj).conj = b * a.conj :=
by rw [conj_mul, conj_conj]
lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := by ext; simp [two_mul]
lemma self_add_conj : a + a.conj = 2 * a.re :=
by simp only [self_add_conj', two_mul, coe_add]
lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := by rw [add_comm, self_add_conj']
lemma conj_add_self : a.conj + a = 2 * a.re := by rw [add_comm, self_add_conj]
lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := eq_sub_iff_add_eq.2 a.conj_add_self'
lemma commute_conj_self : commute a.conj a :=
begin
rw [a.conj_eq_two_re_sub],
exact (coe_commute (2 * a.re) a).sub_left (commute.refl a)
end
lemma commute_self_conj : commute a a.conj :=
a.commute_conj_self.symm
lemma commute_conj_conj {a b : ℍ[R, c₁, c₂]} (h : commute a b) : commute a.conj b.conj :=
calc a.conj * b.conj = (b * a).conj : (conj_mul b a).symm
... = (a * b).conj : by rw h.eq
... = b.conj * a.conj : conj_mul a b
@[simp] lemma conj_coe : conj (x : ℍ[R, c₁, c₂]) = x := by ext; simp
lemma conj_smul : conj (r • a) = r • conj a := conj.map_smul r a
@[simp] lemma conj_one : conj (1 : ℍ[R, c₁, c₂]) = 1 := conj_coe 1
lemma eq_re_of_eq_coe {a : ℍ[R, c₁, c₂]} {x : R} (h : a = x) : a = a.re :=
by rw [h, coe_re]
lemma eq_re_iff_mem_range_coe {a : ℍ[R, c₁, c₂]} :
a = a.re ↔ a ∈ set.range (coe : R → ℍ[R, c₁, c₂]) :=
⟨λ h, ⟨a.re, h.symm⟩, λ ⟨x, h⟩, eq_re_of_eq_coe h.symm⟩
@[simp]
lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R]
{c₁ c₂ : R} {a : ℍ[R, c₁, c₂]} :
conj a = a ↔ a = a.re :=
by simp [ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero]
-- Can't use `rw ← conj_fixed` in the proof without additional assumptions
lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := by ext; simp; ring_exp
lemma mul_conj_eq_coe : a * conj a = (a * conj a).re :=
by { rw a.commute_self_conj.eq, exact a.conj_mul_eq_coe }
lemma conj_zero : conj (0 : ℍ[R, c₁, c₂]) = 0 := conj.map_zero
lemma conj_neg : (-a).conj = -a.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_neg a
lemma conj_sub : (a - b).conj = a.conj - b.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_sub a b
instance : star_ring ℍ[R, c₁, c₂] :=
{ star := conj,
star_involutive := conj_conj,
star_add := conj_add,
star_mul := conj_mul }
@[simp] lemma star_def (a : ℍ[R, c₁, c₂]) : star a = conj a := rfl
open opposite
/-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/
def conj_alg_equiv : ℍ[R, c₁, c₂] ≃ₐ[R] (ℍ[R, c₁, c₂]ᵒᵖ) :=
{ to_fun := op ∘ conj,
inv_fun := conj ∘ unop,
map_mul' := λ x y, by simp,
commutes' := λ r, by simp,
.. conj.to_add_equiv.trans op_add_equiv }
@[simp] lemma coe_conj_alg_equiv : ⇑(conj_alg_equiv : ℍ[R, c₁, c₂] ≃ₐ[R] _) = op ∘ conj := rfl
end quaternion_algebra
/-- Space of quaternions over a type. Implemented as a structure with four fields:
`re`, `im_i`, `im_j`, and `im_k`. -/
def quaternion (R : Type*) [has_one R] [has_neg R] := quaternion_algebra R (-1) (-1)
localized "notation `ℍ[` R `]` := quaternion R" in quaternion
namespace quaternion
variables {R : Type*} [comm_ring R] (r x y z : R) (a b c : ℍ[R])
export quaternion_algebra (re im_i im_j im_k)
instance : has_coe_t R ℍ[R] := quaternion_algebra.has_coe_t
instance : ring ℍ[R] := quaternion_algebra.ring
instance : inhabited ℍ[R] := quaternion_algebra.inhabited
instance : algebra R ℍ[R] := quaternion_algebra.algebra
instance : star_ring ℍ[R] := quaternion_algebra.star_ring
@[ext] lemma ext : a.re = b.re → a.im_i = b.im_i → a.im_j = b.im_j → a.im_k = b.im_k → a = b :=
quaternion_algebra.ext a b
lemma ext_iff {a b : ℍ[R]} :
a = b ↔ a.re = b.re ∧ a.im_i = b.im_i ∧ a.im_j = b.im_j ∧ a.im_k = b.im_k :=
quaternion_algebra.ext_iff a b
@[simp, norm_cast] lemma coe_re : (x : ℍ[R]).re = x := rfl
@[simp, norm_cast] lemma coe_im_i : (x : ℍ[R]).im_i = 0 := rfl
@[simp, norm_cast] lemma coe_im_j : (x : ℍ[R]).im_j = 0 := rfl
@[simp, norm_cast] lemma coe_im_k : (x : ℍ[R]).im_k = 0 := rfl
@[simp] lemma zero_re : (0 : ℍ[R]).re = 0 := rfl
@[simp] lemma zero_im_i : (0 : ℍ[R]).im_i = 0 := rfl
@[simp] lemma zero_im_j : (0 : ℍ[R]).im_j = 0 := rfl
@[simp] lemma zero_im_k : (0 : ℍ[R]).im_k = 0 := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R]) = 0 := rfl
@[simp] lemma one_re : (1 : ℍ[R]).re = 1 := rfl
@[simp] lemma one_im_i : (1 : ℍ[R]).im_i = 0 := rfl
@[simp] lemma one_im_j : (1 : ℍ[R]).im_j = 0 := rfl
@[simp] lemma one_im_k : (1 : ℍ[R]).im_k = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R]) = 1 := rfl
@[simp] lemma add_re : (a + b).re = a.re + b.re := rfl
@[simp] lemma add_im_i : (a + b).im_i = a.im_i + b.im_i := rfl
@[simp] lemma add_im_j : (a + b).im_j = a.im_j + b.im_j := rfl
@[simp] lemma add_im_k : (a + b).im_k = a.im_k + b.im_k := rfl
@[simp, norm_cast] lemma coe_add : ((x + y : R) : ℍ[R]) = x + y := quaternion_algebra.coe_add x y
@[simp] lemma neg_re : (-a).re = -a.re := rfl
@[simp] lemma neg_im_i : (-a).im_i = -a.im_i := rfl
@[simp] lemma neg_im_j : (-a).im_j = -a.im_j := rfl
@[simp] lemma neg_im_k : (-a).im_k = -a.im_k := rfl
@[simp, norm_cast] lemma coe_neg : ((-x : R) : ℍ[R]) = -x := quaternion_algebra.coe_neg x
@[simp] lemma sub_re : (a - b).re = a.re - b.re := rfl
@[simp] lemma sub_im_i : (a - b).im_i = a.im_i - b.im_i := rfl
@[simp] lemma sub_im_j : (a - b).im_j = a.im_j - b.im_j := rfl
@[simp] lemma sub_im_k : (a - b).im_k = a.im_k - b.im_k := rfl
@[simp, norm_cast] lemma coe_sub : ((x - y : R) : ℍ[R]) = x - y := quaternion_algebra.coe_sub x y
@[simp] lemma mul_re :
(a * b).re = a.re * b.re - a.im_i * b.im_i - a.im_j * b.im_j - a.im_k * b.im_k :=
(quaternion_algebra.has_mul_mul_re a b).trans $
by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg]
@[simp] lemma mul_im_i :
(a * b).im_i = a.re * b.im_i + a.im_i * b.re + a.im_j * b.im_k - a.im_k * b.im_j :=
(quaternion_algebra.has_mul_mul_im_i a b).trans $
by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg]
@[simp] lemma mul_im_j :
(a * b).im_j = a.re * b.im_j - a.im_i * b.im_k + a.im_j * b.re + a.im_k * b.im_i :=
(quaternion_algebra.has_mul_mul_im_j a b).trans $
by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg]
@[simp] lemma mul_im_k :
(a * b).im_k = a.re * b.im_k + a.im_i * b.im_j - a.im_j * b.im_i + a.im_k * b.re :=
(quaternion_algebra.has_mul_mul_im_k a b).trans $
by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg]
@[simp, norm_cast] lemma coe_mul : ((x * y : R) : ℍ[R]) = x * y := quaternion_algebra.coe_mul x y
lemma coe_injective : function.injective (coe : R → ℍ[R]) := quaternion_algebra.coe_injective
@[simp] lemma coe_inj {x y : R} : (x : ℍ[R]) = y ↔ x = y := coe_injective.eq_iff
@[simp] lemma smul_re : (r • a).re = r • a.re := rfl
@[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl
@[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl
@[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl
lemma coe_commutes : ↑r * a = a * r := quaternion_algebra.coe_commutes r a
lemma coe_commute : commute ↑r a := quaternion_algebra.coe_commute r a
lemma coe_mul_eq_smul : ↑r * a = r • a := quaternion_algebra.coe_mul_eq_smul r a
lemma mul_coe_eq_smul : a * r = r • a := quaternion_algebra.mul_coe_eq_smul r a
@[simp] lemma algebra_map_def : ⇑(algebra_map R ℍ[R]) = coe := rfl
lemma smul_coe : x • (y : ℍ[R]) = ↑(x * y) := quaternion_algebra.smul_coe x y
/-- Quaternion conjugate. -/
def conj : ℍ[R] ≃ₗ[R] ℍ[R] := quaternion_algebra.conj
@[simp] lemma conj_re : a.conj.re = a.re := rfl
@[simp] lemma conj_im_i : a.conj.im_i = - a.im_i := rfl
@[simp] lemma conj_im_j : a.conj.im_j = - a.im_j := rfl
@[simp] lemma conj_im_k : a.conj.im_k = - a.im_k := rfl
@[simp] lemma conj_conj : a.conj.conj = a := a.conj_conj
@[simp] lemma conj_add : (a + b).conj = a.conj + b.conj := a.conj_add b
@[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := a.conj_mul b
lemma conj_conj_mul : (a.conj * b).conj = b.conj * a := a.conj_conj_mul b
lemma conj_mul_conj : (a * b.conj).conj = b * a.conj := a.conj_mul_conj b
lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := a.self_add_conj'
lemma self_add_conj : a + a.conj = 2 * a.re := a.self_add_conj
lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := a.conj_add_self'
lemma conj_add_self : a.conj + a = 2 * a.re := a.conj_add_self
lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := a.conj_eq_two_re_sub
lemma commute_conj_self : commute a.conj a := a.commute_conj_self
lemma commute_self_conj : commute a a.conj := a.commute_self_conj
lemma commute_conj_conj {a b : ℍ[R]} (h : commute a b) : commute a.conj b.conj :=
quaternion_algebra.commute_conj_conj h
alias commute_conj_conj ← commute.quaternion_conj
@[simp] lemma conj_coe : conj (x : ℍ[R]) = x := quaternion_algebra.conj_coe x
@[simp] lemma conj_smul : conj (r • a) = r • conj a := a.conj_smul r
@[simp] lemma conj_one : conj (1 : ℍ[R]) = 1 := conj_coe 1
lemma eq_re_of_eq_coe {a : ℍ[R]} {x : R} (h : a = x) : a = a.re :=
quaternion_algebra.eq_re_of_eq_coe h
lemma eq_re_iff_mem_range_coe {a : ℍ[R]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R]) :=
quaternion_algebra.eq_re_iff_mem_range_coe
@[simp] lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R] {a : ℍ[R]} :
conj a = a ↔ a = a.re :=
quaternion_algebra.conj_fixed
lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := a.conj_mul_eq_coe
lemma mul_conj_eq_coe : a * conj a = (a * conj a).re := a.mul_conj_eq_coe
@[simp] lemma conj_zero : conj (0:ℍ[R]) = 0 := quaternion_algebra.conj_zero
@[simp] lemma conj_neg : (-a).conj = -a.conj := a.conj_neg
@[simp] lemma conj_sub : (a - b).conj = a.conj - b.conj := a.conj_sub b
open opposite
/-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/
def conj_alg_equiv : ℍ[R] ≃ₐ[R] (ℍ[R]ᵒᵖ) := quaternion_algebra.conj_alg_equiv
@[simp] lemma coe_conj_alg_equiv : ⇑(conj_alg_equiv : ℍ[R] ≃ₐ[R] ℍ[R]ᵒᵖ) = op ∘ conj := rfl
/-- Square of the norm. -/
def norm_sq : monoid_with_zero_hom ℍ[R] R :=
{ to_fun := λ a, (a * a.conj).re,
map_zero' := by rw [conj_zero, zero_mul, zero_re],
map_one' := by rw [conj_one, one_mul, one_re],
map_mul' := λ x y, coe_injective $ by conv_lhs { rw [← mul_conj_eq_coe, conj_mul, mul_assoc,
← mul_assoc y, y.mul_conj_eq_coe, coe_commutes, ← mul_assoc, x.mul_conj_eq_coe, ← coe_mul] } }
lemma norm_sq_def : norm_sq a = (a * a.conj).re := rfl
lemma norm_sq_def' : norm_sq a = a.1^2 + a.2^2 + a.3^2 + a.4^2 :=
by simp only [norm_sq_def, pow_two, ← neg_mul_eq_mul_neg, sub_neg_eq_add,
mul_re, conj_re, conj_im_i, conj_im_j, conj_im_k]
lemma norm_sq_coe : norm_sq (x : ℍ[R]) = x^2 :=
by rw [norm_sq_def, conj_coe, ← coe_mul, coe_re, pow_two]
@[simp] lemma norm_sq_neg : norm_sq (-a) = norm_sq a :=
by simp only [norm_sq_def, conj_neg, neg_mul_neg]
lemma self_mul_conj : a * a.conj = norm_sq a := by rw [mul_conj_eq_coe, norm_sq_def]
lemma conj_mul_self : a.conj * a = norm_sq a := by rw [← a.commute_self_conj.eq, self_mul_conj]
lemma coe_norm_sq_add :
(norm_sq (a + b) : ℍ[R]) = norm_sq a + a * b.conj + b * a.conj + norm_sq b :=
by simp [← self_mul_conj, mul_add, add_mul, add_assoc]
end quaternion
namespace quaternion
variables {R : Type*}
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring R] {a : ℍ[R]}
@[simp] lemma norm_sq_eq_zero : norm_sq a = 0 ↔ a = 0 :=
begin
refine ⟨λ h, _, λ h, h.symm ▸ norm_sq.map_zero⟩,
rw [norm_sq_def', add_eq_zero_iff_eq_zero_of_nonneg, add_eq_zero_iff_eq_zero_of_nonneg,
add_eq_zero_iff_eq_zero_of_nonneg] at h,
exact ext a 0 (pow_eq_zero h.1.1.1) (pow_eq_zero h.1.1.2) (pow_eq_zero h.1.2) (pow_eq_zero h.2),
all_goals { apply_rules [pow_two_nonneg, add_nonneg] }
end
lemma norm_sq_ne_zero : norm_sq a ≠ 0 ↔ a ≠ 0 := not_congr norm_sq_eq_zero
@[simp] lemma norm_sq_nonneg : 0 ≤ norm_sq a :=
by { rw norm_sq_def', apply_rules [pow_two_nonneg, add_nonneg] }
@[simp] lemma norm_sq_le_zero : norm_sq a ≤ 0 ↔ a = 0 :=
by simpa only [le_antisymm_iff, norm_sq_nonneg, and_true] using @norm_sq_eq_zero _ _ a
instance : domain ℍ[R] :=
{ exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩,
eq_zero_or_eq_zero_of_mul_eq_zero := λ a b hab,
have norm_sq a * norm_sq b = 0, by rwa [← norm_sq.map_mul, norm_sq_eq_zero],
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp norm_sq_eq_zero.1 norm_sq_eq_zero.1,
.. quaternion.ring }
end linear_ordered_comm_ring
section field
variables [linear_ordered_field R] (a b : ℍ[R])
@[simps { attrs := [] }]instance : has_inv ℍ[R] := ⟨λ a, (norm_sq a)⁻¹ • a.conj⟩
instance : division_ring ℍ[R] :=
{ inv := has_inv.inv,
inv_zero := by rw [has_inv_inv, conj_zero, smul_zero],
mul_inv_cancel := λ a ha, by rw [has_inv_inv, algebra.mul_smul_comm, self_mul_conj, smul_coe,
inv_mul_cancel (norm_sq_ne_zero.2 ha), coe_one],
.. quaternion.domain }
@[simp] lemma norm_sq_inv : norm_sq a⁻¹ = (norm_sq a)⁻¹ :=
monoid_with_zero_hom.map_inv' norm_sq _
@[simp] lemma norm_sq_div : norm_sq (a / b) = norm_sq a / norm_sq b :=
monoid_with_zero_hom.map_div norm_sq a b
end field
end quaternion
|
5fd9ce1030eaa7bdd7df5dd2b61b1b927d989610 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/function/floor.lean | 1f7c974ad0c6e8ebd3015311b9c0bad162c3d4e0 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,967 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import measure_theory.constructions.borel_space.basic
/-!
# Measurability of `⌊x⌋` etc
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove that `int.floor`, `int.ceil`, `int.fract`, `nat.floor`, and `nat.ceil` are
measurable under some assumptions on the (semi)ring.
-/
open set
section floor_ring
variables {α R : Type*} [measurable_space α] [linear_ordered_ring R] [floor_ring R]
[topological_space R] [order_topology R] [measurable_space R]
lemma int.measurable_floor [opens_measurable_space R] :
measurable (int.floor : R → ℤ) :=
measurable_to_countable $ λ x, by simpa only [int.preimage_floor_singleton]
using measurable_set_Ico
@[measurability] lemma measurable.floor [opens_measurable_space R]
{f : α → R} (hf : measurable f) : measurable (λ x, ⌊f x⌋) :=
int.measurable_floor.comp hf
lemma int.measurable_ceil [opens_measurable_space R] :
measurable (int.ceil : R → ℤ) :=
measurable_to_countable $ λ x,
by simpa only [int.preimage_ceil_singleton] using measurable_set_Ioc
@[measurability] lemma measurable.ceil [opens_measurable_space R]
{f : α → R} (hf : measurable f) : measurable (λ x, ⌈f x⌉) :=
int.measurable_ceil.comp hf
lemma measurable_fract [borel_space R] : measurable (int.fract : R → R) :=
begin
intros s hs,
rw int.preimage_fract,
exact measurable_set.Union (λ z, measurable_id.sub_const _ (hs.inter measurable_set_Ico))
end
@[measurability] lemma measurable.fract [borel_space R]
{f : α → R} (hf : measurable f) : measurable (λ x, int.fract (f x)) :=
measurable_fract.comp hf
lemma measurable_set.image_fract [borel_space R] {s : set R} (hs : measurable_set s) :
measurable_set (int.fract '' s) :=
begin
simp only [int.image_fract, sub_eq_add_neg, image_add_right'],
exact measurable_set.Union (λ m, (measurable_add_const _ hs).inter measurable_set_Ico)
end
end floor_ring
section floor_semiring
variables {α R : Type*} [measurable_space α] [linear_ordered_semiring R] [floor_semiring R]
[topological_space R] [order_topology R] [measurable_space R] [opens_measurable_space R]
{f : α → R}
lemma nat.measurable_floor : measurable (nat.floor : R → ℕ) :=
measurable_to_countable $ λ n, by cases eq_or_ne ⌊n⌋₊ 0; simp [*, nat.preimage_floor_of_ne_zero]
@[measurability] lemma measurable.nat_floor (hf : measurable f) : measurable (λ x, ⌊f x⌋₊) :=
nat.measurable_floor.comp hf
lemma nat.measurable_ceil : measurable (nat.ceil : R → ℕ) :=
measurable_to_countable $ λ n, by cases eq_or_ne ⌈n⌉₊ 0; simp [*, nat.preimage_ceil_of_ne_zero]
@[measurability] lemma measurable.nat_ceil (hf : measurable f) : measurable (λ x, ⌈f x⌉₊) :=
nat.measurable_ceil.comp hf
end floor_semiring
|
af7b5f9ef481c7df8ded542ab7b74b4683e58625 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/omega/coeffs.lean | 0042b173025618c928302cb6b1d1f6f15bb66ce0 | [
"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 | 10,614 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/
/-
Non-constant terms of linear constraints are represented
by storing their coefficients in integer lists.
-/
import data.list.func
import tactic.ring
import tactic.omega.misc
namespace omega
namespace coeffs
open list.func
variable {v : nat → int}
/-- `val_between v as l o` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping all
subterms that include variables outside the range `[l,l+o)` -/
@[simp] def val_between (v : nat → int) (as : list int) (l : nat) : nat → int
| 0 := 0
| (o+1) := (val_between o) + (get (l+o) as * v (l+o))
@[simp] lemma val_between_nil {l : nat} :
∀ m, val_between v [] l m = 0
| 0 := by simp only [val_between]
| (m+1) :=
by simp only [val_between_nil m, omega.coeffs.val_between,
get_nil, zero_add, zero_mul, int.default_eq_zero]
/-- Evaluation of the nonconstant component of a normalized linear arithmetic term. -/
def val (v : nat → int) (as : list int) : int :=
val_between v as 0 as.length
@[simp] lemma val_nil : val v [] = 0 := rfl
lemma val_between_eq_of_le {as : list int} {l : nat} :
∀ m, as.length ≤ l + m →
val_between v as l m = val_between v as l (as.length - l)
| 0 h1 :=
begin rw (nat.sub_eq_zero_iff_le.elim_right _), apply h1 end
| (m+1) h1 :=
begin
rw le_iff_eq_or_lt at h1, cases h1,
{ rw [h1, add_comm l, nat.add_sub_cancel] },
have h2 : list.length as ≤ l + m,
{ rw ← nat.lt_succ_iff, apply h1 },
simpa [ get_eq_default_of_le _ h2, zero_mul, add_zero,
val_between ] using val_between_eq_of_le _ h2
end
lemma val_eq_of_le {as : list int} {k : nat} :
as.length ≤ k → val v as = val_between v as 0 k :=
begin
intro h1, unfold val,
rw [val_between_eq_of_le k _], refl,
rw zero_add, exact h1
end
lemma val_between_eq_val_between
{v w : nat → int} {as bs : list int} {l : nat} :
∀ {m}, (∀ x, l ≤ x → x < l + m → v x = w x) →
(∀ x, l ≤ x → x < l + m → get x as = get x bs) →
val_between v as l m = val_between w bs l m
| 0 h1 h2 := rfl
| (m+1) h1 h2 :=
begin
unfold val_between,
have h3 : l + m < l + (m + 1),
{ rw ← add_assoc, apply lt_add_one },
apply fun_mono_2,
apply val_between_eq_val_between; intros x h4 h5,
{ apply h1 _ h4 (lt_trans h5 h3) },
{ apply h2 _ h4 (lt_trans h5 h3) },
rw [h1 _ _ h3, h2 _ _ h3];
apply nat.le_add_right
end
open_locale list.func
lemma val_between_set {a : int} {l n : nat} :
∀ {m}, l ≤ n → n < l + m → val_between v ([] {n ↦ a}) l m = a * v n
| 0 h1 h2 :=
begin exfalso, apply lt_irrefl l (lt_of_le_of_lt h1 h2) end
| (m+1) h1 h2 :=
begin
rw [← add_assoc, nat.lt_succ_iff, le_iff_eq_or_lt] at h2,
cases h2; unfold val_between,
{ have h3 : val_between v ([] {l + m ↦ a}) l m = 0,
{ apply @eq.trans _ _ (val_between v [] l m),
{ apply val_between_eq_val_between,
{ intros, refl },
{ intros x h4 h5, rw [get_nil,
get_set_eq_of_ne, get_nil],
apply ne_of_lt h5 } },
apply val_between_nil },
rw h2,
simp only [h3, zero_add, list.func.get_set] },
{ have h3 : l + m ≠ n,
{ apply ne_of_gt h2 },
rw [@val_between_set m h1 h2, get_set_eq_of_ne _ _ h3],
simp only [h3, get_nil, add_zero, zero_mul, int.default_eq_zero] }
end
@[simp] lemma val_set {m : nat} {a : int} :
val v ([] {m ↦ a}) = a * v m :=
begin
apply val_between_set, apply zero_le,
apply lt_of_lt_of_le (lt_add_one _),
simp only [length_set, zero_add, le_max_right],
apply_instance,
end
lemma val_between_neg {as : list int} {l : nat} :
∀ {o}, val_between v (neg as) l o = -(val_between v as l o)
| 0 := rfl
| (o+1) :=
begin
unfold val_between,
rw [neg_add, neg_mul_eq_neg_mul],
apply fun_mono_2,
apply val_between_neg,
apply fun_mono_2 _ rfl,
apply get_neg
end
@[simp] lemma val_neg {as : list int} :
val v (neg as) = -(val v as) :=
by simpa only [val, length_neg] using val_between_neg
lemma val_between_add {is js : list int} {l : nat} :
∀ m, val_between v (add is js) l m =
(val_between v is l m) + (val_between v js l m)
| 0 := rfl
| (m+1) :=
by { simp only [val_between, val_between_add m,
list.func.get, get_add], ring }
@[simp] lemma val_add {is js : list int} :
val v (add is js) = (val v is) + (val v js) :=
begin
unfold val,
rw val_between_add, apply fun_mono_2;
apply val_between_eq_of_le;
rw [zero_add, length_add],
apply le_max_left, apply le_max_right
end
lemma val_between_sub {is js : list int} {l : nat} :
∀ m, val_between v (sub is js) l m =
(val_between v is l m) - (val_between v js l m)
| 0 := rfl
| (m+1) :=
by { simp only [val_between, val_between_sub m,
list.func.get, get_sub], ring }
@[simp] lemma val_sub {is js : list int} :
val v (sub is js) = (val v is) - (val v js) :=
begin
unfold val,
rw val_between_sub,
apply fun_mono_2;
apply val_between_eq_of_le;
rw [zero_add, length_sub],
apply le_max_left,
apply le_max_right
end
/-- `val_except k v as` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping the
subterm that includes the `k`th variable. -/
def val_except (k : nat) (v : nat → int) (as) :=
val_between v as 0 k + val_between v as (k+1) (as.length - (k+1))
lemma val_except_eq_val_except
{k : nat} {is js : list int} {v w : nat → int} :
(∀ x ≠ k, v x = w x) → (∀ x ≠ k, get x is = get x js) →
val_except k v is = val_except k w js :=
begin
intros h1 h2, unfold val_except,
apply fun_mono_2,
{ apply val_between_eq_val_between;
intros x h3 h4;
[ {apply h1}, {apply h2} ];
apply ne_of_lt;
rw zero_add at h4;
apply h4 },
{ repeat { rw ← val_between_eq_of_le
((max is.length js.length) - (k+1)) },
{ apply val_between_eq_val_between;
intros x h3 h4;
[ {apply h1}, {apply h2} ];
apply ne.symm;
apply ne_of_lt;
rw nat.lt_iff_add_one_le;
exact h3 },
repeat { rw add_comm,
apply le_trans _ (nat.le_sub_add _ _),
{ apply le_max_right <|> apply le_max_left } } }
end
open_locale omega
lemma val_except_update_set
{n : nat} {as : list int} {i j : int} :
val_except n (v⟨n ↦ i⟩) (as {n ↦ j}) = val_except n v as :=
by apply val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _)
lemma val_between_add_val_between {as : list int} {l m : nat} :
∀ {n}, val_between v as l m + val_between v as (l+m) n =
val_between v as l (m+n)
| 0 := by simp only [val_between, add_zero]
| (n+1) :=
begin
rw ← add_assoc,
unfold val_between,
rw add_assoc,
rw ← @val_between_add_val_between n,
ring,
end
lemma val_except_add_eq (n : nat) {as : list int} :
(val_except n v as) + ((get n as) * (v n)) = val v as :=
begin
unfold val_except, unfold val,
by_cases h1 : n + 1 ≤ as.length,
{ have h4 := @val_between_add_val_between v as 0 (n+1) (as.length - (n+1)),
have h5 : n + 1 + (as.length - (n + 1)) = as.length,
{ rw [add_comm, nat.sub_add_cancel h1] },
rw h5 at h4, apply eq.trans _ h4,
simp only [val_between, zero_add], ring },
have h2 : (list.length as - (n + 1)) = 0,
{ apply nat.sub_eq_zero_of_le
(le_trans (not_lt.1 h1) (nat.le_add_right _ _)) },
have h3 : val_between v as 0 (list.length as) =
val_between v as 0 (n + 1),
{ simpa only [val] using @val_eq_of_le v as (n+1)
(le_trans (not_lt.1 h1) (nat.le_add_right _ _)) },
simp only [add_zero, val_between, zero_add, h2, h3]
end
@[simp] lemma val_between_map_mul {i : int} {as: list int} {l : nat} :
∀ {m}, val_between v (list.map ((*) i) as) l m = i * val_between v as l m
| 0 := by simp only [val_between, mul_zero, list.map]
| (m+1) :=
begin
unfold val_between,
rw [@val_between_map_mul m, mul_add],
apply fun_mono_2 rfl,
by_cases h1 : l + m < as.length,
{ rw [get_map h1, mul_assoc] },
rw not_lt at h1,
rw [get_eq_default_of_le, get_eq_default_of_le];
try {simp}; apply h1
end
lemma forall_val_dvd_of_forall_mem_dvd {i : int} {as : list int} :
(∀ x ∈ as, i ∣ x) → (∀ n, i ∣ get n as) | h1 n :=
by { apply forall_val_of_forall_mem _ h1,
apply dvd_zero }
lemma dvd_val_between {i} {as: list int} {l : nat} :
∀ {m}, (∀ x ∈ as, i ∣ x) → (i ∣ val_between v as l m)
| 0 h1 := dvd_zero _
| (m+1) h1 :=
begin
unfold val_between,
apply dvd_add,
apply dvd_val_between h1,
apply dvd_mul_of_dvd_left,
by_cases h2 : get (l+m) as = 0,
{ rw h2, apply dvd_zero },
apply h1, apply mem_get_of_ne_zero h2
end
lemma dvd_val {as : list int} {i : int} :
(∀ x ∈ as, i ∣ x) → (i ∣ val v as) := by apply dvd_val_between
@[simp] lemma val_between_map_div
{as: list int} {i : int} {l : nat} (h1 : ∀ x ∈ as, i ∣ x) :
∀ {m}, val_between v (list.map (λ x, x / i) as) l m = (val_between v as l m) / i
| 0 := by simp only [int.zero_div, val_between, list.map]
| (m+1) :=
begin
unfold val_between,
rw [@val_between_map_div m, int.add_div_of_dvd_right],
apply fun_mono_2 rfl,
{ apply calc get (l + m) (list.map (λ (x : ℤ), x / i) as) * v (l + m)
= ((get (l + m) as) / i) * v (l + m) :
begin
apply fun_mono_2 _ rfl,
rw get_map',
apply int.zero_div
end
... = get (l + m) as * v (l + m) / i :
begin
repeat {rw mul_comm _ (v (l+m))},
rw int.mul_div_assoc,
apply forall_val_dvd_of_forall_mem_dvd h1
end },
apply dvd_mul_of_dvd_left,
apply forall_val_dvd_of_forall_mem_dvd h1,
end
@[simp] lemma val_map_div {as : list int} {i : int} :
(∀ x ∈ as, i ∣ x) → val v (list.map (λ x, x / i) as) = (val v as) / i :=
by {intro h1, simpa only [val, list.length_map] using val_between_map_div h1}
lemma val_between_eq_zero {is: list int} {l : nat} :
∀ {m}, (∀ x : int, x ∈ is → x = 0) → val_between v is l m = 0
| 0 h1 := rfl
| (m+1) h1 :=
begin
have h2 := @forall_val_of_forall_mem _ _ is (λ x, x = 0) rfl h1,
simpa only [val_between, h2 (l+m), zero_mul, add_zero]
using @val_between_eq_zero m h1,
end
lemma val_eq_zero {is : list int} :
(∀ x : int, x ∈ is → x = 0) → val v is = 0 :=
by apply val_between_eq_zero
end coeffs
end omega
|
a5ccaecca026425e425906ad9b354c1c3855de05 | 5bcdf53ae59d93bf05c4a6b7780107f9bba8a987 | /3_InductiveTypes.lean | e7c8b4efb2f68fa902125b01b649be6c915a83e5 | [] | no_license | joshpoll/CPDT-examples-in-Lean | 3241734e80c8507934a9fbf2ddfed9eedc1ed27b | 287aebec9a4a9dc4a07b8e4cc885c81afe400f1a | refs/heads/master | 1,611,267,038,438 | 1,498,610,301,000 | 1,498,610,301,000 | 95,181,904 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,166 | lean | import mini_crush
namespace hide
-- *Introducing Inductive Types
-- **Proof Terms
#check (fun x : ℕ, x)
#check (fun x : true, x)
#check true.intro
#check (λ _ : false, true.intro)
#check (λ x : false, x)
-- **Enumerations
-- unit
inductive unit : Type
| tt
#check unit
#check unit.tt
theorem unit_singleton_verbose (x : unit) : x = unit.tt :=
by induction x; refl
theorem unit_singleton_concise : ∀ x : unit, x = unit.tt
| unit.tt := rfl
-- TODO: is cases_on like unit_ind?
-- TODO: hovering over #check gives a different type than hovering over the expression itself (which yields the "correct" answer)
#check unit.cases_on
-- empty
inductive empty : Type
-- TODO: cases vs induction?
theorem the_sky_is_falling (x : empty) : 2 + 2 = 5 :=
by cases x
#check empty.cases_on
-- empty to unit
def e2u (e : empty) : unit := match e with end
-- booleans
inductive bool : Type
| true
| false
-- bool negation
def negb : bool → bool
| bool.true := bool.false
| bool.false := bool.true
-- TODO: negb' ? is there a version of ite that works for any type w/ 2 constructors?
-- proof that negb is its own inverse operation
theorem negb_inverse : ∀ b : bool, negb (negb b) = b
| bool.true := rfl
| bool.false := rfl
-- proof that negb has no fixpoint
theorem negb_ineq (b : bool) : negb b ≠ b :=
by cases b; contradiction
-- **Simple Recursive Types
-- nat and some functions
inductive nat : Type
| O : nat
| S : nat → nat
def is_zero : nat → bool
| nat.O := bool.true
| (nat.S _) := bool.false
def pred : nat → nat
| nat.O := nat.O
| (nat.S n) := n
def plus : nat → nat → nat
| nat.O m := m
| (nat.S n) m := nat.S (plus n m)
theorem O_plus_n : ∀ n : nat, plus nat.O n = n :=
begin
simp [plus]
end
theorem O_plus_n_crush : ∀ n : nat, plus nat.O n = n :=
by mini_crush
theorem n_plus_O : ∀ n : nat, plus n nat.O = n :=
begin
intro n,
induction n,
{refl},
simp [plus],
rw ih_1
end
theorem n_plus_O_crush : ∀ n : nat, plus n nat.O = n :=
by mini_crush
theorem s_inj : ∀ n m : nat, nat.S n = nat.S m → n = m :=
begin
intros n m succ_eq,
injection succ_eq
end
theorem s_inj_crush : ∀ n m : nat, nat.S n = nat.S m → n = m :=
by mini_crush
inductive nat_list : Type
| NNil : nat_list
| NCons : nat → nat_list → nat_list
-- length
def nlength : nat_list → nat
| nat_list.NNil := nat.O
| (nat_list.NCons _ ls) := nat.S (nlength ls)
-- apppend
def napp : nat_list → nat_list → nat_list
| nat_list.NNil ls2 := ls2
| (nat_list.NCons n ls1) ls2 := nat_list.NCons n (napp ls1 ls2)
-- the length of an appended list made from ls1 and ls2 is the sum of the lengths of ls1 and ls2
theorem nlength_napp : ∀ ls1 ls2 : nat_list, nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2) :=
begin
intros,
induction ls1; simp [nlength, plus, napp],
rw ih_1
end
theorem nlength_napp_crush : ∀ ls1 ls2 : nat_list, nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2) :=
by mini_crush
-- binary tree
inductive nat_btree : Type
| NLeaf : nat_btree
| NNode : nat_btree → nat → nat_btree → nat_btree
def nsize : nat_btree → nat
| nat_btree.NLeaf := nat.S nat.O
| (nat_btree.NNode tr1 _ tr2) := plus (nsize tr1) (nsize tr2)
def nsplice : nat_btree → nat_btree → nat_btree
| nat_btree.NLeaf tr2 := nat_btree.NNode tr2 nat.O nat_btree.NLeaf
| (nat_btree.NNode tr1' n tr2') tr2 := nat_btree.NNode (nsplice tr1' tr2) n tr2'
theorem plus_assoc : ∀ n1 n2 n3 : nat, plus (plus n1 n2) n3 = plus n1 (plus n2 n3) :=
begin
intros,
induction n1; simp [plus],
rw ih_1
end
theorem nsize_nsplice : ∀ tr1 tr2 : nat_btree, nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1) :=
begin
intros,
induction tr1; simp [nsize, nsplice],
simp [ih_1, ih_2, plus_assoc]
end
#check nat_btree.cases_on
-- **Parameterized Types
-- TODO: is there a way to remove type annotations nearly everywhere ala CPDT p. 50?
universe variable u
inductive list (α : Type u) : Type u
| Nil {} : list
| Cons : α → list → list
def length {α : Type u} : list α → nat
| list.Nil := nat.O
| (list.Cons _ l) := nat.S (length l)
def app {α : Type u} : list α → list α → list α
| list.Nil ls2 := ls2
| (list.Cons x ls1) ls2 := list.Cons x (app ls1 ls2)
-- nearly identical to nlength_napp
theorem length_app : Π (α : Type u), ∀ ls1 ls2 :
list α, length (app ls1 ls2) = plus (length ls1) (length ls2) :=
begin
intros,
induction ls1; simp [length, plus, app],
rw ih_1
end
theorem length_app_crush : Π (α : Type u), ∀ ls1 ls2 :
list α, length (app ls1 ls2) = plus (length ls1) (length ls2) :=
by mini_crush
-- **Mutually Inductive Types
-- even and odd lists
mutual inductive even_list, odd_list
with even_list : Type
| ENil : even_list
| ECons : nat → odd_list → even_list
with odd_list : Type
| OCons : nat → even_list → odd_list
mutual def elength, olength
with elength : even_list → nat
| even_list.ENil := nat.O
| (even_list.ECons _ ol) := nat.S (olength ol)
with olength : odd_list → nat
| (odd_list.OCons _ el) := nat.S (elength el)
mutual def eapp, oapp
with eapp : even_list → even_list → even_list
| even_list.ENil el2 := el2
| (even_list.ECons n ol) el2 := even_list.ECons n (oapp ol el2)
with oapp : odd_list → even_list → odd_list
| (odd_list.OCons n el') el := odd_list.OCons n (eapp el' el)
-- TODO: come back to this one
theorem elength_eapp : ∀ el1 el2 : even_list,
elength (eapp el1 el2) = plus (elength el1) (elength el2) :=
begin
intros,
induction el1; simp [elength, eapp, plus],
admit
end
-- **Reflexive Types
-- a reflexive type A includes at least one constructor that takes an argument of type B → A
-- subset of predicate logic
inductive pformula : Type
| Truth : pformula
| Falsehood : pformula
| Conjunction : pformula → pformula → pformula
-- pformula denotational semantics
def pformulaDenote : pformula → Prop
| pformula.Truth := true
| pformula.Falsehood := false
| (pformula.Conjunction f1 f2) := pformulaDenote f1 ∧ pformulaDenote f2
inductive formula : Type
| Eq : nat → nat → formula
| And : formula → formula → formula
| Forall : (nat → formula) → formula
-- variables implicitly defined using lean functions
-- e.g. ∀ x : nat, x = x is encoded as
example forall_refl : formula := formula.Forall (fun x, formula.Eq x x)
-- formula denotational semantics
def formulaDenote : formula → Prop
| (formula.Eq n1 n2) := n1 = n2
| (formula.And f1 f2) := formulaDenote f1 ∧ formulaDenote f2
| (formula.Forall f) := ∀ n : nat, formulaDenote (f n)
-- a trivial formula transformation
def swapper : formula → formula
| (formula.Eq n1 n2) := formula.Eq n2 n1
| (formula.And f1 f2) := formula.And (swapper f2) (swapper f1)
| (formula.Forall f) := formula.Forall (fun n, swapper (f n))
theorem swapper_preserves_truth (f : formula) : formulaDenote f → formulaDenote (swapper f) :=
by mini_crush
#check formula.cases_on
/-
inductive term : Type
| App : term → term → term
| Abs : (term → term) → term
open term
def uhoh (t : term) : term
| (Abs f) := f t
| _ := t
-/
-- **An Interlude on Induction Principles
-- TODO: equiv to nat_ind? nat_rect? nat_rec?
#check @nat.rec
#check @nat.cases_on
-- skipping the rest of this section for now
-- **Nested Inductive Types
-- tree with arbitrary finite branching
inductive nat_tree : Type
| NNode' : nat → list nat_tree → nat_tree
#check nat_tree.rec
section All
variable T : Type
variable P : T → Prop
def All : list T → Prop
| list.Nil := true
| (list.Cons h t) := P h ∧ All t
end All
#print true
#print ∧
#print and
section nat_tree_ind'
variable P : nat_tree → Prop
-- TODO
end nat_tree_ind'
-- TODO: rest of 3.8
-- **Manual Proofs About Constructors
-- todo
theorem true_neq_false : tt ≠ ff :=
begin
change ¬(tt = ff), -- TODO: replace this with something else?
change (tt = ff) → false,
intro H,
admit -- TODO: need a version of ite that takes any type w/ 2 constructors
end
theorem S_inj' : ∀ n m : nat, nat.S n = nat.S m → n = m :=
begin
intros n m H,
change (pred (nat.S n) = pred (nat.S m)),
rw H
end
end hide |
5a40eb494c1218809b758fee5419ca78e51bef59 | b82c5bb4c3b618c23ba67764bc3e93f4999a1a39 | /src/formal_ml/classical_limit.lean | 7a0e6e72157f6a24703a214503d10035ebdbf455 | [
"Apache-2.0"
] | permissive | nouretienne/formal-ml | 83c4261016955bf9bcb55bd32b4f2621b44163e0 | 40b6da3b6e875f47412d50c7cd97936cb5091a2b | refs/heads/master | 1,671,216,448,724 | 1,600,472,285,000 | 1,600,472,285,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,280 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import order.filter.basic
import data.real.basic
import topology.basic
import topology.instances.real
import data.complex.exponential
import topology.algebra.infinite_sum
import data.nat.basic
import analysis.specific_limits
import analysis.calculus.deriv
import analysis.asymptotics
import formal_ml.sum
import formal_ml.real
import formal_ml.classical_deriv
import formal_ml.filter_util
---Results about limits--------------------------------------------------------------------------
-- cf decidable_linear_ordered_add_comm_group.tendsto_nhds
-- This seems to cover the connection to a classical limit.
def has_classical_limit (f:ℕ → ℝ) (x:ℝ):Prop := ∀ ε:ℝ,
0 < ε → ∃ n, ∀ n', n<n' → abs (f n' - x) < ε
def exists_classical_limit (f:ℕ → ℝ):Prop := ∃ x:ℝ,
has_classical_limit f x
lemma has_classical_limit_def (f:ℕ → ℝ) (x:ℝ):
has_classical_limit f x ↔ filter.tendsto f filter.at_top (@nhds ℝ _ x) :=
begin
split;intro A1,
{
apply filter_tendsto_intro,
intros b A2,
unfold set.preimage,
unfold has_classical_limit at A1,
have A3:(∃ r>0, (set.Ioo (x-r) (x+r)) ⊆ b) := mem_nhds_elim_real_bound _ _ A2,
cases A3 with r A4,
cases A4 with A5 A6,
have A7 := A1 r A5,
cases A7 with n A8,
apply @mem_filter_at_top_intro ℕ _ {x : ℕ | f x ∈ b} (nat.succ n),
rw set.subset_def,
intros n' A9,
simp at A9,
have A10:=nat.lt_of_succ_le A9,
have A11 := A8 n' A10,
rw set.subset_def at A6,
apply A6,
rw ← abs_lt_iff_in_Ioo,
apply A11,
},
{
unfold has_classical_limit,
intros ε A2,
have A3:set.Ioo (x -ε) (x + ε) ∈ nhds x := Ioo_nbhd A2,
have A4:=filter_tendsto_elim A1 A3,
unfold filter.tendsto at A1,
have A5 := filter_le_elim A1 A3,
have A6 := mem_filter_at_top_elim A5,
cases A6 with n A7,
rw set.subset_def at A7,
apply exists.intro n,
intros n' A8,
have A9 := A7 n',
--simp at A9,
rw abs_lt_iff_in_Ioo,
apply A9,
apply le_of_lt,
apply A8,
}
end
section functional_def
local attribute [instance] classical.prop_decidable
noncomputable def classical_limit (f:ℕ → ℝ):ℝ :=
if h:exists_classical_limit f then classical.some h else 0
end functional_def
lemma has_classical_limit_neg {f:ℕ → ℝ} {x:ℝ}:
has_classical_limit f x →
has_classical_limit (-f) (-x) :=
begin
unfold has_classical_limit,
intros A1 ε A2,
have A3 := A1 ε A2,
cases A3 with n A4,
apply exists.intro n,
intros n',
intro A5,
have A6 := A4 n' A5,
simp,
rw abs_antisymm,
apply A6,
end
lemma has_classical_limit_subst (f g:ℕ → ℝ) (x:ℝ):
(f = g) →
has_classical_limit f x = has_classical_limit g x :=
begin
intro A1,
rw A1,
end
lemma has_classical_limit_const {k:ℝ}:has_classical_limit (λ x:ℕ, k) k :=
begin
intros ε A1,
apply exists.intro 0,
intros n' A2,
simp,
exact A1,
end
lemma has_classical_limit_sum {f g:ℕ → ℝ} {x y:ℝ}:
has_classical_limit f x →
has_classical_limit g y →
has_classical_limit (f + g) (x + y) :=
begin
unfold has_classical_limit,
intros A1 B1 ε C1,
have C2:0 < (ε/2) := zero_lt_epsilon_half_of_zero_lt_epsilon C1,
have A2 := A1 (ε/2) C2,
have B2 := B1 (ε/2) C2,
cases A2 with nA A3,
cases B2 with nB B3,
let n := max nA nB,
begin
apply exists.intro n,
intros n' C3,
have A4:nA < n',
{
apply lt_of_le_of_lt,
apply le_max_left nA nB,
apply C3,
},
have B4:nB < n',
{
apply lt_of_le_of_lt,
apply le_max_right nA nB,
apply C3,
},
have A5 := A3 n' A4,
have B5 := B3 n' B4,
have C6:abs ((f + g) n' - (x + y)) ≤ abs (f n' - x) + abs (g n' - y),
{
have C6A:((f + g) n' - (x + y))=((f n' - x) + (g n' - y)),
{
simp,
rw ← sub_sub,
rw sub_eq_add_neg,
rw sub_eq_add_neg,
rw sub_eq_add_neg,
rw add_assoc _ (g n'),
rw add_comm (g n'),
rw ← add_assoc,
rw sub_eq_add_neg,
rw ← add_assoc,
},
rw C6A,
apply abs_add,
},
apply lt_of_le_of_lt,
apply C6,
have C7: ε = (ε /2 + ε /2),
{
simp,
},
rw C7,
apply add_lt_add A5 B5,
end
end
lemma has_classical_limit_sub {f g:ℕ → ℝ} {x y:ℝ}:
has_classical_limit f x →
has_classical_limit g y →
has_classical_limit (f - g) (x - y) :=
begin
intros A1 A2,
rw sub_eq_add_neg,
rw sub_eq_add_neg,
apply has_classical_limit_sum A1,
apply has_classical_limit_neg A2,
end
lemma has_classical_limit_unique {f:ℕ → ℝ} {x y:ℝ}:
has_classical_limit f x →
has_classical_limit f y →
(x = y) :=
begin
rw has_classical_limit_def,
rw has_classical_limit_def,
apply tendsto_nhds_unique,
end
lemma has_classical_limit_classical_limit {f:ℕ → ℝ}:
exists_classical_limit f →
has_classical_limit f (classical_limit f) :=
begin
unfold exists_classical_limit,
intro A1,
unfold classical_limit,
rw dif_pos,
apply classical.some_spec A1,
end
lemma exists_classical_limit_intro {f:ℕ → ℝ} {x:ℝ}:
has_classical_limit f x →
exists_classical_limit f :=
begin
intro A1,
unfold exists_classical_limit,
apply exists.intro x,
apply A1,
end
lemma eq_classical_limit {f:ℕ → ℝ} {x:ℝ}:
has_classical_limit f x →
x = classical_limit f :=
begin
intro A1,
have A2:exists_classical_limit f :=exists_classical_limit_intro A1,
have A3:has_classical_limit f (classical_limit f) := has_classical_limit_classical_limit A2,
apply has_classical_limit_unique A1 A3,
end
/-
This is trivial, because the reals are a topological monoid.
The classical way would be to break it apart into two pieces.
abs (f' * g' - f * g)< ε,
abs (f' * g' - f' * g + f' * g - f * g) < ε
abs (f' * (g' - g) + (f' - f) * g) < ε
abs (f' * (g' - g) + (f' - f) * g) < ε
abs (f' * (g' - g)) + abs((f' - f) * g) < ε
abs (f' * (g' - g)) < ε/2 ∧ abs((f' - f) * g) < ε/2
-/
lemma has_classical_limit_mul {f g:ℕ → ℝ} (x y:ℝ):
has_classical_limit f x →
has_classical_limit g y →
has_classical_limit (f * g) (x * y) :=
begin
rw has_classical_limit_def,
rw has_classical_limit_def,
rw has_classical_limit_def,
apply filter.tendsto.mul,
end
lemma has_classical_limit_mul_const {f:ℕ → ℝ} {k x:ℝ}:
has_classical_limit f x →
has_classical_limit (λ n, k * (f n)) (k * x) :=
begin
intro A1,
have A2:(λ n:ℕ, k * (f n)) = (λ n:ℕ, k) * f,
{
ext n,
simp,
},
rw A2,
apply has_classical_limit_mul,
{
apply has_classical_limit_const,
},
{
apply A1,
}
end
lemma has_classical_limit_mul_const_zero {f:ℕ → ℝ} {k:ℝ}:
has_classical_limit f 0 →
has_classical_limit (λ n, k * (f n)) 0 :=
begin
intro A1,
have A2:has_classical_limit (λ n, k * (f n)) (k * 0),
{
apply has_classical_limit_mul_const A1,
},
rw mul_zero at A2,
apply A2,
end
lemma has_classical_limit_exp (x:ℝ):
(0 ≤ x) →
(x < 1) →
has_classical_limit (λ n, x^n) 0 :=
begin
intros A1 A2,
rw has_classical_limit_def,
apply tendsto_pow_at_top_nhds_0_of_lt_1,
apply A1,
apply A2,
end
lemma has_classical_limit_inv_zero:
has_classical_limit (λ n:ℕ, (n:ℝ)⁻¹) 0 :=
begin
unfold has_classical_limit,
intros ε A1,
apply exists.intro (nat_ceil (ε⁻¹)),
intros n' A2,
simp,
-- ⊢ abs ((n':ℝ)⁻¹) < ε
have A4:0 ≤ (n':ℝ)⁻¹,
{
apply inv_nonneg_of_nonneg,
simp,
},
have A5:(ε⁻¹)⁻¹ = ε,
{
simp,
},
rw abs_of_nonneg A4,
rw ← A5,
apply inv_decreasing,
{
apply inv_pos_of_pos,
apply A1,
},
apply lt_of_le_of_lt,
apply le_nat_ceil,
apply real_lt_coe,
apply A2,
end
lemma has_classical_limit_eq_after {f g:ℕ → ℝ} {x:ℝ} {n:ℕ}:
has_classical_limit f x →
(∀ n':ℕ, n < n' → (f n' = g n')) →
has_classical_limit g x :=
begin
unfold has_classical_limit,
intros A1 A2 ε A3,
have A4 := A1 ε A3,
cases A4 with n' A5,
apply exists.intro (max n' n),
intros n'' A6,
have A7 := A2 n'' (lt_of_le_of_lt (le_max_right n' n) A6),
have A8 := A5 n'' (lt_of_le_of_lt (le_max_left n' n) A6),
rw ← A7,
apply A8,
end
lemma has_classical_limit_ratio_one:
has_classical_limit (λ n:ℕ, ((n + 1):ℝ) * (n:ℝ)⁻¹) 1 :=
begin
have A2:has_classical_limit (λ n:ℕ, (1:ℝ) + (n:ℝ)⁻¹) 1,
{
have A2A:(λ n:ℕ, (1:ℝ) + (n:ℝ)⁻¹)=(λ n:ℕ, (1:ℝ)) + (λ n:ℕ, (n:ℝ)⁻¹),
{
ext n,
simp,
},
rw A2A,
have A2B:(1:ℝ) = (1:ℝ) + (0:ℝ),
{
simp,
},
rw A2B,
apply has_classical_limit_sum,
{
simp,
apply has_classical_limit_const,
},
{
apply has_classical_limit_inv_zero,
}
},
apply has_classical_limit_eq_after A2,
{
intros n A1A,
simp,
rw right_distrib,
simp,
rw mul_inv_cancel,
intro A1B,
simp at A1B,
rw A1B at A1A,
apply lt_irrefl 0 A1A,
},
end
lemma has_classical_limit_abs_zero {f:ℕ → ℝ}:
has_classical_limit (abs ∘ f) 0 ↔
has_classical_limit f 0 :=
begin
unfold has_classical_limit,split;
intros A1 ε A2;
have A3:= A1 ε A2;
cases A3 with n A4;
apply exists.intro n;
intros n' A5;
have A6:= A4 n' A5;
simp at A6,
{
rw abs_abs at A6,
simp,
apply A6,
},
{
simp,
rw abs_abs,
apply A6,
}
end
lemma has_classical_limit_half_abs_zero {f g:ℕ → ℝ}:
has_classical_limit (f * g) 0 ↔
has_classical_limit (f * (abs ∘ g)) 0 :=
begin
have A1:∀ n',abs ((f * g) n' - 0)=abs ((f * abs ∘ g) n' - 0),
{
intro n',
simp,
rw abs_mul,
rw abs_mul,
rw abs_abs,
},
unfold has_classical_limit,
split;intros A2 ε A3;have A4:=A2 ε A3;cases A4 with n A5;apply exists.intro n;intros n' A6;
have A7:=A5 n' A6,
{
rw ← A1,
apply A7,
},
{
rw A1,
apply A7,
}
end
lemma has_classical_limit_bound {f:ℕ → ℝ} (g:ℕ → ℝ):
has_classical_limit g 0 →
(∃ (n:ℕ), ∀ (n':ℕ), n < n' → abs (f n') ≤ g n') →
has_classical_limit f 0 :=
begin
intros A1 A2,
unfold has_classical_limit,
cases A2 with n₁ A3,
intros ε A4,
unfold has_classical_limit at A1,
have A5 := A1 ε A4,
cases A5 with n₂ A6,
apply exists.intro (max n₁ n₂),
intros n' A7,
have A8 := A3 n' (lt_of_le_of_lt (le_max_left n₁ n₂) A7),
have A9 := A6 n' (lt_of_le_of_lt (le_max_right n₁ n₂) A7),
rw sub_zero,
rw sub_zero at A9,
have A10:g n' < ε,
{
rw abs_of_nonneg at A9,
{
apply A9,
},
{
apply le_trans,
apply abs_nonneg (f n'),
apply A8,
}
},
apply lt_of_le_of_lt,
apply A8,
apply A10,
end
/-
r < (1 + r)/2
-/
lemma bound_ratio_inductive {a b c d:ℝ}:
0 < a → 0 < c → a ≤ b→ c * a⁻¹ ≤ d → c ≤ d * b :=
begin
intros A1' A2' A3 A4,
have A1 := (le_of_lt A1'),
have A2 := (le_of_lt A2'),
have A5:0 ≤ c * a⁻¹ :=mul_nonneg A2 (inv_nonneg_of_nonneg (A1)),
have A6:(c * a⁻¹) * a ≤ d * b := mul_le_mul A4 A3 (A1) (le_trans A5 A4),
rw mul_assoc at A6,
rw inv_mul_cancel at A6,
rw mul_one at A6,
apply A6,
intro A7,
rw A7 at A1',
apply lt_irrefl (0:ℝ) A1',
end
lemma has_classical_limit_ratio_lt_oneh2 {f:ℕ→ ℝ} {k:ℝ} {r:ℝ} {n:ℕ}:
(0≤ k) →
(r < 1) →
(∀ n, 0 < f n) →
(f n = k * r^n) →
(∀ n',n ≤ n' → f (nat.succ n') * (f n')⁻¹ ≤ r) →
(∀ n',n ≤ n' → f n' ≤ k * r^n') :=
begin
intros A1 A3 A4 A5 A6,
intro n',
induction n',
{
intros B1,
simp at B1,
rw B1 at A5,
rw A5,
},
{
intro C1,
rw le_iff_lt_or_eq at C1,
cases C1,
{
have C2:n ≤ n'_n := nat.lt_succ_iff.mp C1,
have C3:=n'_ih C2,
have C4:=A6 n'_n C2,
have C5:k * r ^ nat.succ n'_n=r * (k * r^n'_n),
{
rw nat_succ_pow,
rw ← mul_assoc,
rw mul_comm k r,
rw mul_assoc,
},
rw C5,
apply bound_ratio_inductive,
{
apply A4 n'_n,
},
{
apply A4 (nat.succ n'_n),
},
{
apply C3,
},
{
apply C4,
},
},
{
rw ← C1,
rw ← A5,
}
}
end
/-
If the ratio of one value to the next approaches a value between 0 and 1 exclusive, then
there is an n where the ratio is always in (0,r'), where r' < 1.
This implies that abs (f n') < k (r')^n', and we can prove that k (r')^n' → 0.
There is a section in specific_limits.lean, edist_le_geometric, that has a similar
flavor.
NOTE: after writing this, I reviewed later unproven lemmas, and there would be a significant
advantage to have the constraints be:
(r < 1)
has_classical_limit (λ n:ℕ, (abs ∘ f (nat.succ n)) * (abs (f n)⁻¹) r →
which is basically what I am using anyway. Specifically, this resolves the limit
for x^n/n!, i.e. the terms in the exponential series.
-/
lemma has_classical_limit_ratio_lt_one2 {f:ℕ → ℝ} {r:ℝ}:
has_classical_limit (λ n:ℕ, (f (nat.succ n)) * (f n)⁻¹) r →
(r < 1) →
(0 ≤ r) →
(∀ n, 0 < f n) →
has_classical_limit f 0 :=
begin
intros A1 A2 A3 D1,
let r' := (1+r)/2,
begin
have A4:r' = (1+r)/2 := rfl,
have C4:r' = (r + 1)/2,
{
rw add_comm,
},
have C5:r < r',
{
rw C4,
apply half_bound_lower,
apply A2,
},
unfold has_classical_limit at A1,
have A5 : 0 < (r' - r),
{
apply sub_pos_of_lt,
apply C5,
},
have C1:0 < r',
{
apply lt_of_le_of_lt A3 C5,
},
have C2:r' ≠ 0,
{
intro C2A,
rw C2A at C1,
apply lt_irrefl 0 C1,
},
have C3:r' < 1,
{
rw C4,
apply half_bound_upper,
apply A2,
},
have A6 := A1 (r' - r) A5,
cases A6 with n A7,
let ns := (nat.succ n);
let k := (abs (f ns))*(((r')⁻¹)^(ns));
let g:ℕ → ℝ := λ n:ℕ, k * ((r')^n),
begin
have B1:ns = (nat.succ n) := rfl,
have B2:k = (abs (f ns))*(((r')⁻¹)^(ns)) := rfl,
have B3:g = λ n:ℕ, k * ((r')^n) := rfl,
have B4:has_classical_limit g 0,
{
have B4A:k * 0 = 0 := mul_zero k,
rw ← B4A,
rw B3,
apply has_classical_limit_mul_const,
apply has_classical_limit_exp,
apply le_of_lt,
apply C1,
apply C3,
},
apply has_classical_limit_bound g B4,
have B5:∀ n',ns ≤ n' → (abs ∘ f) n' ≤ k * (r')^n',
{
apply has_classical_limit_ratio_lt_oneh2,
{
rw B2,
apply mul_nonneg,
{
apply abs_nonneg,
},
{
apply le_of_lt,
apply pow_pos,
apply inv_pos_of_pos,
apply C1,
}
},
{
apply C3,
},
{
intro n',
simp,
apply abs_pos_of_pos,
apply D1,
},
{
rw B2,
rw mul_assoc,
rw inv_pow_cancel2,
rw mul_one,
apply C2,
},
{
intros n' B5A,
have B5B:abs (f (nat.succ n') * (f n')⁻¹ - r) < (r' - r),
{
apply A7,
rw B1 at B5A,
apply B5A,
},
have B5C:f (nat.succ n') * (f n')⁻¹ < r',
{
have B5CB:f (nat.succ n') * (f n')⁻¹ - r < (r' - r),
{
apply lt_of_le_of_lt,
apply le_abs_self,
apply B5B,
},
apply lt_of_sub_lt_sub B5CB,
},
have B5D:0 < (f (nat.succ n') * (f n')⁻¹),
{
apply mul_pos,
apply D1,
apply inv_pos_of_pos,
apply D1,
},
have B5E:abs (f (nat.succ n') * (f n')⁻¹) = (abs (f (nat.succ n'))) * (abs (f n'))⁻¹,
{
rw ← abs_inv,
rw abs_mul,
},
simp,
rw ← B5E,
rw abs_of_pos,
apply le_of_lt,
apply B5C,
apply B5D,
}
},
apply exists.intro ns,
intros n' B6,
apply B5,
apply le_of_lt,
apply B6
end
end
end
/-
lemma has_classical_limit_eq_after {f g:ℕ → ℝ} {x:ℝ} {n:ℕ}:
has_classical_limit f x →
(∀ n':ℕ, n < n' → (f n' = g n')) →
has_classical_limit g x :=
begin
-/
lemma has_classical_limit_ratio_lt_one3 {f:ℕ → ℝ} {r:ℝ} {k:ℕ}:
has_classical_limit (λ n:ℕ, (f (nat.succ n)) * (f n)⁻¹) r →
(r < 1) →
(0 ≤ r) →
(∀ n, k < n → 0 < f n) →
has_classical_limit f 0 :=
begin
intros A1 A2 A3 A4,
let g:ℕ → ℝ := λ n, if (k < n) then f n else 1,
begin
have A6:g = λ n, if (k < n) then f n else 1 := rfl,
have A5:has_classical_limit (λ n:ℕ, (g (nat.succ n)) * (g n)⁻¹) r,
{
have A5A:∀ n:ℕ, k < n →
(λ n:ℕ,(f (nat.succ n)) * (f n)⁻¹) n=
(λ n:ℕ, (g (nat.succ n)) * (g n)⁻¹) n,
{
intros n A5A1,
rw A6,
simp,
rw if_pos,
rw if_pos,
apply A5A1,
apply lt_trans,
apply A5A1,
apply lt_succ,
},
apply has_classical_limit_eq_after A1 A5A,
},
have A7:has_classical_limit g 0,
{
apply has_classical_limit_ratio_lt_one2,
apply A5,
apply A2,
apply A3,
{
intro n,
rw A6,
simp,
have A7A:k < n ∨ ¬ (k < n) := lt_or_not_lt,
cases A7A,
{
rw if_pos,
apply A4,
apply A7A,
apply A7A,
},
{
rw if_neg,
apply zero_lt_one,
apply A7A,
}
}
},
have A8:∀ n:ℕ, k < n → g n = f n,
{
intros n A8A,
rw A6,
simp,
rw if_pos,
apply A8A,
},
apply has_classical_limit_eq_after A7 A8,
end
end
lemma pow_cancel_ne_zero {r:ℝ} {n:ℕ}:((r≠ 0) → (r^(nat.succ n)) * (r^n)⁻¹ = r) :=
begin
intro A0,
induction n,
{
simp,
},
{
rw nat_succ_pow,
have A1:(r^(nat.succ n_n))⁻¹=r⁻¹ * (r^(n_n))⁻¹,
{
rw nat_succ_pow,
rw mul_inv',
},
rw A1,
rw mul_comm r,
rw mul_assoc,
rw ← mul_assoc r (r⁻¹),
rw mul_inv_cancel,
rw one_mul,
rw n_ih,
apply A0,
}
end
lemma has_classical_limit_ratio_one_exp {f:ℕ → ℝ} {r:ℝ} {k:ℕ}:
(∀ n:ℕ, k < n → 0 < f n) →
has_classical_limit (λ n:ℕ, (f (nat.succ n)) * (f n)⁻¹) 1 →
(r < 1) →
(0 < r) →
has_classical_limit (λ n:ℕ, f n * r^n) 0
:=
begin
intros A1 A2 A3 A4,
let g := (λ n:ℕ, f n * r^n),
begin
have A5:g = (λ n:ℕ, f n * r^n) := rfl,
have A6:has_classical_limit (λ n:ℕ, (g (nat.succ n)) * (g n)⁻¹) r,
{
have A6A:1 * r = r := one_mul r,
have A6B:(λ n:ℕ, (g (nat.succ n)) * (g n)⁻¹) =
(λ (n:ℕ), (f (nat.succ n)) * (f n)⁻¹ * r),
{
ext n,
rw A5,
simp,
rw mul_comm (f n) (r^n),
rw @mul_inv' _ _ (r^n) (f n),
rw mul_assoc,
rw ← mul_assoc (r^(nat.succ n)) (r^n)⁻¹ (f n)⁻¹,
rw pow_cancel_ne_zero,
{
rw mul_comm r,
rw mul_assoc,
},
{
intro A7,
rw A7 at A4,
apply lt_irrefl (0:ℝ),
apply A4,
}
},
rw ← A6A,
rw A6B,
apply has_classical_limit_mul,
{
apply A2,
},
{
apply has_classical_limit_const,
}
},
apply has_classical_limit_ratio_lt_one3,
{
apply A6,
},
{
apply A3,
},
{
apply le_of_lt,
apply A4,
},
{
intros n B1,
apply mul_pos,
{
apply A1,
apply B1,
},
{
apply pow_pos,
apply A4,
}
}
end
end
lemma has_classical_limit_poly_ratio {k:ℕ}:
has_classical_limit (λ (n : ℕ), ((nat.succ n):ℝ) ^ k * ((n:ℝ) ^ k)⁻¹) 1 :=
begin
induction k,
{
simp,
apply has_classical_limit_const,
},
{
have A1: (λ (n : ℕ), ((nat.succ n):ℝ) ^ nat.succ k_n * ((n:ℝ) ^ nat.succ k_n)⁻¹) =
(λ (n : ℕ), ((nat.succ n):ℝ ) * ((n:ℝ))⁻¹) *
(λ (n : ℕ), ((nat.succ n):ℝ) ^ k_n * ((n:ℝ) ^ k_n)⁻¹),
{
ext n,
simp,
rw nat_succ_pow,
rw nat_succ_pow,
rw mul_inv',
--rw mul_comm (↑n ^ k_n)⁻¹ (↑n)⁻¹,
rw ← mul_assoc,
rw mul_assoc ((n:ℝ) + 1) (((n:ℝ) + 1) ^ k_n) ((n:ℝ)⁻¹),
rw mul_comm (((n:ℝ) + 1) ^ k_n) ((n:ℝ)⁻¹),
rw ← mul_assoc ((n:ℝ) + 1) ((n:ℝ)⁻¹) (((n:ℝ) + 1) ^ k_n),
rw mul_assoc,
},
have A2:(1:ℝ) = (1:ℝ) * (1:ℝ),
{
rw mul_one,
},
rw A2,
rw A1,
apply has_classical_limit_mul,
{
apply has_classical_limit_ratio_one,
},
{
apply k_ih,
}
}
end
lemma has_classical_limit_poly_exp (x:ℝ) (k:ℕ):
(x < 1) →
(0 < x) →
has_classical_limit (λ n, n^k * x^n) 0 :=
begin
intros A1 A2,
apply has_classical_limit_ratio_one_exp,
{
intros n A3,
apply pow_pos,
simp,
apply A3,
},
{
apply has_classical_limit_poly_ratio,
},
{
apply A1,
},
{
apply A2,
}
end
lemma has_classical_limit_zero_exp {f:ℕ → ℝ}:has_classical_limit (λ n:ℕ, (0:ℝ)^n * (f n)) 0 :=
begin
unfold has_classical_limit,
intros ε A1,
apply exists.intro 0,
intros n' A2,
rw zero_exp_zero A2,
simp,
exact A1,
end
lemma has_classical_limit_offset {f:ℕ → ℝ} {x:ℝ} {k:ℕ}:
has_classical_limit f x ↔ has_classical_limit (f ∘ (λ n,k+n)) x :=
begin
unfold has_classical_limit,
split;intros A1 ε A2;have A3 := A1 ε A2;cases A3 with n A4,
{
apply exists.intro n,
intros n' A5,
have A6:n < k + n',
{
apply lt_of_lt_of_le,
apply A5,
simp,
},
have A7 := A4 (k + n') A6,
simp,
apply A7,
},
{
apply exists.intro (n + k),
intros n' A5,
have A6:n < n' - k,
{
apply nat_lt_sub_of_add_lt,
apply A5,
},
have A7 := A4 (n' - k) A6,
simp at A7,
have A8:k + (n' - k) = n',
{
rw add_comm,
apply nat_minus_cancel_of_le,
apply le_of_lt,
apply nat_lt_of_add_lt,
apply A5,
},
rw A8 at A7,
apply A7,
}
end
lemma has_classical_limit_ratio_power_fact {x:ℝ}:
has_classical_limit
(λ (n : ℕ), (x ^ (nat.succ n) * ((nat.fact (nat.succ n)):ℝ)⁻¹) *
(x ^ n * ((nat.fact n):ℝ)⁻¹)⁻¹ ) 0 :=
begin
have A1:x = 0 ∨ (x ≠ 0) := eq_or_ne,
cases A1,
{
rw A1,
have A2:(λ (n : ℕ), 0 ^ nat.succ n * ((nat.fact (nat.succ n)):ℝ)⁻¹ *
(0 ^ n * ((nat.fact n):ℝ )⁻¹)⁻¹)=λ (n:ℕ), (0:ℝ),
{
ext,
rw nat_succ_pow,
simp,
},
rw A2,
apply has_classical_limit_const,
},
{
have A2:(λ (n : ℕ), (x ^ (nat.succ n) * ((nat.fact (nat.succ n)):ℝ)⁻¹) *
(x ^ n * ((nat.fact n):ℝ)⁻¹)⁻¹ ) =(λ (n : ℕ), (x * (((nat.succ n)):ℝ)⁻¹)),
{
ext n,
rw nat_succ_pow,
rw mul_inv',
rw inv_inv',
rw ← mul_assoc,
simp,
rw mul_inv',
rw ← mul_assoc,
rw mul_assoc ( x * x ^ n * ((n:ℝ) + 1)⁻¹) (((nat.fact n):ℝ)⁻¹),
rw mul_comm _ (x^n)⁻¹,
rw mul_assoc,
rw mul_assoc (x^n)⁻¹,
rw @inv_mul_cancel ℝ _ ↑(n.fact),
rw mul_one,
rw mul_assoc,
rw mul_comm (((n:ℝ) + 1)⁻¹) ((x^n)⁻¹),
rw ← mul_assoc,
rw mul_assoc x (x ^ n),
rw mul_inv_cancel,
rw mul_one,
apply pow_ne_zero,
apply A1,
simp,
apply nat_fact_nonzero,
},
rw A2,
have A3:x * 0 = 0 := mul_zero x,
rw ← A3,
apply has_classical_limit_mul_const,
have A4:(λ (n : ℕ), ((nat.succ n):ℝ)⁻¹)=(λ (n : ℕ), (↑(n))⁻¹) ∘ (λ n:ℕ, 1 + n),
{
ext n,
simp,
rw add_comm,
},
rw A4,
rw ← has_classical_limit_offset,
apply has_classical_limit_inv_zero,
}
end
lemma has_classical_limit_supr_of_monotone_of_bdd_above {f:ℕ → ℝ}:
(monotone f) → (bdd_above (set.range f)) → has_classical_limit f (⨆ n, f n) :=
begin
intros A1 A2,
unfold has_classical_limit,
intros ε A3,
--have A4:∃ (x:ℝ) (H:x∈ (set.range f)), (⨆ n, f n) - ε < x,
have A4:∃ (n:ℕ), (⨆ n, f n) - ε < f n,
{
apply exists_lt_of_lt_csupr,
simp,
apply sub_lt_of_sub_lt,
rw sub_self,
apply A3,
},
cases A4 with n A5,
apply exists.intro n,
intros n' A6,
rw abs_lt_iff_in_Ioo,
split,
{
apply lt_of_lt_of_le A5,
apply A1,
apply le_of_lt A6,
},
{
have A7:f n' ≤ (⨆ n, f n),
{
apply le_csupr,
apply A2,
},
apply lt_of_le_of_lt A7,
simp,
apply A3,
}
end
lemma exists_classical_limit_of_monotone_of_bdd_above {f:ℕ → ℝ}:
(monotone f) → (bdd_above (set.range f)) → exists_classical_limit f :=
begin
intros A1 A2,
have A3:=has_classical_limit_supr_of_monotone_of_bdd_above A1 A2,
apply exists_classical_limit_intro A3,
end
/-
This is useful for any type which doesn't have a bottom.
-/
def multiset.max {α:Type*} [decidable_linear_order α]: multiset α → option α :=
(multiset.fold (option.lift_or_get max) none) ∘ (multiset.map some)
lemma multiset.max_insert {α:Type*} [decidable_linear_order α] {a:α} {s:multiset α}:
(insert a s).max = option.lift_or_get max (some a) s.max :=
begin
unfold multiset.max,
simp,
end
lemma multiset.max_insert2 {α:Type*} [decidable_linear_order α] {a:α} {s:multiset α}:
(a::s).max = option.lift_or_get max (some a) s.max :=
begin
unfold multiset.max,
simp,
end
lemma option_max {α:Type*} [decidable_linear_order α] {a:α} {b:option α} {c:α}:
option.lift_or_get max (some a) b = some c
→ a ≤ c :=
begin
intro A1,
cases b,
{
unfold option.lift_or_get at A1,
simp at A1,
rw A1,
},
{
unfold option.lift_or_get at A1,
simp at A1,
subst c,
apply le_max_left,
}
end
lemma option_max_some {α:Type*} [decidable_linear_order α] {a:α} {b:α} {c:α}:
option.lift_or_get max (some a) (some b) = some c
↔ max a b = c :=
begin
unfold option.lift_or_get,
simp,
end
lemma option_max_some_nonempty {α:Type*} [decidable_linear_order α] {a:α} {b:option α}:
∃ c:α, c∈ option.lift_or_get max (some a) b :=
begin
cases b;unfold option.lift_or_get;simp,
end
lemma multiset.max_some_nonempty {α:Type*} [decidable_linear_order α] {a:α} {s:multiset α}:
(a∈ s) → (∃ b, s.max = some b) :=
begin
apply multiset.induction_on s,
{
simp,
},
{
intros c t A1 A2,
rw multiset.max_insert2,
apply option_max_some_nonempty,
}
end
-- See:
theorem le_max_of_mem {S : multiset ℝ} {a: ℝ}:
a∈ S → (∃ b ∈ S.max, a ≤ b) :=
begin
apply multiset.induction_on S,
{
intros A1,
simp at A1,
exfalso,
apply A1,
},
{
intros c T A2 A3,
have A4:=multiset.max_some_nonempty A3,
cases A4 with b A5,
simp at A3,
apply exists.intro b,
simp,
split,
{
apply A5,
},
{
cases A3,
{
subst c,
unfold multiset.max at A5,
simp at A5,
apply option_max A5,
},
{
have A6 := A2 A3,
cases A6 with d A7,
cases A7 with A8 A9,
rw multiset.max_insert2 at A5,
simp at A8,
rw A8 at A5,
rw option_max_some at A5,
have A10 := le_max_right c d,
rw A5 at A10,
apply le_trans,
apply A9,
apply A10,
}
}
}
end
/-
There is probably the equivalent of this somewhere in the library.
-/
lemma bdd_above_of_exists_classical_limit {f:ℕ → ℝ}:
exists_classical_limit f → (bdd_above (set.range f)) :=
begin
intros A1,
/-
First, we choose an arbitrary boundary around the limit, say (x - 1) (x + 1).
Then, we use the definition of limit to prove that past some N, the value of
f is less than (x + 1). Then, below N, we take the max.
-/
unfold exists_classical_limit at A1,
cases A1 with x A2,
unfold has_classical_limit at A2,
have A3:(0:ℝ)<(1:ℝ) := zero_lt_one,
have A4 := A2 1 A3,
cases A4 with n A5,
unfold bdd_above,
have A6:∃ x1:ℝ, multiset.max (multiset.map f (multiset.range (nat.succ n))) = some x1,
{
have A6A:(f 0) ∈ (multiset.map f (multiset.range (nat.succ n))),
{
simp,
cases n,
{
left,refl,
},
{
right,
apply exists.intro 0,
split,
simp,
}
},
apply multiset.max_some_nonempty,
apply A6A,
},
cases A6 with x1 A7,
let x2 := max x1 (x + 1),
begin
have A8 : x2 = max x1 (x + 1) := rfl,
apply exists.intro x2,
unfold upper_bounds,
simp,
intros x3 n' A9,
have A10: (n < n') ∨ n' ≤ n:= lt_or_le n n',
cases A10,
{
right,
have A11 := A5 n' A10,
rw abs_lt_iff_in_Ioo at A11,
simp at A11,
rw ← A9,
apply le_of_lt A11.right,
},
{
left,
have A11:f n' ∈ (multiset.map f (multiset.range (nat.succ n))),
{
rw le_iff_lt_or_eq at A10,
simp,
cases A10,
{
right,
apply exists.intro n',
split,
apply A10,
refl,
},
{
left,
rw A10,
}
},
have A12:=le_max_of_mem A11,
cases A12 with b A13,
cases A13 with A14 A15,
rw A7 at A14,
simp at A14,
rw A14,
rw ← A9,
apply A15,
}
end
end
lemma has_classical_limit_supr_of_monotone_of_exists_classical_limit {f:ℕ → ℝ}:
monotone f →
exists_classical_limit f →
has_classical_limit f (⨆ n, f n) :=
begin
intros A1 A2,
have A3:(bdd_above (set.range f)) := bdd_above_of_exists_classical_limit A2,
apply has_classical_limit_supr_of_monotone_of_bdd_above A1 A3,
end
lemma has_classical_limit_le {f g:ℕ → ℝ} {x y:ℝ}:
has_classical_limit f x →
has_classical_limit g y →
f ≤ g → x ≤ y :=
begin
intros A1 A2 A3,
apply le_of_not_lt,
intro A4,
let ε := (x - y)/2,
begin
have A5:ε = (x - y)/2 := rfl,
have A6:0 < ε,
{
apply half_pos,
apply sub_pos_of_lt A4,
},
have A7 := A1 ε A6,
cases A7 with nf A8,
have A9 := A2 ε A6,
cases A9 with ng A10,
let n' := nat.succ (max nf ng),
begin
have A11:n' = nat.succ (max nf ng) := rfl,
have A12:nf < n',
{
rw A11,
apply nat.lt_succ_of_le,
apply le_max_left,
},
have A13:ng < n',
{
rw A11,
apply nat.lt_succ_of_le,
apply le_max_right,
},
have A14 := A8 n' A12,
have A15 := A10 n' A13,
have A16:x - ε < f n',
{
rw abs_lt2 at A14,
apply A14.left,
},
have A17:g n' < y + ε,
{
rw abs_lt2 at A15,
apply A15.right,
},
have A18:x - ε = y + ε,
{
apply half_equal A5,
},
have A19:g n' < f n',
{
apply lt_trans,
apply A17,
rw ← A18,
apply A16,
},
have A20:f n' ≤ g n',
{
apply A3,
},
apply not_lt_of_le A20,
apply A19,
end
end
end
|
10a703814da899d9a3e45c8c86a17053abf25ea9 | bde6690019e9da475b0c91d5a066e0f6681a1179 | /library/standard/equality_test.lean | 4e8afef39720d6bcf711fc76d2abe2074346996e | [
"Apache-2.0"
] | permissive | leodemoura/libraries | ae67d491abc580407aa837d65736d515bec39263 | 14afd47544daa9520ea382d33ba7f6f05c949063 | refs/heads/master | 1,473,601,302,073 | 1,403,713,370,000 | 1,403,713,370,000 | 19,831,525 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,818 | lean | ----------------------------------------------------------------------------------------------------
--
-- playing with the axioms
--
----------------------------------------------------------------------------------------------------
import kernel
import macros
-- the natural axioms for equality, together with refl
axiom subst_new {A : (Type U)} {a b : A} {P : A → Type} (H1 : P a) (H2 : a = b) : P b
axiom subst_new_id {A : (Type U)} {a : A} {P : A → Type} (H1 : P a) (e : a = a) : subst_new H1 e = H1
-- previously an axiom
theorem subst_old {A : (Type U)} {a b : A} {P : A → Bool} (H1 : P a) (H2 : a = b) : P b
:= subst_new H1 H2.
-- casting
definition cast_new {A B : Type} (e : A = B) (a : A) : B
:= subst_new a e
theorem cast_new_id {A : Type} (e : A = A) (a : A) : cast_new e a = a
:= subst_new_id a e
-- previously a variable
definition cast_old {A B : Type} (e : A == B) (a : A) : B
:= cast_new (to_eq e) a
-- previously an axiom
theorem cast_new_heq {A B : Type} (e : A = B) (a : A) : cast_new e a == a
:= subst_new
(show ∀ e : A = A, ∀ a : A, cast_new e a == a, from fun e, fun a, to_heq (@cast_new_id A e a))
e e a
-- corresponding axioms for hsubst
-- I am not sure we need them
-- axiom hsubst_new {A B : (Type U+1)} {a : A} {b : B} (P : ∀ T : (Type U+1), T → Type) :
-- P A a → a == b → P B b
-- axiom hsubst_new_id {A : (Type U+1)} {a : A} (P : ∀ T : (Type U+1), T → Type) (p : P A a)
-- (e : a == a): hsubst_new P p e = p
-- -- previously an axiom
-- theorem hsubst_old {A B : (Type U+1)} {a : A} {b : B} (P : ∀ T : (Type U+1), T → Bool)
-- (p : P A a) (e : a == b) : P B b
-- := hsubst_new P p e
-- why is the theorem hcongr1 in kernal.lean called that? maybe congr1_dep would be better?
-- then this would be hcongr1_dep
axiom hcongr1_new {A : (Type U+1)} {B B' : A → (Type U+1)} {f : ∀ x : A, B x} {f' : ∀ x : A, B' x}
(a : A) (e : f == f') : f a == f' a
-- previously an axiom
theorem hcongr_old {A A' : (Type U+1)} {B : A → (Type U+1)} {B' : A' → (Type U+1)}
{f : ∀ x : A, B x} {f' : ∀ x : A', B' x} {a : A} {a' : A'} :
f == f' → a == a' → f a == f' a'
:=
take eq_f_f' : f == f',
take eq_a_a' : a == a',
have aux : ∀ B B' : A → (Type U+1), ∀ f : ∀ x : A, B x, ∀ f' : ∀ x : A, B' x,
f == f' → f a == f' a, from (fun B B' : A → (Type U+1), fun f f' e, hcongr1_new a e),
-- it seems the elaborator can't infer the predicate here
-- (hsubst _ aux eq_a_a') B B' f f' eq_f_f'
hsubst
(fun X : (Type U+1), fun x : X,
∀ B : A → (Type U+1), ∀ B' : X → (Type U+1), ∀ f : ∀ x : A, B x, ∀ f' : ∀ x : X, B' x,
f == f' → f a == f' x)
aux eq_a_a' B B' f f' eq_f_f'
theorem hpiext_new {A : Type} {B B' : A → Type} (e : B = B') : (∀ x, B x) = (∀ x, B' x)
:=
let P := fun X : A → Type, (∀ x, B x) = (∀ x, X x) in
substp P (refl (∀ x, B x)) e
-- subst (refl _) e -- causes nontermination
theorem hpiext_old {A A' : Type} {B : A → Type} {B' : A' → Type}
(e : A = A') (H : ∀ x x', x == x' → B x == B' x') : (∀ x, B x) == (∀ x, B' x)
:=
have aux: ∀ B B' : A → Type, (∀ x x', x == x' → B x == B' x') → (∀ x, B x) == (∀ x, B' x), from (
take B B' : A → Type,
take H : (∀ x x', x == x' → B x == B' x'),
have H2 : ∀x, B x = B' x, from (take x : A, to_eq (H x x (hrefl x))),
have H3 : B = B', from funext H2,
to_heq (hpiext_new H3)
),
@subst_new _ _ _ (fun X,
∀ B : A → Type, ∀ B' : X → Type, (∀ x x', x == x' → B x == B' x') → (∀ x, B x) == (∀ x, B' x))
aux e B B' H
theorem app_cast {A : Type} {B B' : A → Type} (f : ∀ x, B x) (e : B = B')
(a : A) : cast_new (hpiext_new e) f a = cast_new (congr1 e a) (f a)
:=
let P := fun X : A → Type, ∀ e' : B = X,
cast_new (hpiext_new e') f a = cast_new (congr1 e' a) (f a) in
have H : P B, from (
take e', trans (hcongr1 (cast_new_id _ f) a) (symm (cast_new_id _ (f a)))),
have H2 : P B', from subst H e,
H2 e
-- should replace the old one
theorem type_eq_new {A B : Type} {a : A} {b : B} (e : a == b) : A = B
:= to_eq (type_eq e)
theorem heq_to_eq2 {A B : Type} {a : A} {b : B} (e : a == b):
cast_new (type_eq_new e) a = b
:= to_eq (htrans (cast_new_heq (type_eq_new e) a) e)
-- an alternative characterization of ==
-- could be used as a definition
theorem heq_equiv {A B : Type} {a : A} {b : B} :
(a == b) ↔ ∃ e : A = B, cast_new e a = b
:=
iff_intro (
assume e : a == b,
exists_intro (type_eq_new e) (heq_to_eq2 e)
) (
assume H : ∃ e : A = B, cast_new e a = b,
obtain (e : A = B) (H1 : cast_new e a = b), from H,
htrans (hsymm (cast_new_heq e a)) (to_heq H1)
)
theorem hrefl_sim {A : Type} {a : A} : ∃ e : A = A, cast_new e a = a
:=
exists_intro (refl A) (cast_new_id _ a)
theorem hsubst_sim {A B : Type} {a : A} {b : B} (P : ∀ T : Type, T → Bool)
(p : P A a) (H : ∃ e : A = B, cast_new e a = b) : P B b
:=
obtain (e : A = B) (e1: cast_new e a = b), from H,
have aux : ∀ e' : A = A, P A a → P A (cast_new e' a), from (
assume e' : A = A,
assume H' : P A a,
have e'' : a = cast_new e' a, from symm (cast_new_id e' a),
subst H' e''
),
-- let temp := @subst Type A B
-- (fun X : Type, ∀ e' : A = X, P A a → P X (cast_new e' a)) aux e in
have H2 : ∀ (e' : A = B), P A a → P B (cast_new e' a), from
@subst Type A B (fun X : Type, ∀ e' : A = X, P A a → P X (cast_new e' a)) aux e,
have H3 : P B (cast_new e a), from H2 e p,
subst H3 e1
axiom pi_ext (A : Type) (B B' : A → Type) : inhabited (∀ x, B x) → (∀ x, B x) = (∀ x, B' x) → B = B'
axiom sig_ext (A : Type) (B B' : A → Type) : inhabited A → (sig x, B x) = (sig x, B' x) → B = B'
|
d8d53e44e5408e4793d689ea1fcd5fc55c7b4678 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/whiskering.lean | 9d6aa2cc71e00cf94a03300cd5b25293f5b1ed24 | [
"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 | 8,128 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.natural_isomorphism
/-!
# Whiskering
Given a functor `F : C ⥤ D` and functors `G H : D ⥤ E` and a natural transformation `α : G ⟶ H`,
we can construct a new natural transformation `F ⋙ G ⟶ F ⋙ H`,
called `whisker_left F α`. This is the same as the horizontal composition of `𝟙 F` with `α`.
This operation is functorial in `F`, and we package this as `whiskering_left`. Here
`(whiskering_left.obj F).obj G` is `F ⋙ G`, and
`(whiskering_left.obj F).map α` is `whisker_left F α`.
(That is, we might have alternatively named this as the "left composition functor".)
We also provide analogues for composition on the right, and for these operations on isomorphisms.
At the end of the file, we provide the left and right unitors, and the associator,
for functor composition.
(In fact functor composition is definitionally associative, but very often relying on this causes
extremely slow elaboration, so it is better to insert it explicitly.)
We also show these natural isomorphisms satisfy the triangle and pentagon identities.
-/
namespace category_theory
universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄
section
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
If `α : G ⟶ H` then
`whisker_left F α : (F ⋙ G) ⟶ (F ⋙ H)` has components `α.app (F.obj X)`.
-/
@[simps] def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) :=
{ app := λ X, α.app (F.obj X),
naturality' := λ X Y f, by rw [functor.comp_map, functor.comp_map, α.naturality] }
/--
If `α : G ⟶ H` then
`whisker_right α F : (G ⋙ F) ⟶ (G ⋙ F)` has components `F.map (α.app X)`.
-/
@[simps] def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) :=
{ app := λ X, F.map (α.app X),
naturality' := λ X Y f,
by rw [functor.comp_map, functor.comp_map, ←F.map_comp, ←F.map_comp, α.naturality] }
variables (C D E)
/--
Left-composition gives a functor `(C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E))`.
`(whiskering_left.obj F).obj G` is `F ⋙ G`, and
`(whiskering_left.obj F).map α` is `whisker_left F α`.
-/
@[simps] def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) :=
{ obj := λ F,
{ obj := λ G, F ⋙ G,
map := λ G H α, whisker_left F α },
map := λ F G τ,
{ app := λ H,
{ app := λ c, H.map (τ.app c),
naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end },
naturality' := λ X Y f, begin ext, dsimp, rw [f.naturality] end } }
/--
Right-composition gives a functor `(D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E))`.
`(whiskering_right.obj H).obj F` is `F ⋙ H`, and
`(whiskering_right.obj H).map α` is `whisker_right α H`.
-/
@[simps] def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) :=
{ obj := λ H,
{ obj := λ F, F ⋙ H,
map := λ _ _ α, whisker_right α H },
map := λ G H τ,
{ app := λ F,
{ app := λ c, τ.app (F.obj c),
naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end },
naturality' := λ X Y f, begin ext, dsimp, rw [←nat_trans.naturality] end } }
variables {C} {D} {E}
@[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} :
whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) :=
rfl
@[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} :
whisker_left F (𝟙 G) = 𝟙 (F.comp G) :=
rfl
@[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) :
whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) :=
((whiskering_right C D E).obj F).map_id _
@[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) :
whisker_right (𝟙 G) F = 𝟙 (G.comp F) :=
((whiskering_right C D E).obj F).map_id _
@[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) :
whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) :=
rfl
@[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) :
whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) :=
((whiskering_right C D E).obj F).map_comp α β
/--
If `α : G ≅ H` is a natural isomorphism then
`iso_whisker_left F α : (F ⋙ G) ≅ (F ⋙ H)` has components `α.app (F.obj X)`.
-/
def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) :=
((whiskering_left C D E).obj F).map_iso α
@[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) :
(iso_whisker_left F α).hom = whisker_left F α.hom :=
rfl
@[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) :
(iso_whisker_left F α).inv = whisker_left F α.inv :=
rfl
/--
If `α : G ≅ H` then
`iso_whisker_right α F : (G ⋙ F) ≅ (H ⋙ F)` has components `F.map_iso (α.app X)`.
-/
def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) :=
((whiskering_right C D E).obj F).map_iso α
@[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) :
(iso_whisker_right α F).hom = whisker_right α.hom F :=
rfl
@[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) :
(iso_whisker_right α F).inv = whisker_right α.inv F :=
rfl
instance is_iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) [is_iso α] :
is_iso (whisker_left F α) :=
is_iso.of_iso (iso_whisker_left F (as_iso α))
instance is_iso_whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) [is_iso α] :
is_iso (whisker_right α F) :=
is_iso.of_iso (iso_whisker_right (as_iso α) F)
variables {B : Type u₄} [category.{v₄} B]
local attribute [elab_simple] whisker_left whisker_right
@[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) :
whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α :=
rfl
@[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) :
whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) :=
rfl
lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) :
whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) :=
rfl
end
namespace functor
universes u₅ v₅
variables {A : Type u₁} [category.{v₁} A]
variables {B : Type u₂} [category.{v₂} B]
/--
The left unitor, a natural isomorphism `((𝟭 _) ⋙ F) ≅ F`.
-/
@[simps] def left_unitor (F : A ⥤ B) : ((𝟭 A) ⋙ F) ≅ F :=
{ hom := { app := λ X, 𝟙 (F.obj X) },
inv := { app := λ X, 𝟙 (F.obj X) } }
/--
The right unitor, a natural isomorphism `(F ⋙ (𝟭 B)) ≅ F`.
-/
@[simps] def right_unitor (F : A ⥤ B) : (F ⋙ (𝟭 B)) ≅ F :=
{ hom := { app := λ X, 𝟙 (F.obj X) },
inv := { app := λ X, 𝟙 (F.obj X) } }
variables {C : Type u₃} [category.{v₃} C]
variables {D : Type u₄} [category.{v₄} D]
/--
The associator for functors, a natural isomorphism `((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H))`.
(In fact, `iso.refl _` will work here, but it tends to make Lean slow later,
and it's usually best to insert explicit associators.)
-/
@[simps] def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) :=
{ hom := { app := λ _, 𝟙 _ },
inv := { app := λ _, 𝟙 _ } }
lemma triangle (F : A ⥤ B) (G : B ⥤ C) :
(associator F (𝟭 B) G).hom ≫ (whisker_left F (left_unitor G).hom) =
(whisker_right (right_unitor F).hom G) :=
by { ext, dsimp, simp } -- See note [dsimp, simp].
variables {E : Type u₅} [category.{v₅} E]
variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E)
lemma pentagon :
(whisker_right (associator F G H).hom K) ≫
(associator F (G ⋙ H) K).hom ≫
(whisker_left F (associator G H K).hom) =
((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) :=
by { ext, dsimp, simp }
end functor
end category_theory
|
e7336e035ece0d26486d0d1874d0572af9de9f38 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/subst_test2.lean | 1f4e550881756f8905b86fe032937cd00f4f401e | [
"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 | 444 | lean | import data.nat
open nat
structure less_than (n : nat) := (val : nat) (lt : val < n)
namespace less_than
open decidable
set_option pp.beta false
definition less_than.has_decidable_eq [instance] (n : nat) : ∀ (i j : less_than n), decidable (i = j)
| (mk ival ilt) (mk jval jlt) :=
match nat.has_decidable_eq ival jval with
| inl veq := inl (by substvars)
| inr vne := inr (by intro h; injection h; contradiction)
end
end less_than
|
50087bcf9ab9fa107104e99f8c193413080a0aaa | 4727251e0cd73359b15b664c3170e5d754078599 | /src/set_theory/surreal/basic.lean | 8a2e6482a5bf247b81c286d1c9db1e1805e62920 | [
"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 | 14,188 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison
-/
import set_theory.game.pgame
/-!
# Surreal numbers
The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games.
A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and
all those options are themselves numeric. In terms of combinatorial games, the numeric games have
"frozen"; you can only make your position worse by playing, and Left is some definite "number" of
moves ahead (or behind) Right.
A surreal number is an equivalence class of numeric pregames.
In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else
besides!) but we do not yet have a complete development.
## Order properties
Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms
of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games).
## Algebraic operations
We show that the surreals form a linear ordered commutative group.
One can also map all the ordinals into the surreals!
### Multiplication of surreal numbers
The definition of multiplication for surreal numbers is surprisingly difficult and is currently
missing in the library. A sample proof can be found in Theorem 3.8 in the second reference below.
The difficulty lies in the length of the proof and the number of theorems that need to proven
simultaneously. This will make for a fun and challenging project.
## References
* [Conway, *On numbers and games*][conway2001]
* [Schleicher, Stoll, *An introduction to Conway's games and numbers*][schleicher_stoll]
-/
universes u
local infix ` ≈ ` := pgame.equiv
namespace pgame
/-- A pre-game is numeric if everything in the L set is less than everything in the R set,
and all the elements of L and R are also numeric. -/
def numeric : pgame → Prop
| ⟨l, r, L, R⟩ :=
(∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i))
lemma numeric_def (x : pgame) : numeric x ↔ (∀ i j, x.move_left i < x.move_right j) ∧
(∀ i, numeric (x.move_left i)) ∧ (∀ i, numeric (x.move_right i)) :=
by { cases x, refl }
lemma numeric.left_lt_right {x : pgame} (o : numeric x) (i : x.left_moves) (j : x.right_moves) :
x.move_left i < x.move_right j :=
by { cases x with xl xr xL xR, exact o.1 i j }
lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) :
numeric (x.move_left i) :=
by { cases x with xl xr xL xR, exact o.2.1 i }
lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
numeric (x.move_right j) :=
by { cases x with xl xr xL xR, exact o.2.2 j }
@[elab_as_eliminator]
theorem numeric_rec {C : pgame → Prop}
(H : ∀ l r (L : l → pgame) (R : r → pgame),
(∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) →
(∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) :
∀ x, numeric x → C x
| ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ :=
H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i))
theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x :=
begin
refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy,
refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _),
rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩),
{ exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) },
{ exact not_lt.2 (le_trans h₂ h₁) (hy _ _) },
{ exact not_lt.2 (le_trans h₁ h₂) (hx _ _) },
{ exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) },
end
theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y :=
not_lt.1 (lt_asymm ox oy h)
/-- `<` is transitive when both sides of the left inequality are numeric -/
theorem lt_trans {x y z : pgame} (ox : numeric x) (oy : numeric y) (h₁ : x < y)
(h₂ : y < z) : x < z :=
lt_of_le_of_lt (le_of_lt ox oy h₁) h₂
/-- `<` is transitive when both sides of the right inequality are numeric -/
theorem lt_trans' {x y z : pgame} (oy : numeric y) (oz : numeric z) (h₁ : x < y)
(h₂ : y < z) : x < z :=
lt_of_lt_of_le h₁ (le_of_lt oy oz h₂)
/-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they
don't on all pre-games). -/
theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) :
x < y ↔ x ≤ y ∧ ¬ y ≤ x :=
⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩
theorem numeric_zero : numeric 0 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩
theorem numeric_one : numeric 1 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩
theorem numeric.neg : Π {x : pgame} (o : numeric x), numeric (-x)
| ⟨l, r, L, R⟩ o := ⟨λ j i, lt_iff_neg_gt.1 (o.1 i j), λ j, (o.2.2 j).neg, λ i, (o.2.1 i).neg⟩
/-- For the `<` version, see `pgame.move_left_lt`. -/
theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) :
x.move_left i ≤ x :=
le_of_lt (o.move_left i) o (pgame.move_left_lt i)
/-- For the `<` version, see `pgame.lt_move_right`. -/
theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
x ≤ x.move_right j :=
le_of_lt o (o.move_right j) (pgame.lt_move_right j)
theorem add_lt_add
{w x y z : pgame.{u}} (oy : numeric y) (oz : numeric z)
(hwx : w < x) (hyz : y < z) : w + y < x + z :=
begin
rw lt_def_le at *,
rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩;
rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩,
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix _
... ≤ move_left x ix + move_left z iz : add_le_add_left hiz _
... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) _ },
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix _
... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy) _
... ≤ move_left x ix + z : add_le_add_left hjy _ },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw _
... ≤ x + move_left z iz : add_le_add_left hiz _
... ≤ x + z : add_le_add_left (oz.move_left_le iz) _ },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw _
... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy) _
... ≤ x + z : add_le_add_left hjy _ },
end
theorem numeric.add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y)
| ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy :=
⟨begin
rintros (ix|iy) (jx|jy),
{ show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩,
exact add_lt_add_right (ox.1 ix jx) _ },
{ show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy,
exact add_lt_add oy (oy.move_right jy) (pgame.lt_mk ix) (pgame.mk_lt jy), },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails?
exact add_lt_add (oy.move_left iy) oy (pgame.mk_lt jx) (pgame.lt_mk iy), },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails?
exact @add_lt_add_left pgame _ _ _ _ _ (oy.1 iy jy) ⟨xl, xr, xL, xR⟩ }
end,
begin
split,
{ rintros (ix|iy),
{ exact (ox.move_left ix).add oy },
{ exact ox.add (oy.move_left iy) } },
{ rintros (jx|jy),
{ apply (ox.move_right jx).add oy },
{ apply ox.add (oy.move_right jy) } }
end⟩
using_well_founded { dec_tac := pgame_wf_tac }
lemma numeric.sub {x y : pgame} (ox : numeric x) (oy : numeric y) : numeric (x - y) := ox.add oy.neg
/-- Pre-games defined by natural numbers are numeric. -/
theorem numeric_nat : Π (n : ℕ), numeric n
| 0 := numeric_zero
| (n + 1) := (numeric_nat n).add numeric_one
/-- The pre-game `half` is numeric. -/
theorem numeric_half : numeric half :=
begin
split,
{ rintros ⟨ ⟩ ⟨ ⟩,
exact zero_lt_one },
split; rintro ⟨ ⟩,
{ exact numeric_zero },
{ exact numeric_one }
end
theorem half_add_half_equiv_one : half + half ≈ 1 :=
begin
split; rw le_def; split,
{ rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩),
{ right,
use (sum.inr punit.star),
calc ((half + half).move_left (sum.inl punit.star)).move_right (sum.inr punit.star)
= (half.move_left punit.star + half).move_right (sum.inr punit.star) : by fsplit
... = (0 + half).move_right (sum.inr punit.star) : by fsplit
... ≈ 1 : zero_add_equiv 1
... ≤ 1 : pgame.le_refl 1 },
{ right,
use (sum.inl punit.star),
calc ((half + half).move_left (sum.inr punit.star)).move_right (sum.inl punit.star)
= (half + half.move_left punit.star).move_right (sum.inl punit.star) : by fsplit
... = (half + 0).move_right (sum.inl punit.star) : by fsplit
... ≈ 1 : add_zero_equiv 1
... ≤ 1 : pgame.le_refl 1 } },
{ rintro ⟨ ⟩ },
{ rintro ⟨ ⟩,
left,
use (sum.inl punit.star),
calc 0 ≤ half : le_of_lt numeric_zero numeric_half pgame.zero_lt_half
... ≈ 0 + half : (zero_add_equiv half).symm
... = (half + half).move_left (sum.inl punit.star) : by fsplit },
{ rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩); left,
{ exact ⟨sum.inr punit.star, le_of_le_of_equiv (pgame.le_refl _) (add_zero_equiv _).symm⟩ },
{ exact ⟨sum.inl punit.star, le_of_le_of_equiv (pgame.le_refl _) (zero_add_equiv _).symm⟩ } }
end
end pgame
/-- The equivalence on numeric pre-games. -/
def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1
instance surreal.setoid : setoid {x // pgame.numeric x} :=
⟨λ x y, x.1.equiv y.1,
λ x, pgame.equiv_refl _,
λ x y, pgame.equiv_symm,
λ x y z, pgame.equiv_trans⟩
/-- The type of surreal numbers. These are the numeric pre-games quotiented
by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient,
the order becomes a total order. -/
def surreal := quotient surreal.setoid
namespace surreal
open pgame
/-- Construct a surreal number from a numeric pre-game. -/
def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩
instance : has_zero surreal :=
{ zero := ⟦⟨0, numeric_zero⟩⟧ }
instance : has_one surreal :=
{ one := ⟦⟨1, numeric_one⟩⟧ }
instance : inhabited surreal := ⟨0⟩
/-- Lift an equivalence-respecting function on pre-games to surreals. -/
def lift {α} (f : ∀ x, numeric x → α)
(H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α :=
quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2)
/-- Lift a binary equivalence-respecting function on pre-games to surreals. -/
def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α)
(H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂),
x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α :=
lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h))
(λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _))
instance : has_le surreal :=
⟨lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy))⟩
instance : has_lt surreal :=
⟨lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy))⟩
/-- Addition on surreals is inherited from pre-game addition:
the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
instance : has_add surreal :=
⟨surreal.lift₂
(λ (x y : pgame) (ox) (oy), ⟦⟨x + y, ox.add oy⟩⟧)
(λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quotient.sound (pgame.add_congr hx hy))⟩
/-- Negation for surreal numbers is inherited from pre-game negation:
the negation of `{L | R}` is `{-R | -L}`. -/
instance : has_neg surreal :=
⟨surreal.lift
(λ x ox, ⟦⟨-x, ox.neg⟩⟧)
(λ _ _ _ _ a, quotient.sound (pgame.neg_congr a))⟩
instance : ordered_add_comm_group surreal :=
{ add := (+),
add_assoc := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact quotient.sound add_assoc_equiv },
zero := 0,
zero_add := by { rintros ⟨_⟩, exact quotient.sound (pgame.zero_add_equiv a) },
add_zero := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_zero_equiv a) },
neg := has_neg.neg,
add_left_neg := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_left_neg_equiv a) },
add_comm := by { rintros ⟨_⟩ ⟨_⟩, exact quotient.sound pgame.add_comm_equiv },
le := (≤),
lt := (<),
le_refl := by { rintros ⟨_⟩, refl },
le_trans := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact pgame.le_trans },
lt_iff_le_not_le := by { rintros ⟨_, ox⟩ ⟨_, oy⟩, exact pgame.lt_iff_le_not_le ox oy },
le_antisymm := by { rintros ⟨_⟩ ⟨_⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ },
add_le_add_left := by { rintros ⟨_⟩ ⟨_⟩ hx ⟨_⟩, exact @add_le_add_left pgame _ _ _ _ _ hx _ } }
noncomputable instance : linear_ordered_add_comm_group surreal :=
{ le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact
or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)),
decidable_le := classical.dec_rel _,
..surreal.ordered_add_comm_group }
-- We conclude with some ideas for further work on surreals; these would make fun projects.
-- TODO define the inclusion of groups `surreal → game`
-- TODO define the field structure on the surreals
end surreal
|
9bcd256bbb3ef121351d3e98857a152198f2fb0f | 50b3917f95cf9fe84639812ea0461b38f8f0dbe1 | /canonical_isomorphism/sheaf_canonical.lean | 14a6180a1c878c111c506feb24e93c17f36950ed | [] | no_license | roro47/xena | 6389bcd7dcf395656a2c85cfc90a4366e9b825bb | 237910190de38d6ff43694ffe3a9b68f79363e6c | refs/heads/master | 1,598,570,061,948 | 1,570,052,567,000 | 1,570,052,567,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,638 | lean | import data.equiv
-- recall the interface for equiv:
-- C : equiv α β;
-- the function is C, the function the other way is C.symm, which is also the equiv the other way
-- and the proofs are C.inverse_apply_apply and C.apply_inverse_apply
universes u v w x
-- category of foos
definition is_foo (α : Type u) : Prop := sorry
class foo (α : Type u) := -- replace with actual definition
(is_foo : is_foo α)
variables {R : Type u} {α : Type v} {β : Type w} {γ : Type x}
variables [foo R] [foo α] [foo β] [foo γ]
-- Now make foos into a category with, broadly speaking, a faithful forgetful
-- functor to Type. In practice I just mean that "morphisms" between
-- two foos α and β are just functions α → β which satisfy some properties,
-- and identity and composition are what you think they are.
namespace foo
-- we are now in the foo namespace, so "morphism" means "morphism of foos"
definition is_morphism (f : α → β) : Prop := sorry -- replace with actual definition
class morphism (f : α → β) :=
(is_morphism : is_morphism f)
variables {sα : R → α} {sβ : R → β} {sγ : R → γ} (f : α → β) (g : β → γ)
[foo.morphism sα] [foo.morphism sβ] [foo.morphism sγ] [foo.morphism f] [foo.morphism g]
-- axioms for a category
instance id_is_morphism (α : Type u) [foo α] : foo.morphism (@id α : α → α) := sorry
instance comp_is_morphism (f : α → β) (g : β → γ) [foo.morphism f] [foo.morphism g] : foo.morphism (λ x, g (f x)) := sorry
instance comp_is_morphism' (f : α → β) (g : β → γ) [foo.morphism f] [foo.morphism g] : foo.morphism (g ∘ f) := sorry
end foo
-- equiv in category of foos
structure foo_equiv (α : Type u) (β : Type v) [foo α] [foo β] extends equiv α β :=
(to_fun_morphism : foo.morphism to_fun)
(inv_fun_morphism : foo.morphism inv_fun)
instance to_fun_morphism_is_morphism (X : foo_equiv α β) := X.to_fun_morphism
instance inv_fun_morphism_is_morphism (X : foo_equiv α β) := X.inv_fun_morphism
infix ` ≃ₑ `:25 := foo_equiv -- I can't get a small f
namespace foo_equiv
-- foo_equiv is an equivalence relation
variable α
protected def refl : α ≃ₑ α := ⟨⟨id,id,λ x,rfl,λ x,rfl⟩,by apply_instance,by apply_instance⟩
variable {α}
protected def symm (f : α ≃ₑ β) : β ≃ₑ α := ⟨⟨f.inv_fun,f.to_fun,f.right_inv,f.left_inv⟩,f.inv_fun_morphism,f.to_fun_morphism⟩
protected def trans (f : α ≃ₑ β) (g : β ≃ₑ γ) : α ≃ₑ γ := ⟨⟨λ a, g.to_fun (f.to_fun a),λ c, f.inv_fun (g.inv_fun c),
λ a,by simp [g.left_inv (f.to_fun a),f.left_inv a],
λ c,by simp [f.right_inv (g.inv_fun c),g.right_inv c]⟩,
by apply_instance,by apply_instance⟩
end foo_equiv
namespace foo
-- important structure
definition is_unique_morphism (f : α → β) [foo.morphism f] : Prop := ∀ (g : α → β) [foo.morphism g], g = f
-- is this provable?
lemma comp_unique {α : Type v} {β : Type w} {γ : Type x}
[foo α] [foo β] [foo γ]
(f : α → β) (g : β → γ) (h : α → γ)
[foo.morphism f] [foo.morphism g] [foo.morphism h] :
is_unique_morphism f → is_unique_morphism g → is_unique_morphism h → g ∘ f = h := λ Hf Hg Hh,
Hh (g ∘ f)
-- isolating some specific interesting foos called "those which are nice".
-- Such nice foos have a certain universal property.
definition is_nice (α : Type u) [foo α] : Prop := sorry -- has content
-- here is the important property they have
theorem unique_morphism_from_loc {α : Type u} [foo α] (H : is_nice α)
{β : Type v} [foo β] (φ : α → β) [morphism φ] :
is_unique_morphism φ := sorry -- this proof will have some content, it is the property we want from nice foos
-- Now let R be a fixed foo. An R-foo is morphism R → α in the category
-- of foos.
definition is_R_foo_morphism {R : Type u} {α : Type v} {β : Type w} [foo R] [foo α] [foo β]
(sα : R → α) [morphism sα] (sβ : R → β) [morphism sβ] (f : α → β) [morphism f] : Prop := ∀ r : R, sβ r = f (sα r) -- "a triangle commutes"
-- Another key property, related to is_unique_morphism
definition is_unique_R_foo_morphism {R : Type u} {α : Type v} {β : Type w} [foo R] [foo α] [foo β]
(sα : R → α) [morphism sα] (sβ : R → β) [morphism sβ] (f : α → β) [morphism f] (H : is_R_foo_morphism sα sβ f) : Prop :=
∀ (g : α → β) [morphism g],by exactI is_R_foo_morphism sα sβ g → g = f
-- seems to be important for me; slightly convoluted statement.
-- R -> β unique morphism and α → β unique R-morphism implies α → ̌β unique morphism
theorem unique_of_unique_of_unique_R {R : Type u} {α : Type v} {β : Type w}
[foo R] [foo α] [foo β]
(sα : R → α) [morphism sα] (f : α → β) [morphism f] :
is_unique_morphism (f ∘ sα)
→ is_unique_R_foo_morphism sα (f ∘ sα) f (λ r,rfl)
→ is_unique_morphism f := λ H1 H2,begin
intros g Hg,letI := Hg,
have H3 : g ∘ sα = f ∘ sα := by simp [H1 (g ∘ sα)],
refine H2 g _,
intro r,rw ←H3,
end
end foo
/-
open equiv
-- Scott's basic class.
class transportable (f : Type u → Type v) :=
(on_equiv : Π {α β : Type u} (e : equiv α β), equiv (f α) (f β))
(on_refl : Π (α : Type u), on_equiv (equiv.refl α) = equiv.refl (f α))
(on_trans : Π {α β γ : Type u} (d : equiv α β) (e : equiv β γ),
on_equiv (equiv.trans d e) = equiv.trans (on_equiv d) (on_equiv e))
variables
{α : Type u} {β : Type v} {γ : Type w} {α' : Type u'} {β' : Type v'} {γ' : Type w'}
structure canonically_isomorphic_functions
(Cα : equiv α α') (Cβ : equiv β β') (f : α → β) (f' : α' → β') -- extends equiv α α', equiv β β'
:=
(commutes : ∀ a : α, Cβ (f a) = f' (Cα a))
-- is there a better way to do this with "extends"?
-- Do I need an interface for this? Why can't I make this a simp lemma?
theorem canonically_isomorphic_functions.diag_commutes
(Cα : equiv α α') (Cβ : equiv β β') (f : α → β) (f' : α' → β')
(C : canonically_isomorphic_functions Cα Cβ f f') : ∀ a : α, Cβ (f a) = f' (Cα a) := C.commutes
definition canonically_isomorphic_functions.refl :
Π {α : Type u} {β : Type v} (f : α → β), canonically_isomorphic_functions
(equiv.refl α) (equiv.refl β) f f := λ α β f,⟨λ a, rfl⟩
definition canonically_isomorphic_functions.symm :
∀ (f : α → β) (f' : α' → β') (Cα : equiv α α') (Cβ : equiv β β'),
canonically_isomorphic_functions Cα Cβ f f' →
canonically_isomorphic_functions Cα.symm Cβ.symm f' f :=
λ f f' Cα Cβ Cf,⟨λ a',begin
suffices : Cβ.symm (f' (Cα (Cα.symm a'))) = f (Cα.symm a'),
by simpa using this,
suffices : Cβ.symm (Cβ (f (Cα.symm a'))) = f (Cα.symm a'),
by simpa [Cf.commutes (Cα.symm a')],
simp,
end
⟩
definition canonically_isomorphic_functions.trans :
∀ (f : α → β) (f' : α' → β') (g : β → γ) (g' : β' → γ')
(Cα : equiv α α') (Cβ : equiv β β') (Cγ : equiv γ γ'),
canonically_isomorphic_functions Cα Cβ f f' →
canonically_isomorphic_functions Cβ Cγ g g' →
canonically_isomorphic_functions Cα Cγ (g ∘ f) (g' ∘ f') :=
λ f f' g g' Cα Cβ Cγ Cf Cg,⟨λ a,begin
show Cγ (g (f a)) = g' (f' (Cα a)),
rw [Cg.commutes,Cf.commutes]
end⟩
structure canonically_isomorphic_add_group_homs (Cα : equiv α α') (Cβ : equiv β β') (f : α → β) (f' : α' → β')
[add_group α] [add_group β] [add_group α'] [add_group β']
[is_group_hom f] [is_group_hom f']
:= sorry
-- extends canonically_isomorphic_functions Cα Cβ f f' -- how to get that to work?
:= sorry
(Cf : canonically_isomorphic_functions Cα Cβ f f')
-/
|
3ab1b4860a3987c83554961889136743e3993740 | d26814d9437130e14d6d016c92d8c436b6dc62f3 | /icat.hlean | 772fc39bb9c165e41a4e50af26aa35f008ad06f2 | [] | no_license | jonas-frey/segal | 92fb5a556c164d4e9e864f2da1258be5a6482af8 | 64b4ec62ec5f293b781d5bbfea5a6b0997558c13 | refs/heads/master | 1,594,256,935,764 | 1,566,490,351,000 | 1,566,490,351,000 | 203,831,654 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,130 | hlean | import hit.pushout hit.trunc arity my_prelude prop_join
ifin vector types.sigma
open trunc is_trunc nat pi prod function is_equiv ifin pushout equiv
eq vector sigma prod.ops trunc sigma.ops bool
universe u
definition tpower : Type.{0} → ℕ → Type.{0}
:= begin intros A n, induction n with n R, exact unit, exact A × R
end
definition proj {A : Type.{0}} {n : ℕ} (i : ifin n) : tpower A n → A
:= begin induction i with n' n' i' p, exact pr1, exact p ∘ pr2 end
definition is_trunc_tpower [instance] n A i [H : is_trunc i A]
: is_trunc i (tpower A n)
:= begin induction n, apply is_trunc_of_is_contr,
apply is_contr_unit, apply is_trunc_prod, apply v_0 end
notation `tr` x := trunctype.mk x _ --!is_trunc_pi
notation A ` ^ ` n := tpower A n -- vector A n --ifin n → A
prefix `#`:100 := nat.succ
notation `~`i := ifin_of_fin $ mk i dec_star
definition teq [constructor] {n : ℕ₋₂} {A : trunctype (n.+1)} (x y : A)
: trunctype n := trunctype.mk (x=y) !is_trunc_eq
infix ` == `:50 := teq
prefix `∨l`:100 := or.intro_left
prefix `∨r`:100 := or.intro_right
infix ` * ` := λ v i, proj i v
axiom I : Set.{0}
axioms (S T : I)
axiom LEQ : I → I → Prop.{0}
infix ` ≼ `:50 := LEQ
axiom REFL (x : I) : x ≼ x
axiom TRANS (x y z : I) : x ≼ y → y ≼ z → x ≼ z
axiom ASYM (x y : I) : x ≼ y → y ≼ x → x = y
axiom LIN (x y : I) : x ≼ y ∨ y ≼ x
axiom SMIN (x : I) : S ≼ x
axiom TMAX (x : I) : x ≼ T
axiom SNEQT : S ≠ T
-- enumeration set off by 1
definition delta (n : ℕ) (v : I^#n) : Prop.{0}
:= tr∀ i, v * emb i ≼ v * ifs i
definition boundary (n : ℕ) (w : I ^#n) : Prop.{0}
:= delta n w ∧ (w*ifz = S ∨ w*maxi = T ∨ ∃ i, w * emb i = w * ifs i)
-- these are the inner horns
definition horn (n : ℕ) (j : ifin n) (w : I^#n) : Prop.{0}
:= delta n w ∧ (w*ifz=S ∨ w*maxi=T ∨ ∃i, i≠j × w * emb i = w * ifs i)
definition spine (n : ℕ) (v : I^#n) : Prop.{0}
:= delta n v ∧ tr∀ i, v*i = S ∨ v*i = T
definition Δ (n) : Set.{0} := trΣ v, delta n v
definition Λ (n) (j) : Set.{0} := trΣ v, horn n j v
definition δΔ (n) : Set.{0} := trΣ v, boundary n v
definition Λ_to_Δ (n) (j) : Λ n j → Δ n := sigma.total $ λ v, pr1
definition δΔ_to_Δ (n) : δΔ n → Δ n := sigma.total $ λ v, pr1
definition segal n j (A : Type) : Type
:= is_equiv $ precompose A $ Λ_to_Δ n j
theorem segal_exp_closed n j (A B : Type)
: segal n j A → segal n j (B → A)
:= λ H, is_equiv.rec_on H $ λ fill rinv linv adj, adjointify _
(λ f h b, fill (λ v: Λ n j, f v b) h)
(λh, ↑(λ v, ↑(λb, rinv (λ v, h v b) ▻ v)))
(λf, ↑(λ v, ↑(λb, linv (λ v, f v b) ▻ v)))
definition cell {A : Type} {n : ℕ} (b : δΔ n → A) : Type
:= Σ s : Δ n → A, s ∘ δΔ_to_Δ n = b
-- 1-simplex, 1-horn, 1-spine
definition Δ1 := I
definition δΔ1 := Σ i, S=i ∨ T=i
check @or_pushout
definition blarb : δΔ1 ≃ bool :=
begin
refine (or_pushout (λi, S==i) (λi, T==i))⁻¹ᵉ ⬝e _,
fapply equiv.MK,
intro a, induction a, exact ff, exact tt,
induction x, induction a_1, exfalso,
exact SNEQT (a_1⬝a_2⁻¹),
intro b, induction b,
apply inl, exact dpair S rfl,
apply inr, exact dpair T rfl,
intro b, induction b, reflexivity,
reflexivity, intro a,
induction a, induction x, induction a_1,
reflexivity,
induction x, induction a_1, reflexivity,
induction x, induction a_1,
induction a_2, exfalso, exact SNEQT a_1
end
definition SS {n : ℕ} : I^n := nat.rec unit.star (λ a, pair S) n
definition TT {n : ℕ} : I^n := nat.rec unit.star (λ a, pair T) n
definition ISS {n : ℕ} : I → I^#n := λi, (i,SS)
definition rem {n : ℕ} : I^n → I^#n := λv, (T,v)
definition xxyy {A} {n} (f:I→A) (g:I^#n→A) (p : f T = g SS)
: Σ h : I^##n→A, (∀i, h(i,@SS (#n)) = f i) × (∀v, h(T,v) = g v)
:= begin
induction n, fconstructor, unfold tpower at g,
end
-- 2-simplex and 2-horn
definition delta2 : I×I → Prop.{0}
:= λ ij, prod.rec_on ij $ λ i j, i ≼ j
definition horn2 : I×I → Prop.{0}
:= λ ij, S == ij.1 ∨ T == ij.2
definition horn2_to_delta2 (ij : I × I) : horn2 ij → delta2 ij
:= prod.rec_on ij $ λ i j d, begin induction d with p p, esimp at p,
induction p, apply SMIN, esimp at p,
induction p, apply TMAX end
definition Δ2 : Set.{0} := trΣ ip, delta2 ip
definition Λ2 : Set.{0} := trΣ ip, horn2 ip
definition Λ2_to_Δ2 : Λ2 → Δ2 := sigma.total horn2_to_delta2
definition d0 : I → Δ2 := λi, dpair (i, T) !TMAX
definition d1 : I → Δ2 := λi, dpair (i, i) !REFL
definition d2 : I → Δ2 := λi, dpair (S, i) !SMIN
definition d0_h : I → Λ2 := λi, ⟨(i, T), ∨r rfl⟩
definition d2_h : I → Λ2 := λi, ⟨(S, i), ∨l rfl⟩
definition Δ2_SS : Δ2 := ⟨(S,S),SMIN S⟩
definition Δ2_ST : Δ2 := ⟨(S,T),SMIN T⟩
definition Δ2_TT : Δ2 := ⟨(T,T),TMAX T⟩
definition Λ2_SS : Λ2 := ⟨(S,S), ∨l rfl⟩
definition Λ2_TT : Λ2 := ⟨(T,T), ∨r rfl⟩
definition left_slice_equiv {A B : Type} (a0 : A)
: B ≃ (Σ ab : A×B, a0 = ab.1)
:= begin fapply equiv.MK,
{intro b, apply dpair (a0,b), esimp},
{λdp, dp.1.2},
{intro dp, induction dp with ab p, induction ab with a b,
esimp at p, induction p, apply sigma_eq, apply idpatho},
{intro b, reflexivity}
end
definition right_slice_equiv {A B : Type} (b0 : B)
: A ≃ (Σ ab : A×B, b0 = ab.2)
:= begin fapply equiv.MK,
{intro a, apply dpair (a,b0), esimp},
{λdp, dp.1.1},
{intro dp, induction dp with ab p, induction ab with a b,
esimp at p, induction p, apply sigma_eq, apply idpatho},
{intro a, reflexivity},
end
definition Λ2_pushout_char : pushout (λx:unit, T) (λx:unit, S) ≃ Λ2
:= begin
refine _ ⬝e !or_pushout, fapply pushout.equiv,
{ symmetry, apply equiv_unit_of_is_contr,
fapply is_contr.mk, fconstructor, exact (S, T),
fconstructor, esimp, esimp,
intro, apply sigma_eq, apply is_prop.elimo,
induction a, induction a with i j, induction a_1 with p q,
apply prod_eq, exact p, exact q
},
{ apply left_slice_equiv},
{ apply right_slice_equiv},
{ reflexivity},
{ reflexivity}
end
structure has_composition [class] (A : Type)
:= (pce : is_equiv $ precompose A Λ2_to_Δ2)
structure icat [class]
:= (carrier : Type) (hc : has_composition carrier)
attribute [coercion] icat.carrier
definition mor {A : Type} (a b : A) : Type
:= Σ f : I → A, f S = a × f T = b
definition twocell {A : Type} (a b c : A)
(f : mor a b) (g : mor b c) (h : mor a c)
:= Σ d : Δ2 → A,
definition id_mor {A : Type} {a : A} : mor a a
:= dpair (λi, a) (rfl, rfl)
-- modus ponens
definition mp (A : Type) {B : Type} : A → (A → B) → B := λ a f, f a
definition face0 {C : icat} (h : Δ2 → C) : mor (h Δ2_ST) (h Δ2_TT)
:= ⟨ h ∘ d0
, ( h ◅ sigma_eq rfl !is_prop.elimo
, h ◅ sigma_eq rfl !is_prop.elimo
)
⟩
definition face1 {C : icat} (h : Δ2 → C) : mor (h Δ2_SS) (h Δ2_TT)
:= ⟨ h ∘ d1
, ( h ◅ sigma_eq rfl !is_prop.elimo
, h ◅ sigma_eq rfl !is_prop.elimo
)
⟩
definition face2 {C : icat} (h : Δ2 → C) : mor (h Δ2_SS) (h Δ2_ST)
:= ⟨ h ∘ d2
, ( h ◅ sigma_eq rfl !is_prop.elimo
, h ◅ sigma_eq rfl !is_prop.elimo
)
⟩
-- definition comp_fil {C : icat} {a b c : C} (f : mor a b) (g : mor b c)
-- : Σ h : Δ2 → C, face2 h = f × face1 h = g
-- := begin end
definition comp_mor {C : icat} {a b c : C}
: mor b c → mor a b → mor a c
:= begin induction C with C H, induction H,
induction pce with comp rinv linv, intros g f,
apply mp (Σ h : Λ2→C, h Λ2_SS = a × h Λ2_TT = c),
{ induction f with f cdf, induction cdf with cf df,
induction g with g cdg, induction cdg with cg dg,
induction df, induction cf, induction dg,
fconstructor,
{ refine _ ∘ Λ2_pushout_char⁻¹ᶠ, intro po,
induction po with i j gl, exact f i, exact g j, exact cg⁻¹
},{ exact (rfl, rfl)}
},{ intro hpq, induction hpq with h pq, induction pq with p q,
exact ⟨ comp h ∘ d1
, ( comp h ◅ sigma_eq rfl !is_prop.elimo ⬝ rinv h ▻ Λ2_SS ⬝ p
, comp h ◅ sigma_eq rfl !is_prop.elimo ⬝ rinv h ▻ Λ2_TT ⬝ q
)
⟩
}
end
infix ` • `:59 := comp_mor
definition to_mor [coercion] {C : icat} (f : I → C) : mor (f S) (f T)
:= ⟨f, (rfl, rfl)⟩
definition comp_check {C : icat} (h : Δ2 → C)
: face0 h • face2 h = face1 h
:= begin
end
definition left_unit {C : icat} {a b : C} (f : mor a b)
: id_mor • f = f
:= begin
end
definition hom {A : Type} (a b : A) : Type
:= Σ f : I → A, f S = a × f T = b
definition matching_pairs (A : Type) : Type
:= Σ f g : I → A, f T = g S
definition triangles_to_matching_pairs (A : Type)
: (Δ2 → A) → matching_pairs A
:= begin intros t, fconstructor, exact t ∘ d2, fconstructor, exact t∘ d0,
apply ap t, fapply sigma_eq, esimp, apply is_prop.elimo end
definition has_composition (A : Type) : Type
:= is_equiv $ triangles_to_matching_pairs A
structure icat [class] (A : Type) := (hc : has_composition A)
definition compose {A : Type} [H : icat A] {a b c : A}
: hom b c → hom a b → hom a c
:= begin induction H, intros g f, induction hc with C,
induction f with f pq, induction pq with pf qf,
induction g with g pq, induction pq with pg qg, induction pf, induction qf, induction qg,
assert mapa : matching_pairs A, apply dpair f, apply dpair g, exact pg⁻¹,
fconstructor, exact C mapa ∘ d1, split, unfold mapa, end
-- faces
-- false ~ source, true ~ target
open sum sigma function
definition cube_map {n m : ℕ} (f : ifin m → ifin n + bool) : I^n → I^m
:= begin
intro v, apply vector_of_ifin_power, intro i, cases f i, exact v*a,
cases a, exact s, exact t
end
definition imp_trans {A C : Type} (B : Type) : (A→B) → (B→C) → (A → C)
:= λf g, g ∘ f
definition is_face (n m : ℕ) (f : ifin m → ifin n + bool)
: (∀i:ifin n, Σ j:ifin m, f j = inl i) → is_embedding (cube_map f)
:= begin
apply @imp_trans
(∀i:ifin n, Σ j:ifin m, f j = inl i) (is_embedding (cube_map f))
(Σ h : ifin n → ifin m, Π i, f (h i) = inl i),
intro H,
fconstructor, exact λx, pr1 (H x), exact λx, pr2 (H x),intro p,
induction p with h H, apply is_embedding_of_is_injective,
intro v w,
{
intro p, apply eq_of_feq !vector_equiv_ifin_power, apply ↑, intro i,
calc v * i = cube_map f v * h i : begin unfold cube_map, rewrite [proj_is_eval, H] end
... = cube_map f w * h i : (λ x, x * (h i)) ◅ p
... = w * i : begin unfold cube_map, rewrite [proj_is_eval, H] end,
},
end
theorem l10_pb : Λ 1 ifz ≃ pushout (λx : unit, t) (λx : unit, s)
:= begin
transitivity (Σv:I^2, v * ifz = s ∨ v * maxi = t),
{
apply total_equiv, intro v,
fapply is_trunc.equiv_of_is_prop,
{ intro x, induction x with x y, induction y with y y,
exact or.intro_left y, induction y,
exact or.intro_right a, induction b, induction a with i p,
induction p, cases i, exact empty.elim (a rfl), cases a_2
},
{ unfold horn, intro, induction a, fconstructor,
intro i, cases i, krewrite a, apply smin,
cases a_1, apply or.intro_left a, fconstructor,
intro i, cases i, krewrite b, apply tmax,
cases a, apply or.intro_right, apply or.intro_left b
},
{ exact _},
{ exact _}
},
{
refine or_pushout (λv:I^2, v*ifz==s) (λ v, v*maxi==t) ⬝e _,
fapply pushout.equiv,
fapply equiv.MK (λx, unit.star)
(λ x:unit, dpair [s,t] (rfl, rfl))
(λx, !is_prop.elim),
{ intro u, fapply sigma_eq, induction u,
induction a_1, apply vector_eq, exact a_1⁻¹,esimp,
exact @vector_eq _ _ [t] (tail a) (a_2⁻¹) !vector0_eq_nil⁻¹,
exact !is_prop.elimo
},
fapply equiv.MK, intro u, induction u with v p, exact v * maxi,
λ i, dpair [s,i] rfl,
intro i, esimp, intro u, induction u with v p,
fapply sigma_eq, esimp, apply vector_eq, exact p⁻¹,
apply vector_eq, exact rfl,
exact !vector0_eq_nil⬝!vector0_eq_nil⁻¹, apply is_prop.elimo,
fapply equiv.MK, intro u, induction u with v p, exact v * ifz,
intro i, apply dpair [i,t],
esimp,
intro i, esimp, intro u, induction u with v p,
fapply sigma_eq, apply vector_eq,
esimp, apply vector_eq,
exact p⁻¹, exact !vector0_eq_nil⬝!vector0_eq_nil⁻¹, apply is_prop.elimo,
intro, induction x, induction a_1, exact a_2,
intro, induction x,induction a_1, exact a_1
}
end
-- definition flip : I^2 → I^2
-- | [i,j] := [j,i]
definition flup : ifin 2 → ifin 2
:= ifin_power_of_vector [maxi, ifz]
definition eflup : ifin 2 ≃ ifin 2
:= begin
fapply equiv.MK, exact flup, exact flup,
intro i, cases i with i, reflexivity,
cases a, reflexivity, cases a_1,
intro i, cases i with i, reflexivity,
cases a, reflexivity, cases a_1,
end
definition hypo : I → Δ 1 :=
begin intro i, fconstructor, exact [i,i], unfold delta, esimp,
intro j, cases j, apply ref, cases a end
definition set_equiv_diag {A : Set} : A ≃ Σ v : A^2, v*ifz = v*(ifs ifz)
:= begin
fapply equiv.MK, λ a, dpair [a,a] begin reflexivity end,
λ dp, pr1 dp * ifz, intro dp, induction dp with v p, fapply sigma_eq,
fapply vector_eq, esimp, fapply vector_eq, exact p,
apply !vector0_eq_nil⁻¹
end
open prod prod.ops
definition square_decompose : I^2 ≃ pushout hypo hypo
:= begin
transitivity (Σ v:I^2, v*ifz ≼ v*maxi ∨ v*maxi≼v*ifz),
{ transitivity (Σ v:I^2, unit),
exact !sigma_unit_right⁻¹ᵉ,
apply total_equiv,
λ v, equiv_of_is_prop (λx, !lin) (λx, unit.star) _ _
},{ refine !or_pushout ⬝e _,
symmetry,
fapply pushout.equiv,
{ transitivity (Σv:I^2, v*ifz=v*maxi),
apply set_equiv_diag,
apply total_equiv,
intro v, apply equiv_of_is_prop,
intro H, rewrite H, exact (!ref, !ref),
λ u, asym _ _ u.1 u.2, exact _, exact _
},{ apply total_equiv, intro v,
cases v, cases a_1, cases a_3, unfold delta,
apply equiv_of_is_prop,
intro p, intro w,cases w, exact p, esimp, cases a, cases v,
intro, apply a_2, exact _, exact _
},{ unfold Δ, unfold delta,
fapply sigma_equiv_sigma, apply vector_equiv_of_ifin_equiv,
apply eflup,
intro v, apply equiv_of_is_prop, intro h i, cases i, apply h,
cases a, intro h, apply h ifz, exact _, exact _
},{ intros, esimp,
induction x with i pp, induction pp with H1 H2, cases i,
clear e_1, cases a_1, cases a_3, rename a i, rename a_2 j,
esimp at H1, esimp at H2, assert H : i = j, apply asym,
apply H1, apply H2, induction H, fapply sigma_eq, esimp,
apply is_prop.elimo
},{ intros, esimp,
induction x with i pp, induction pp with H1 H2, cases i,
clear e_1, cases a_1, cases a_3, rename a i, rename a_2 j,
esimp at H1, esimp at H2, assert H : i = j, apply asym,
apply H1, apply H2, induction H, fapply sigma_eq, esimp,
apply is_prop.elimo
}
}
end
definition foo (x : vector nat 3) : unit :=
match x with [a, b, c] := unit.star end
-- theorem bin_enough (A : Type)
-- : has_composition 1 ifz A → has_composition 2 ifz A :=
-- begin
-- unfold has_composition,
-- intro e,
-- induction e with f rinv linv coh,
-- fapply adjointify, intros h v,
-- end
|
07dba0cc9f5ce9941c0dd53e3668e3e2b2860134 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/big_operators/default.lean | 93732f096814c9c164468de4a4f19d9720651a5c | [] | 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 | 417 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.big_operators.order
import Mathlib.algebra.big_operators.intervals
import Mathlib.algebra.big_operators.ring
import Mathlib.algebra.big_operators.pi
import Mathlib.algebra.big_operators.finsupp
import Mathlib.algebra.big_operators.nat_antidiagonal
import Mathlib.algebra.big_operators.enat
import Mathlib.PostPort
namespace Mathlib
|
6b09808d26c1d6459cb89563018c23b923804d69 | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Init/Data/Array/Basic.lean | 9cae7da3277f4d0ebab3634656d0adb8786134f1 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,832 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Nat.Basic
import Init.Data.Fin.Basic
import Init.Data.UInt
import Init.Data.Repr
import Init.Data.ToString
import Init.Control.Id
import Init.Util
universes u v w
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (α : Type u) :=
(sz : Nat)
(data : Fin sz → α)
attribute [extern "lean_array_mk"] Array.mk
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_sz"] Array.sz
@[reducible, extern "lean_array_get_size"]
def Array.size {α : Type u} (a : @& Array α) : Nat :=
a.sz
namespace Array
variables {α : Type u}
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def mkEmpty (c : @& Nat) : Array α :=
{ sz := 0,
data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) }
@[extern "lean_array_push"]
def push (a : Array α) (v : α) : Array α :=
{ sz := Nat.succ a.sz,
data := fun ⟨j, h₁⟩ =>
if h₂ : j = a.sz then v
else a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) h₂⟩ }
@[extern "lean_mk_array"]
def mkArray {α : Type u} (n : Nat) (v : α) : Array α :=
{ sz := n,
data := fun _ => v}
theorem szMkArrayEq {α : Type u} (n : Nat) (v : α) : (mkArray n v).sz = n :=
rfl
def empty : Array α :=
mkEmpty 0
instance : HasEmptyc (Array α) :=
⟨Array.empty⟩
instance : Inhabited (Array α) :=
⟨Array.empty⟩
def isEmpty (a : Array α) : Bool :=
a.size = 0
def singleton (v : α) : Array α :=
mkArray 1 v
@[extern "lean_array_fget"]
def get (a : @& Array α) (i : @& Fin a.size) : α :=
a.data i
/- Low-level version of `fget` which is as fast as a C array read.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fget` may be slightly slower than `uget`. -/
@[extern "lean_array_uget"]
def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α :=
a.get ⟨i.toNat, h⟩
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def get! [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
if h : i < a.size then a.get ⟨i, h⟩ else arbitrary α
def back [Inhabited α] (a : Array α) : α :=
a.get! (a.size - 1)
def get? (a : Array α) (i : Nat) : Option α :=
if h : i < a.size then some (a.get ⟨i, h⟩) else none
def getD (a : Array α) (i : Nat) (v₀ : α) : α :=
if h : i < a.size then a.get ⟨i, h⟩ else v₀
def getOp [Inhabited α] (self : Array α) (idx : Nat) : α :=
self.get! idx
-- auxiliary declaration used in the equation compiler when pattern matching array literals.
abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α :=
a.get ⟨i, h₁.symm ▸ h₂⟩
@[extern "lean_array_fset"]
def set (a : Array α) (i : @& Fin a.size) (v : α) : Array α :=
{ sz := a.sz,
data := fun j => if h : i = j then v else a.data j }
theorem szFSetEq (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size :=
rfl
theorem szPushEq (a : Array α) (v : α) : (push a v).size = a.size + 1 :=
rfl
/- Low-level version of `fset` which is as fast as a C array fset.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fset` may be slightly slower than `uset`. -/
@[extern "lean_array_uset"]
def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α :=
a.set ⟨i.toNat, h⟩ v
/- "Comfortable" version of `fset`. It performs a bound check at runtime. -/
@[extern "lean_array_set"]
def set! (a : Array α) (i : @& Nat) (v : α) : Array α :=
if h : i < a.size then a.set ⟨i, h⟩ v else panic! "index out of bounds"
@[extern "lean_array_fswap"]
def swap (a : Array α) (i j : @& Fin a.size) : Array α :=
let v₁ := a.get i;
let v₂ := a.get j;
let a := a.set i v₂;
a.set j v₁
@[extern "lean_array_swap"]
def swap! (a : Array α) (i j : @& Nat) : Array α :=
if h₁ : i < a.size then
if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩
else panic! "index out of bounds"
else panic! "index out of bounds"
@[inline] def swapAt {α : Type} (a : Array α) (i : Fin a.size) (v : α) : α × Array α :=
let e := a.get i;
let a := a.set i v;
(e, a)
-- TODO: delete as soon as we can define local instances
@[neverExtract] private def swapAtPanic! [Inhabited α] (i : Nat) : α × Array α :=
panic! ("index " ++ toString i ++ " out of bounds")
@[inline] def swapAt! {α : Type} (a : Array α) (i : Nat) (v : α) : α × Array α :=
if h : i < a.size then swapAt a ⟨i, h⟩ v else @swapAtPanic! _ ⟨v⟩ i
@[extern "lean_array_pop"]
def pop (a : Array α) : Array α :=
{ sz := Nat.pred a.size,
data := fun ⟨j, h⟩ => a.get ⟨j, Nat.ltOfLtOfLe h (Nat.predLe _)⟩ }
-- TODO(Leo): justify termination using wf-rec
partial def shrink : Array α → Nat → Array α
| a, n => if n ≥ a.size then a else shrink a.pop n
section
variables {m : Type v → Type w} [Monad m]
variables {β : Type v} {σ : Type u}
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : Nat → β → m β
| i, b =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
f idx (a.get idx) b >>= iterateMAux (i+1)
else pure b
@[inline] def iterateM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β :=
iterateMAux a f 0 b
@[inline] def foldlM (f : β → α → m β) (init : β) (a : Array α) : m β :=
iterateM a init (fun _ b a => f a b)
@[inline] def foldlFromM (f : β → α → m β) (init : β) (a : Array α) (beginIdx : Nat := 0) : m β :=
iterateMAux a (fun _ b a => f a b) beginIdx init
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateM₂Aux (a₁ : Array α) (a₂ : Array σ) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : Nat → β → m β
| i, b =>
if h₁ : i < a₁.size then
let idx₁ : Fin a₁.size := ⟨i, h₁⟩;
if h₂ : i < a₂.size then
let idx₂ : Fin a₂.size := ⟨i, h₂⟩;
f idx₁ (a₁.get idx₁) (a₂.get idx₂) b >>= iterateM₂Aux (i+1)
else pure b
else pure b
@[inline] def iterateM₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : m β :=
iterateM₂Aux a₁ a₂ f 0 b
@[inline] def foldlM₂ (f : β → α → σ → m β) (b : β) (a₁ : Array α) (a₂ : Array σ): m β :=
iterateM₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂)
@[specialize] partial def findSomeMAux (a : Array α) (f : α → m (Option β)) : Nat → m (Option β)
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
do r ← f (a.get idx);
match r with
| some v => pure r
| none => findSomeMAux (i+1)
else pure none
@[inline] def findSomeM? (a : Array α) (f : α → m (Option β)) : m (Option β) :=
findSomeMAux a f 0
@[specialize] partial def findSomeRevMAux (a : Array α) (f : α → m (Option β)) : ∀ (idx : Nat), idx ≤ a.size → m (Option β)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let idx : Fin a.size := ⟨i - 1, this⟩;
do
r ← f (a.get idx);
match r with
| some v => pure r
| none =>
have i - 1 ≤ a.size from Nat.leOfLt this;
findSomeRevMAux (i-1) this
else pure none
@[inline] def findSomeRevM? (a : Array α) (f : α → m (Option β)) : m (Option β) :=
findSomeRevMAux a f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def findMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option α)
| i =>
if h : i < a.size then do
let v := a.get ⟨i, h⟩;
condM (p v) (pure (some v)) (findMAux (i+1))
else pure none
@[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) :=
findMAux a p 0
@[inline] def find? {α : Type} (a : Array α) (p : α → Bool) : Option α :=
Id.run $ a.findM? p
@[specialize] partial def findRevMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : ∀ (idx : Nat), idx ≤ a.size → m (Option α)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v := a.get ⟨i - 1, this⟩;
do {
condM (p v) (pure (some v)) $
have i - 1 ≤ a.size from Nat.leOfLt this;
findRevMAux (i-1) this
}
else pure none
@[inline] def findRevM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) :=
findRevMAux a p a.size (Nat.leRefl _)
@[inline] def findRev? {α : Type} (a : Array α) (p : α → Bool) : Option α :=
Id.run $ a.findRevM? p
section
variables {β : Type w} {σ : Type u}
@[inline] def iterate (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateMAux a f 0 b
@[inline] def iterateFrom (a : Array α) (b : β) (i : Nat) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateMAux a f i b
@[inline] def foldl (f : β → α → β) (init : β) (a : Array α) : β :=
iterate a init (fun _ a b => f b a)
@[inline] def foldlFrom (f : β → α → β) (init : β) (a : Array α) (beginIdx : Nat := 0) : β :=
Id.run $ foldlFromM f init a beginIdx
@[inline] def iterate₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → β) : β :=
Id.run $ iterateM₂Aux a₁ a₂ f 0 b
@[inline] def foldl₂ (f : β → α → σ → β) (b : β) (a₁ : Array α) (a₂ : Array σ) : β :=
iterate₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂)
@[inline] def findSome? (a : Array α) (f : α → Option β) : Option β :=
Id.run $ findSomeMAux a f 0
@[inline] def findSome! [Inhabited β] (a : Array α) (f : α → Option β) : β :=
match findSome? a f with
| some b => b
| none => panic! "failed to find element"
@[inline] def findSomeRev? (a : Array α) (f : α → Option β) : Option β :=
Id.run $ findSomeRevMAux a f a.size (Nat.leRefl _)
@[inline] def findSomeRev! [Inhabited β] (a : Array α) (f : α → Option β) : β :=
match findSomeRev? a f with
| some b => b
| none => panic! "failed to find element"
@[specialize] partial def findIdxMAux {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option Nat)
| i =>
if h : i < a.size then
condM (p (a.get ⟨i, h⟩)) (pure (some i)) (findIdxMAux (i+1))
else
pure none
@[inline] def findIdxM? {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : m (Option Nat) :=
findIdxMAux a p 0
@[specialize] partial def findIdxAux (a : Array α) (p : α → Bool) : Nat → Option Nat
| i =>
if h : i < a.size then
if p (a.get ⟨i, h⟩) then some i else findIdxAux (i+1)
else
none
@[inline] def findIdx? (a : Array α) (p : α → Bool) : Option Nat :=
findIdxAux a p 0
@[inline] def findIdx! (a : Array α) (p : α → Bool) : Nat :=
match findIdxAux a p 0 with
| some i => i
| none => panic! "failed to find element"
def getIdx? [HasBeq α] (a : Array α) (v : α) : Option Nat :=
a.findIdx? $ fun a => a == v
end
section
variables {m : Type → Type w} [Monad m]
@[specialize] partial def anyRangeMAux (a : Array α) (endIdx : Nat) (hlt : endIdx ≤ a.size) (p : α → m Bool) : Nat → m Bool
| i =>
if h : i < endIdx then
let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe h hlt⟩;
do b ← p (a.get idx);
match b with
| true => pure true
| false => anyRangeMAux (i+1)
else pure false
@[inline] def anyM (a : Array α) (p : α → m Bool) : m Bool :=
anyRangeMAux a a.size (Nat.leRefl _) p 0
@[inline] def allM (a : Array α) (p : α → m Bool) : m Bool := do
b ← anyM a (fun v => do b ← p v; pure (!b)); pure (!b)
@[inline] def anyRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool :=
if h : endIdx ≤ a.size then
anyRangeMAux a endIdx h p beginIdx
else
anyRangeMAux a a.size (Nat.leRefl _) p beginIdx
@[inline] def allRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool := do
b ← anyRangeM a beginIdx endIdx (fun v => do b ← p v; pure b); pure (!b)
end
@[inline] def any (a : Array α) (p : α → Bool) : Bool :=
Id.run $ anyM a p
@[inline] def anyRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool :=
Id.run $ anyRangeM a beginIdx endIdx p
@[inline] def anyFrom (a : Array α) (beginIdx : Nat) (p : α → Bool) : Bool :=
Id.run $ anyRangeM a beginIdx a.size p
@[inline] def all (a : Array α) (p : α → Bool) : Bool :=
!any a (fun v => !p v)
@[inline] def allRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool :=
!anyRange a beginIdx endIdx (fun v => !p v)
section
variables {m : Type v → Type w} [Monad m]
variable {β : Type v}
@[specialize] private def iterateRevMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : ∀ (i : Nat), i ≤ a.size → β → m β
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := ⟨j, h⟩;
b ← f i (a.get i) b;
iterateRevMAux j (Nat.leOfLt h) b
@[inline] def iterateRevM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β :=
iterateRevMAux a f a.size (Nat.leRefl _) b
@[inline] def foldrM (f : α → β → m β) (init : β) (a : Array α) : m β :=
iterateRevM a init (fun _ => f)
@[specialize] private def foldrRangeMAux (a : Array α) (f : α → β → m β) (beginIdx : Nat) : ∀ (i : Nat), i ≤ a.size → β → m β
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := ⟨j, h⟩;
b ← f (a.get i) b;
if j == beginIdx then pure b else foldrRangeMAux j (Nat.leOfLt h) b
@[inline] def foldrRangeM (beginIdx endIdx : Nat) (f : α → β → m β) (ini : β) (a : Array α) : m β :=
if h : endIdx ≤ a.size then
foldrRangeMAux a f beginIdx endIdx h ini
else
foldrRangeMAux a f beginIdx a.size (Nat.leRefl _) ini
@[specialize] partial def foldlStepMAux (step : Nat) (a : Array α) (f : β → α → m β) : Nat → β → m β
| i, b =>
if h : i < a.size then do
let curr := a.get ⟨i, h⟩;
b ← f b curr;
foldlStepMAux (i+step) b
else
pure b
@[inline] def foldlStepM (f : β → α → m β) (init : β) (step : Nat) (a : Array α) : m β :=
foldlStepMAux step a f 0 init
end
@[inline] def iterateRev {β} (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateRevM a b f
@[inline] def foldr {β} (f : α → β → β) (init : β) (a : Array α) : β :=
Id.run $ foldrM f init a
@[inline] def foldrRange {β} (beginIdx endIdx : Nat) (f : α → β → β) (init : β) (a : Array α) : β :=
Id.run $ foldrRangeM beginIdx endIdx f init a
@[inline] def foldlStep {β} (f : β → α → β) (init : β) (step : Nat) (a : Array α) : β :=
Id.run $ foldlStepM f init step a
@[inline] def getEvenElems (a : Array α) : Array α :=
a.foldlStep (fun r a => Array.push r a) empty 2
def toList (a : Array α) : List α :=
a.foldr List.cons []
instance [HasRepr α] : HasRepr (Array α) :=
⟨fun a => "#" ++ repr a.toList⟩
instance [HasToString α] : HasToString (Array α) :=
⟨fun a => "#" ++ toString a.toList⟩
section
variables {m : Type v → Type w} [Monad m]
variable {β : Type v}
@[specialize] unsafe partial def umapMAux (f : Nat → α → m β) : Nat → Array NonScalar → m (Array PNonScalar.{v})
| i, a =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let v : NonScalar := a.get idx;
let a := a.set idx (arbitrary _);
do newV ← f i (unsafeCast v); umapMAux (i+1) (a.set idx (unsafeCast newV))
else
pure (unsafeCast a)
@[inline] unsafe partial def umapM (f : α → m β) (as : Array α) : m (Array β) :=
@unsafeCast (m (Array PNonScalar.{v})) (m (Array β)) $ umapMAux (fun i a => f a) 0 (unsafeCast as)
@[inline] unsafe partial def umapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) :=
@unsafeCast (m (Array PNonScalar.{v})) (m (Array β)) $ umapMAux f 0 (unsafeCast as)
@[implementedBy Array.umapM] def mapM (f : α → m β) (as : Array α) : m (Array β) :=
as.foldlM (fun bs a => do b ← f a; pure (bs.push b)) (mkEmpty as.size)
@[implementedBy Array.umapIdxM] def mapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) :=
as.iterateM (mkEmpty as.size) (fun i a bs => do b ← f i.val a; pure (bs.push b))
end
section
variables {m : Type u → Type v} [Monad m]
@[inline] def modifyM [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) :=
if h : i < a.size then do
let idx : Fin a.size := ⟨i, h⟩;
let v := a.get idx;
let a := a.set idx (arbitrary α);
v ← f v;
pure $ (a.set idx v)
else
pure a
end
section
variable {β : Type v}
@[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α :=
Id.run $ a.modifyM i f
@[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α :=
self.modify idx f
@[inline] def mapIdx (f : Nat → α → β) (a : Array α) : Array β :=
Id.run $ mapIdxM f a
@[inline] def map (f : α → β) (as : Array α) : Array β :=
Id.run $ mapM f as
end
section
variables {m : Type v → Type w} [Monad m]
variable {β : Type v}
@[specialize]
partial def forMAux (f : α → m PUnit) (a : Array α) : Nat → m PUnit
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let v : α := a.get idx;
do f v; forMAux (i+1)
else
pure ⟨⟩
@[inline] def forM (f : α → m PUnit) (a : Array α) : m PUnit :=
a.forMAux f 0
@[specialize]
partial def forRevMAux (f : α → m PUnit) (a : Array α) : forall (i : Nat), i ≤ a.size → m PUnit
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v : α := a.get ⟨i-1, this⟩;
have i - 1 ≤ a.size from Nat.leOfLt this;
do f v; forRevMAux (i-1) this
else
pure ⟨⟩
@[inline] def forRevM (f : α → m PUnit) (a : Array α) : m PUnit :=
a.forRevMAux f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
partial def extractAux (a : Array α) : Nat → ∀ (e : Nat), e ≤ a.size → Array α → Array α
| i, e, hle, r =>
if hlt : i < e then
let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe hlt hle⟩;
extractAux (i+1) e hle (r.push (a.get idx))
else r
def extract (a : Array α) (b e : Nat) : Array α :=
let r : Array α := mkEmpty (e - b);
if h : e ≤ a.size then extractAux a b e h r
else r
protected def append (a : Array α) (b : Array α) : Array α :=
b.foldl (fun a v => a.push v) a
instance : HasAppend (Array α) := ⟨Array.append⟩
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) : Nat → Bool
| i =>
if h : i < a.size then
let aidx : Fin a.size := ⟨i, h⟩;
let bidx : Fin b.size := ⟨i, hsz ▸ h⟩;
match p (a.get aidx) (b.get bidx) with
| true => isEqvAux (i+1)
| false => false
else
true
@[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool :=
if h : a.size = b.size then
isEqvAux a b h p 0
else
false
instance [HasBeq α] : HasBeq (Array α) :=
⟨fun a b => isEqv a b HasBeq.beq⟩
-- TODO(Leo): justify termination using wf-rec, and use `swap`
partial def reverseAux : Array α → Nat → Array α
| a, i =>
let n := a.size;
if i < n / 2 then
reverseAux (a.swap! i (n - i - 1)) (i+1)
else
a
def reverse (a : Array α) : Array α :=
reverseAux a 0
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def filterAux (p : α → Bool) : Array α → Nat → Nat → Array α
| a, i, j =>
if h₁ : i < a.size then
if p (a.get ⟨i, h₁⟩) then
if h₂ : j < i then
filterAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1)
else
filterAux a (i+1) (j+1)
else
filterAux a (i+1) j
else
a.shrink j
@[inline] def filter (p : α → Bool) (as : Array α) : Array α :=
filterAux p as 0 0
@[specialize] partial def filterMAux {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) : Array α → Nat → Nat → m (Array α)
| a, i, j =>
if h₁ : i < a.size then
condM (p (a.get ⟨i, h₁⟩))
(if h₂ : j < i then
filterMAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1)
else
filterMAux a (i+1) (j+1))
(filterMAux a (i+1) j)
else
pure $ a.shrink j
@[inline] def filterM {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) (as : Array α) : m (Array α) :=
filterMAux p as 0 0
partial def indexOfAux {α} [HasBeq α] (a : Array α) (v : α) : Nat → Option (Fin a.size)
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
if a.get idx == v then some idx
else indexOfAux (i+1)
else none
def indexOf {α} [HasBeq α] (a : Array α) (v : α) : Option (Fin a.size) :=
indexOfAux a v 0
partial def eraseIdxAux {α} : Nat → Array α → Array α
| i, a =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let idx1 : Fin a.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩;
eraseIdxAux (i+1) (a.swap idx idx1)
else
a.pop
def feraseIdx {α} (a : Array α) (i : Fin a.size) : Array α :=
eraseIdxAux (i.val + 1) a
def eraseIdx {α} (a : Array α) (i : Nat) : Array α :=
if i < a.size then eraseIdxAux (i+1) a else a
theorem szFSwapEq (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size :=
rfl
theorem szPopEq (a : Array α) : a.pop.size = a.size - 1 :=
rfl
section
/- Instance for justifying `partial` declaration.
We should be able to delete it as soon as we restore support for well-founded recursion. -/
instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } :=
⟨⟨a.pop, szPopEq a⟩⟩
partial def eraseIdxSzAux {α} (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 }
| i, r, heq =>
if h : i < r.size then
let idx : Fin r.size := ⟨i, h⟩;
let idx1 : Fin r.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩;
eraseIdxSzAux (i+1) (r.swap idx idx1) ((szFSwapEq r idx idx1).trans heq)
else
⟨r.pop, (szPopEq r).trans (heq ▸ rfl)⟩
end
def eraseIdx' {α} (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } :=
eraseIdxSzAux a (i.val + 1) a rfl
def contains [HasBeq α] (as : Array α) (a : α) : Bool :=
as.any $ fun b => a == b
def elem [HasBeq α] (a : α) (as : Array α) : Bool :=
as.contains a
partial def insertAtAux {α} (i : Nat) : Array α → Nat → Array α
| as, j =>
if i == j then as
else
let as := as.swap! (j-1) j;
insertAtAux as (j-1)
/--
Insert element `a` at position `i`.
Pre: `i < as.size` -/
def insertAt {α} (as : Array α) (i : Nat) (a : α) : Array α :=
if i > as.size then panic! "invalid index"
else
let as := as.push a;
as.insertAtAux i as.size
theorem ext {α : Type u} (a b : Array α) : a.size = b.size → (∀ (i : Nat) (hi₁ : i < a.size) (hi₂ : i < b.size) , a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) → a = b :=
match a, b with
| ⟨sz₁, f₁⟩, ⟨sz₂, f₂⟩ =>
show sz₁ = sz₂ → (∀ (i : Nat) (hi₁ : i < sz₁) (hi₂ : i < sz₂) , f₁ ⟨i, hi₁⟩ = f₂ ⟨i, hi₂⟩) → Array.mk sz₁ f₁ = Array.mk sz₂ f₂ from
fun h₁ h₂ =>
match sz₁, sz₂, f₁, f₂, h₁, h₂ with
| sz, _, f₁, f₂, rfl, h₂ =>
have f₁ = f₂ from funext $ fun ⟨i, hi₁⟩ => h₂ i hi₁ hi₁;
congrArg _ this
theorem extLit {α : Type u} {n : Nat}
(a b : Array α)
(hsz₁ : a.size = n) (hsz₂ : b.size = n)
(h : ∀ (i : Nat) (hi : i < n), a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b :=
Array.ext a b (hsz₁.trans hsz₂.symm) $ fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁)
end Array
export Array (mkArray)
@[inlineIfReduce] def List.toArrayAux {α : Type u} : List α → Array α → Array α
| [], r => r
| a::as, r => List.toArrayAux as (r.push a)
@[inlineIfReduce] def List.redLength {α : Type u} : List α → Nat
| [] => 0
| _::as => as.redLength + 1
@[inline] def List.toArray {α : Type u} (as : List α) : Array α :=
as.toArrayAux (Array.mkEmpty as.redLength)
|
809e0949723a8c44058dd51b4accaececa62ca46 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/nat/enat.lean | 958b4737bb7568b01375ff86f7af7123a8c9268c | [
"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 | 18,816 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.pfun
import tactic.norm_num
import data.equiv.mul_add
/-!
# Natural numbers with infinity
The natural numbers and an extra `top` element `⊤`.
## Main definitions
The following instances are defined:
* `ordered_add_comm_monoid enat`
* `canonically_ordered_add_monoid enat`
There is no additive analogue of `monoid_with_zero`; if there were then `enat` could
be an `add_monoid_with_top`.
* `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well
with `+` and `≤`.
* `with_top_add_equiv : enat ≃+ with_top ℕ`
* `with_top_order_iso : enat ≃o with_top ℕ`
## Implementation details
`enat` is defined to be `roption ℕ`.
`+` and `≤` are defined on `enat`, but there is an issue with `*` because it's not
clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous
so there is no `-` defined on `enat`.
Before the `open_locale classical` line, various proofs are made with decidability assumptions.
This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`,
followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`.
## Tags
enat, with_top ℕ
-/
open roption
/-- Type of natural numbers with infinity (`⊤`) -/
def enat : Type := roption ℕ
namespace enat
instance : has_zero enat := ⟨some 0⟩
instance : inhabited enat := ⟨0⟩
instance : has_one enat := ⟨some 1⟩
instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩
instance : has_coe ℕ enat := ⟨some⟩
instance (n : ℕ) : decidable (n : enat).dom := is_true trivial
@[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := roption.some_inj
@[simp] lemma dom_coe (x : ℕ) : (x : enat).dom := trivial
instance : add_comm_monoid enat :=
{ add := (+),
zero := (0),
add_comm := λ x y, roption.ext' and.comm (λ _ _, add_comm _ _),
zero_add := λ x, roption.ext' (true_and _) (λ _ _, zero_add _),
add_zero := λ x, roption.ext' (and_true _) (λ _ _, add_zero _),
add_assoc := λ x y z, roption.ext' and.assoc (λ _ _, add_assoc _ _ _) }
instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩
instance : has_top enat := ⟨none⟩
instance : has_bot enat := ⟨0⟩
instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩
lemma le_def (x y : enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy :=
iff.rfl
@[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat,
P ⊤ → (∀ n : ℕ, P n) → P a :=
roption.induction_on
@[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ :=
roption.ext' (false_and _) (λ h, h.left.elim)
@[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ :=
by rw [add_comm, top_add]
@[simp, norm_cast] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl
@[simp, norm_cast] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y :=
roption.ext' (and_true _).symm (λ _ _, rfl)
lemma get_coe {x : ℕ} : get (x : enat) true.intro = x := rfl
@[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : enat).dom) : get (x : enat) h = x := rfl
lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) :
get ((x : enat) + y) h = x + get y h.2 := rfl
@[simp] lemma get_add {x y : enat} (h : (x + y).dom) :
get (x + y) h = x.get h.1 + y.get h.2 := rfl
@[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x :=
roption.ext' (iff_of_true trivial h) (λ _ _, rfl)
@[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl
@[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl
lemma dom_of_le_of_dom {x y : enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h
lemma dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ y) : x.dom := dom_of_le_of_dom h trivial
instance decidable_le (x y : enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) :=
if hx : x.dom
then decidable_of_decidable_of_iff
(show decidable (∀ (hy : (y : enat).dom), x.get hx ≤ (y : enat).get hy),
from forall_prop_decidable _) $
by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] }
else if hy : y.dom
then is_false $ λ h, hx $ dom_of_le_of_dom h hy
else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩
/-- The coercion `ℕ → enat` preserves `0` and addition. -/
def coe_hom : ℕ →+ enat := ⟨coe, enat.coe_zero, enat.coe_add⟩
instance : partial_order enat :=
{ le := (≤),
le_refl := λ x, ⟨id, λ _, le_refl _⟩,
le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩,
⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩,
le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, roption.ext' ⟨hyx₁, hxy₁⟩
(λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) }
lemma lt_def (x y : enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy :=
begin
rw [lt_iff_le_not_le, le_def, le_def, not_exists],
split,
{ rintro ⟨⟨hyx, H⟩, h⟩,
by_cases hx : x.dom,
{ use hx, intro hy,
specialize H hy, specialize h (λ _, hy),
rw not_forall at h, cases h with hx' h,
rw not_le at h, exact h },
{ specialize h (λ hx', (hx hx').elim),
rw not_forall at h, cases h with hx' h,
exact (hx hx').elim } },
{ rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ }
end
@[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y :=
⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩
@[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y :=
by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe]
@[simp] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} :
x.get hx ≤ y.get hy ↔ x ≤ y :=
by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]}
lemma le_coe_iff (x : enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n :=
begin
show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n,
simp only [forall_prop_of_true, dom_coe, get_coe'],
split; rintro ⟨_, _⟩; refine ⟨_, _⟩; intros; try { assumption }
end
lemma lt_coe_iff (x : enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n :=
by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe]
lemma coe_le_iff (n : ℕ) (x : enat) : (n : enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h :=
by simpa only [le_def, exists_prop_of_true, dom_coe, forall_true_iff] using iff.rfl
lemma coe_lt_iff (n : ℕ) (x : enat) : (n : enat) < x ↔ ∀ h : x.dom, n < x.get h :=
by simpa only [lt_def, exists_prop_of_true, dom_coe] using iff.rfl
protected lemma zero_lt_one : (0 : enat) < 1 :=
by { norm_cast, norm_num }
instance semilattice_sup_bot : semilattice_sup_bot enat :=
{ sup := (⊔),
bot := (⊥),
bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩,
le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩,
le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩,
sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩,
λ _, sup_le (hx₂ _) (hy₂ _)⟩,
..enat.partial_order }
instance order_top : order_top enat :=
{ top := (⊤),
le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩,
..enat.semilattice_sup_bot }
lemma dom_of_lt {x y : enat} : x < y → x.dom :=
enat.cases_on x not_top_lt $ λ _ _, trivial
lemma top_eq_none : (⊤ : enat) = none := rfl
@[simp] lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ :=
lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false)
@[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x)
lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃(n : ℕ), x = n := roption.ne_none_iff
lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom :=
by classical; exact not_iff_comm.1 roption.eq_none_iff'.symm
lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ :=
ne_of_lt $ lt_of_lt_of_le h le_top
lemma eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) < x :=
begin
split,
{ rintro rfl n, exact coe_lt_top _ },
{ contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ }
end
lemma eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) ≤ x :=
(eq_top_iff_forall_lt x).trans
⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩
lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x :=
enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩
(λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h),
λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩)
noncomputable instance : linear_order enat :=
{ le_total := λ x y, enat.cases_on x
(or.inr le_top) (enat.cases_on y (λ _, or.inl le_top)
(λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2)
(or.inl ∘ coe_le_coe.2))),
decidable_le := classical.dec_rel _,
..enat.partial_order }
noncomputable instance : bounded_lattice enat :=
{ inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := λ _ _ _, le_min,
..enat.order_top,
..enat.semilattice_sup_bot }
lemma sup_eq_max {a b : enat} : a ⊔ b = max a b :=
le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _))
(max_le le_sup_left le_sup_right)
lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl
instance : ordered_add_comm_monoid enat :=
{ add_le_add_left := λ a b ⟨h₁, h₂⟩ c,
enat.cases_on c (by simp)
(λ c, ⟨λ h, and.intro trivial (h₁ h.2),
λ _, add_le_add_left (h₂ _) c⟩),
lt_of_add_lt_add_left := λ a b c, enat.cases_on a
(λ h, by simpa [lt_irrefl] using h)
(λ a, enat.cases_on b
(λ h, absurd h (not_lt_of_ge (by rw add_top; exact le_top)))
(λ b, enat.cases_on c
(λ _, coe_lt_top _)
(λ c h, coe_lt_coe.2 (by rw [← coe_add, ← coe_add, coe_lt_coe] at h;
exact lt_of_add_lt_add_left h)))),
..enat.linear_order,
..enat.add_comm_monoid }
instance : canonically_ordered_add_monoid enat :=
{ le_iff_exists_add := λ a b, enat.cases_on b
(iff_of_true le_top ⟨⊤, (add_top _).symm⟩)
(λ b, enat.cases_on a
(iff_of_false (not_le_of_gt (coe_lt_top _))
(not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _))))
(λ a, ⟨λ h, ⟨(b - a : ℕ),
by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩,
(λ ⟨c, hc⟩, enat.cases_on c
(λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top)
(λ c (hc : (b : enat) = a + c),
coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc;
rw hc; exact nat.le_add_right _ _)) hc)⟩)),
..enat.semilattice_sup_bot,
..enat.ordered_add_comm_monoid }
protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z :=
begin
rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩,
rcases ne_top_iff.mp hz with ⟨k, rfl⟩,
induction y using enat.cases_on with n,
{ rw [top_add], apply_mod_cast coe_lt_top },
norm_cast at h, apply_mod_cast add_lt_add_right h
end
protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y :=
⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩
protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y :=
by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz]
protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y :=
by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] }
lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 :=
by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num }
lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y :=
begin
induction y using enat.cases_on with n, apply le_top,
rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩,
apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h
end
lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y :=
begin
induction y using enat.cases_on with n, apply le_top,
rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩,
apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h
end
lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y :=
begin
split, swap, exact add_one_le_of_lt,
intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩,
induction y using enat.cases_on with n, apply coe_lt_top,
apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h
end
lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y :=
begin
split, exact le_of_lt_add_one,
intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩,
induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top },
apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h
end
lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ :=
by apply enat.cases_on a; apply enat.cases_on b;
simp; simp only [(enat.coe_add _ _).symm, enat.coe_ne_top]; simp
protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b :=
begin
rcases ne_top_iff.1 hc with ⟨c, rfl⟩,
apply enat.cases_on a; apply enat.cases_on b;
simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)];
simp only [(enat.coe_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm];
tauto
end
protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c :=
by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha]
section with_top
/-- Computably converts an `enat` to a `with_top ℕ`. -/
def to_with_top (x : enat) [decidable x.dom] : with_top ℕ := x.to_option
lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl
@[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ :=
by convert to_with_top_top
lemma to_with_top_zero : to_with_top 0 = 0 := rfl
@[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom} : to_with_top 0 = 0 :=
by convert to_with_top_zero
lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl
@[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} :
to_with_top (n : enat) = n :=
by convert to_with_top_coe n
@[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom]
[decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y :=
enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp))
@[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] :
to_with_top x < to_with_top y ↔ x < y :=
lt_iff_lt_of_le_iff_le to_with_top_le
end with_top
section with_top_equiv
open_locale classical
@[simp] lemma to_with_top_add {x y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y :=
begin
apply enat.cases_on y; apply enat.cases_on x,
{ simp },
{ simp },
{ simp },
-- not sure why `simp` can't do this
{ intros, rw [to_with_top_coe', to_with_top_coe'], norm_cast, exact to_with_top_coe' _ }
end
/-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/
noncomputable def with_top_equiv : enat ≃ with_top ℕ :=
{ to_fun := λ x, to_with_top x,
inv_fun := λ x, match x with (some n) := coe n | none := ⊤ end,
left_inv := λ x, by apply enat.cases_on x; intros; simp; refl,
right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl }
@[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ :=
to_with_top_top'
@[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n :=
to_with_top_coe' _
@[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 :=
with_top_equiv_coe _
@[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y :=
to_with_top_le
@[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y :=
to_with_top_lt
/-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/
noncomputable def with_top_order_iso : enat ≃o with_top ℕ :=
{ map_rel_iff' := λ _ _, with_top_equiv_le,
.. with_top_equiv}
@[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ :=
rfl
@[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n :=
rfl
@[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 :=
rfl
@[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} :
with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y :=
by rw ← with_top_equiv_le; simp
@[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} :
with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y :=
by rw ← with_top_equiv_lt; simp
/-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/
noncomputable def with_top_add_equiv : enat ≃+ with_top ℕ :=
{ map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add,
..with_top_equiv}
end with_top_equiv
lemma lt_wf : well_founded ((<) : enat → enat → Prop) :=
show well_founded (λ a b : enat, a < b),
by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff};
exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf)
instance : has_well_founded enat := ⟨(<), lt_wf⟩
section find
variables (P : ℕ → Prop) [decidable_pred P]
/-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/
def find : enat := ⟨∃ n, P n, nat.find⟩
@[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl
lemma find_dom (h : ∃ n, P n) : (find P).dom := h
lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : enat) < find P :=
begin
rw coe_lt_iff, intro h', rw find_get,
have := @nat.find_spec P _ h',
contrapose! this,
exact h _ this
end
lemma lt_find_iff (n : ℕ) : (n : enat) < find P ↔ (∀ m ≤ n, ¬P m) :=
begin
refine ⟨_, lt_find P n⟩,
intros h m hm,
by_cases H : (find P).dom,
{ apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h },
{ exact not_exists.mp H m }
end
lemma find_le (n : ℕ) (h : P n) : find P ≤ n :=
by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ }
lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n :=
(eq_top_iff_forall_lt _).trans
⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩
end find
noncomputable instance : linear_ordered_add_comm_monoid_with_top enat :=
{ top_add' := top_add,
.. enat.linear_order,
.. enat.ordered_add_comm_monoid,
.. enat.order_top }
end enat
|
b425fdbf29efa7dba63f2521db939d90bdceb9c2 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/topology/basic.lean | a5198c676840ce5829513ba5163a8f2bf4e1dada | [
"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 | 44,265 | 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, Jeremy Avigad
-/
import order.filter.ultrafilter
import order.filter.partial
import order.filter.bases
/-!
# Basic theory of topological spaces.
The main definition is the type class `topological space α` which endows a type `α` with a topology.
Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and
`frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has
`x` as a cluster point if `is_cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x`
along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular
the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`.
This file also defines locally finite families of subsets of `α`.
For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`,
`continuous_at f a` means `f` is continuous at `a`, and global continuity is
`continuous f`. There is also a version of continuity `pcontinuous` for
partially defined functions.
## Implementation notes
Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in
<https://leanprover-community.github.io/theories/topology.html>.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
## Tags
topological space, interior, closure, frontier, neighborhood, continuity, continuous function
-/
open set filter classical
open_locale classical filter
universes u v w
/-!
### Topological spaces
-/
/-- A topology on `α`. -/
@[protect_proj] structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
/-- A constructor for topologies by specifying the closed sets,
and showing that they satisfy the appropriate conditions. -/
def topological_space.of_closed {α : Type u} (T : set (set α))
(empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) :
topological_space α :=
{ is_open := λ X, Xᶜ ∈ T,
is_open_univ := by simp [empty_mem],
is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht,
is_open_sUnion := λ s hs,
by rw set.compl_sUnion; exact sInter_mem (set.compl '' s)
(λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) }
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
@[ext]
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $
λ a s has hs ih h, by rw sInter_insert; exact
is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _)
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bInter_empty; exact is_open_univ)
(λ a s has hs ih h, by rw bInter_insert; exact
is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_Inter [fintype β] {s : β → set α}
(h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) :=
suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa,
is_open_bInter finite_univ (λ i _, h i)
lemma is_open_Inter_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_open (s h)) : is_open (Inter s) :=
by by_cases p; simp *
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : ¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set α) : Prop := is_open sᶜ
@[simp] lemma is_closed_empty : is_closed (∅ : set α) :=
by unfold is_closed; rw compl_empty; exact is_open_univ
@[simp] lemma is_closed_univ : is_closed (univ : set α) :=
by unfold is_closed; rw compl_univ; exact is_open_empty
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i
@[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open_inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂
lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bUnion_empty; exact is_closed_empty)
(λ a s has hs ih h, by rw bUnion_insert; exact
is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_Union [fintype β] {s : β → set α}
(h : ∀ i, is_closed (s i)) : is_closed (Union s) :=
suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i),
by convert this; simp [set.ext_iff],
is_closed_bUnion finite_univ (λ i _, h i)
lemma is_closed_Union_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_closed (s h)) : is_closed (Union s) :=
by by_cases p; simp *
lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-!
### Interior of a set
-/
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior)
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁),
have u \ s ⊆ ∅,
by rwa h₂ at this,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior]
/-!
### Closure of a set
-/
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s :=
closure_minimal (subset.refl _) hs
lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) :=
λ _ _, closure_mono
lemma closure_inter_subset_inter_closure (s t : set α) :
closure (s ∩ t) ⊆ closure s ∩ closure t :=
(monotone_closure α).map_inf_le s t
lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact is_closed_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩
lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s :=
⟨is_closed_of_closure_subset, is_closed.closure_subset⟩
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
is_closed_empty.closure_eq
@[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩
lemma set.nonempty.closure {s : set α} (h : s.nonempty) :
set.nonempty (closure s) :=
let ⟨x, hx⟩ := h in ⟨x, subset_closure hx⟩
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
is_closed_univ.closure_eq
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
is_closed_closure.closure_eq
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure)
((monotone_closure α).le_map_sup s t)
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ :=
begin
unfold interior closure is_closed,
rw [compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl]
end
@[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty :=
⟨λ h o oo ao, classical.by_contradiction $ λ os,
have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := (H _ h₁ nc) in hc (h₂ hs)⟩
lemma dense_iff_inter_open {s : set α} :
closure s = univ ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty :=
begin
split ; intro h,
{ rintros U U_op ⟨x, x_in⟩,
exact mem_closure_iff.1 (by simp only [h]) U U_op x_in },
{ apply eq_univ_of_forall, intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op ⟨_, x_in⟩ },
end
lemma dense_of_subset_dense {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : closure s₁ = univ) :
closure s₂ = univ :=
by { rw [← univ_subset_iff, ← hd], exact closure_mono h }
/-!
### Frontier of a set
-/
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure sᶜ :=
by rw [closure_compl, frontier, diff_eq]
/-- The complement of a set has the same frontier as the original set. -/
@[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s :=
by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm]
lemma frontier_inter_subset (s t : set α) :
frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) :=
begin
simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union],
convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t),
simp only [inter_distrib_left, inter_distrib_right, inter_assoc],
congr' 2,
apply inter_comm
end
lemma frontier_union_subset (s t : set α) :
frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) :=
by simpa only [frontier_compl, ← compl_union]
using frontier_inter_subset sᶜ tᶜ
lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s :=
by rw [frontier, hs.closure_eq]
lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s :=
by rw [frontier, interior_eq_of_open hs]
/-- The frontier of a set is closed. -/
lemma is_closed_frontier {s : set α} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure
/-- The frontier of a closed set has no interior point. -/
lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ :=
begin
have A : frontier s = s \ interior s, from h.frontier_eq,
have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) ⊆ frontier s := interior_subset,
have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
/-!
### Neighborhoods
-/
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s)
localized "notation `𝓝` := nhds" in topological_space
lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := rfl
lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) :=
has_basis_binfi_principal
(λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open_inter hs ht⟩,
⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩)
⟨univ, ⟨mem_univ a, is_open_univ⟩⟩
lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f :=
by simp [nhds_def]
lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f :=
by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf)
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
(nhds_basis_opens a).mem_iff.trans
⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩
lemma eventually_nhds_iff {a : α} {p : α → Prop} :
(∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t :=
mem_nhds_sets_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq]
lemma map_nhds {a : α} {f : α → β} :
map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) :=
((nhds_basis_opens a).map f).eq_binfi
attribute [irreducible] nhds
lemma mem_of_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s :=
λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs
lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α}
(h : ∀ᶠ y in 𝓝 a, p y) : p a :=
mem_of_nhds h
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ 𝓝 a :=
mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩
lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) :=
begin
convert nhds_basis_opens a,
ext s,
split,
{ rintros ⟨s_in, s_op⟩,
exact ⟨mem_of_nhds s_in, s_op⟩ },
{ rintros ⟨a_in, s_op⟩,
exact ⟨mem_nhds_sets s_op a_in, s_op⟩ },
end
/-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close
to `a` this predicate is true in a neighbourhood of `y`. -/
lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) :
∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x :=
let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in
eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩
@[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x :=
⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩
@[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds
@[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g :=
eventually_eventually_nhds
lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a :=
let ⟨u, hu, H⟩ := h.exists_mem in H _ (mem_of_nhds hu)
@[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g :=
eventually_eventually_nhds
/-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close
to `a` these functions are equal in a neighbourhood of `y`. -/
lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g :=
h.eventually_nhds
/-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have
`f x ≤ g x` in a neighbourhood of `y`. -/
lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g :=
h.eventually_nhds
theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) :
(∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) :=
((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp]
theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t)
(l : filter β) :
(∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) :=
all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t, id) _
theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} :
tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha
lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) :=
assume a s hs, mem_pure_sets.2 $ mem_of_nhds hs
lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (𝓝 (f a)) :=
tendsto_le_right (pure_le_nhds _) (tendsto_pure_pure f a)
lemma order_top.tendsto_at_top {α : Type*} [order_top α] [topological_space β] (f : α → β) :
tendsto f at_top (𝓝 $ f ⊤) :=
tendsto_le_right (pure_le_nhds _) $ tendsto_at_top_pure f
@[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) :=
ne_bot_of_le (pure_le_nhds a)
/-!
### Cluster points
In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point)
(also known as limit points and accumulation points) of a filter and of a sequence.
-/
/-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as
an accumulation point or a limit point. -/
def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F)
lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h
lemma cluster_pt_iff {x : α} {F : filter α} :
cluster_pt x F ↔ ∀ {U V : set α}, U ∈ 𝓝 x → V ∈ F → (U ∩ V).nonempty :=
inf_ne_bot_iff
/-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty
set. -/
lemma cluster_pt_principal_iff {x : α} {s : set α} :
cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty :=
inf_principal_ne_bot_iff
lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f :=
by rwa [cluster_pt, inf_eq_right.mpr H]
lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) :
cluster_pt x f :=
cluster_pt.of_le_nhds H
lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f :=
by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot]
lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) :
cluster_pt x g :=
ne_bot_of_le_ne_bot H $ inf_le_inf_left _ h
lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x f :=
H.mono inf_le_left
lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x g :=
H.mono inf_le_right
/-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point
of `map u F`. -/
def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F)
lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) :
map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s :=
by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl }
lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ}
{x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) :
map_cluster_pt x F u :=
begin
have := calc
map (u ∘ φ) p = map u (map φ p) : map_map
... ≤ map u F : map_mono h,
have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F,
from le_inf H this,
exact ne_bot_of_le this
end
/-!
### Interior, closure and frontier in terms of neighborhoods
-/
lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} :=
set.ext $ λ x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ 𝓝 a :=
by simp only [interior_eq_nhds, le_principal_iff]; refl
lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x :=
show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm
... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} :=
calc closure s = (interior sᶜ)ᶜ : closure_eq_compl_interior_compl
... = {a | ¬ 𝓝 a ≤ 𝓟 sᶜ} : by rw [interior_eq_nhds]; refl
... = {a | cluster_pt a (𝓟 s)} : set.ext $ assume a, not_congr
(is_compl_principal s).inf_left_eq_bot_iff.symm
theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) :=
by simp only [closure_eq_cluster_pts, mem_set_of_eq]
theorem mem_closure_iff_nhds {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty :=
mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff
theorem mem_closure_iff_nhds' {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t :=
by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right]
theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} :
x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) :=
by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right]
theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s)
{t : set α} :
a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i :=
mem_closure_iff_nhds.trans
⟨λ H i hi, let ⟨x, hx⟩ := (H _ $ h.mem_of_mem hi) in ⟨x, hx.2, hx.1⟩,
λ H t' ht', let ⟨i, hi, hit⟩ := h.mem_iff.1 ht', ⟨x, xt, hx⟩ := H i hi in
⟨x, hit hx, xt⟩⟩
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set α} {x : α} :
x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u.val ∧ u.val ≤ 𝓝 x :=
begin
rw closure_eq_cluster_pts, change cluster_pt x (𝓟 s) ↔ _, symmetry,
convert exists_ultrafilter_iff _, ext u,
rw [←le_principal_iff, inf_comm, le_inf_iff]
end
lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s :=
calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm
... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt]
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
assume a ⟨hs, ht⟩,
have s ∈ 𝓝 a, from mem_nhds_sets h hs,
have 𝓝 a ⊓ 𝓟 s = 𝓝 a, by rwa [inf_eq_left, le_principal_iff],
have cluster_pt a (𝓟 (s ∩ t)),
from calc 𝓝 a ⊓ 𝓟 (s ∩ t) = 𝓝 a ⊓ (𝓟 s ⊓ 𝓟 t) : by rw inf_principal
... = 𝓝 a ⊓ 𝓟 t : by rw [←inf_assoc, this]
... ≠ ⊥ : by rw [closure_eq_cluster_pts] at ht; assumption,
by rwa [closure_eq_cluster_pts]
lemma dense_inter_of_open_left {s t : set α} (hs : closure s = univ) (ht : closure t = univ)
(hso : is_open s) :
closure (s ∩ t) = univ :=
eq_univ_of_subset (closure_minimal (closure_inter_open hso) is_closed_closure) $
by simp only [*, inter_univ]
lemma dense_inter_of_open_right {s t : set α} (hs : closure s = univ) (ht : closure t = univ)
(hto : is_open t) :
closure (s ∩ t) = univ :=
inter_comm t s ▸ dense_inter_of_open_left ht hs hto
lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) :=
calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm]
... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hf : tendsto f b (𝓝 a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b) : a ∈ s :=
is_closed_iff_cluster_pt.mp hs a $ ne_bot_of_le $ le_inf hf (le_principal_iff.mpr h)
lemma mem_of_closed_of_tendsto' {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (𝓝 a)) (hs : is_closed s) [ne_bot (x ⊓ 𝓟 (f ⁻¹' s))] : a ∈ s :=
have tendsto f (x ⊓ 𝓟 (f ⁻¹' s)) (𝓝 a) := tendsto_inf_left hf,
mem_of_closed_of_tendsto this hs $ mem_inf_sets_of_right $ mem_principal_self _
lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s :=
mem_of_closed_of_tendsto hf is_closed_closure $
filter.mem_sets_of_superset h (preimage_mono subset_closure)
/-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter.
Then `f` tends to `a` along `l` restricted to `s` if and only it tends to `a` along `l`. -/
lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β}
{a : α} (h : ∀ x ∉ s, f x = a) :
tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) :=
begin
rw [tendsto_iff_comap, tendsto_iff_comap],
replace h : 𝓟 sᶜ ≤ comap f (𝓝 a),
{ rintros U ⟨t, ht, htU⟩ x hx,
have : f x ∈ t, from (h x hx).symm ▸ mem_of_nhds ht,
exact htU this },
refine ⟨λ h', _, le_trans inf_le_left⟩,
have := sup_le h' h,
rw [sup_inf_right, sup_principal, union_compl_self, principal_univ,
inf_top_eq, sup_le_iff] at this,
exact this.1
end
/-!
### Limits of filters in topological spaces
-/
section lim
/-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/
noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a
/-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`,
if it exists. -/
noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α :=
Lim (f.map g)
/-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate
this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma Lim_spec {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) :=
epsilon_spec h
/-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate
this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma lim_spec {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) :
tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) :=
Lim_spec h
end lim
/-!
### Locally finite families
-/
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty }
lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f :=
assume x, ⟨univ, univ_mem_sets, h.subset $ subset_univ _⟩
lemma locally_finite_subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma is_closed_Union_of_locally_finite {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i),
have ∀i, a ∈ (f i)ᶜ,
from assume i hi, h $ mem_Union.2 ⟨i, hi⟩,
have ∀i, (f i)ᶜ ∈ (𝓝 a),
by simp only [mem_nhds_sets_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, h₂ i, this i⟩,
let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in
calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (𝓝 a) _ _ _ h_fin,
exact assume i h, this i
end
... ≤ 𝓟 (⋃i, f i)ᶜ :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
end topological_space
/-!
### Continuity
-/
section continuous
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
open_locale topological_space
/-- A function between topological spaces is continuous if the preimage
of every open set is open. -/
def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s)
lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) :
is_open (f ⁻¹' s) :=
hf s h
/-- A function between topological spaces is continuous at a point `x₀`
if `f x` tends to `f x₀` when `x` tends to `x₀`. -/
def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x))
lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
h
lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x)
(ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x :=
h ht
lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β}
(hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) :=
interior_maximal (preimage_mono interior_subset) (hf _ is_open_interior)
lemma continuous_id : continuous (id : α → α) :=
assume s h, h
lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) :
continuous (g ∘ f) :=
assume s h, hf _ (hg s h)
lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) :=
nat.rec_on n continuous_id (λ n ihn, ihn.comp h)
lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_at f x) :
continuous_at (g ∘ f) x :=
hg.comp hf
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $
λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, hf _ ht⟩, subset.refl _⟩
lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) :
continuous_at f x :=
h.tendsto x
lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)),
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ 𝓝 (f a),
from λ a ha, mem_nhds_sets hs ha,
show is_open (f ⁻¹' s),
from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds
lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x :=
continuous_const.continuous_at
lemma continuous_at_id {x : α} : continuous_at id x :=
continuous_id.continuous_at
lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) :
continuous_at (f^[n]) x :=
nat.rec_on n continuous_at_id $ λ n ihn,
show continuous_at (f^[n] ∘ f) x,
from continuous_at.comp (hx.symm ▸ ihn) hf
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, hf sᶜ hs,
assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) :
is_closed (f ⁻¹' s) :=
continuous_iff_is_closed.mp hf s h
lemma continuous_at_iff_ultrafilter {f : α → β} (x) : continuous_at f x ↔
∀ g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) :=
tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
/-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g`
are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/
lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)}
(hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λa, @ite (p a) (h a) β (f a) (g a)) :=
continuous_iff_is_closed.mpr $
assume s hs,
have (λa, ite (p a) (f a) (g a)) ⁻¹' s =
(closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s),
from set.ext $ assume a,
classical.by_cases
(assume : a ∈ frontier {a | p a},
have hac : a ∈ closure {a | p a}, from this.left,
have hai : a ∈ closure {a | ¬ p a},
from have a ∈ (interior {a | p a})ᶜ, from this.right, by rwa [←closure_compl] at this,
by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt})
(assume hf : a ∈ (frontier {a | p a})ᶜ,
classical.by_cases
(assume : p a,
have hc : a ∈ closure {a | p a}, from subset_closure this,
have hnc : a ∉ closure {a | ¬ p a},
by show a ∉ closure {a | p a}ᶜ; rw [closure_compl]; simpa [frontier, hc] using hf,
by simp [this, hc, hnc])
(assume : ¬ p a,
have hc : a ∈ closure {a | ¬ p a}, from subset_closure this,
have hnc : a ∉ closure {a | p a},
begin
have hc : a ∈ closure {a | p a}ᶜ, from hc,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf
end,
by simp [this, hc, hnc])),
by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs)
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs)
/- Continuity and partial functions -/
/-- Continuity of a partial function -/
def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom :=
by rw [←pfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : α →. β} :
pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) :=
begin
split,
{ intros h x y h',
simp only [ptendsto'_def, mem_nhds_sets_iff],
rintros s ⟨t, tsubs, opent, yt⟩,
exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩
},
intros hf s os,
rw is_open_iff_nhds,
rintros x ⟨y, ys, fxy⟩ t,
rw [mem_principal_sets],
assume h : f.preimage s ⊆ t,
change t ∈ 𝓝 x,
apply mem_sets_of_superset _ h,
have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x,
{ intros s hs,
have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s ∈ 𝓝 x,
apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩
end
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
have ∀ (a : α), cluster_pt a (𝓟 s) → cluster_pt (f a) (𝓟 (f '' s)),
from assume a ha,
have h₁ : ¬ map f (𝓝 a ⊓ 𝓟 s) = ⊥,
by rwa[map_eq_bot_iff],
have h₂ : map f (𝓝 a ⊓ 𝓟 s) ≤ 𝓝 (f a) ⊓ 𝓟 (f '' s),
from le_inf
(le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a)
(le_trans (map_mono inf_le_right) $ by simp [subset_preimage_image] ),
ne_bot_of_le_ne_bot h₁ h₂,
by simp [image_subset_iff, closure_eq_cluster_pts]; assumption
lemma mem_closure {s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t :=
subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $
(mem_image_of_mem f ha)
end continuous
|
34862e689ee2a16fcbba2dcd831c826f9c910930 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/analysis/calculus/lagrange_multipliers.lean | 19499de7a05f145dc7135084a18527353ea8fc1f | [
"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 | 6,766 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.local_extr
import analysis.calculus.implicit
/-!
# Lagrange multipliers
In this file we formalize the
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) method of solving
conditional extremum problems: if a function `φ` has a local extremum at `x₀` on the set
`f ⁻¹' {f x₀}`, `f x = (f₀ x, ..., fₙ₋₁ x)`, then the differentials of `fₖ` and `φ` are linearly
dependent. First we formulate a geometric version of this theorem which does not rely on the
target space being `ℝⁿ`, then restate it in terms of coordinates.
## TODO
Formalize Karush-Kuhn-Tucker theorem
## Tags
lagrange multiplier, local extremum
-/
open filter set
open_locale topological_space filter big_operators
variables {E F : Type*} [normed_group E] [normed_space ℝ E] [complete_space E]
[normed_group F] [normed_space ℝ F] [complete_space F]
{f : E → F} {φ : E → ℝ} {x₀ : E} {f' : E →L[ℝ] F} {φ' : E →L[ℝ] ℝ}
/-- Lagrange multipliers theorem: if `φ : E → ℝ` has a local extremum on the set `{x | f x = f x₀}`
at `x₀`, both `f : E → F` and `φ` are strictly differentiable at `x₀`, and the codomain of `f` is
a complete space, then the linear map `x ↦ (f' x, φ' x)` is not surjective. -/
lemma is_local_extr_on.range_ne_top_of_has_strict_fderiv_at
(hextr : is_local_extr_on φ {x | f x = f x₀} x₀) (hf' : has_strict_fderiv_at f f' x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
(f'.prod φ').range ≠ ⊤ :=
begin
intro htop,
set fφ := λ x, (f x, φ x),
have A : map φ (𝓝[f ⁻¹' {f x₀}] x₀) = 𝓝 (φ x₀),
{ change map (prod.snd ∘ fφ) (𝓝[fφ ⁻¹' {p | p.1 = f x₀}] x₀) = 𝓝 (φ x₀),
rw [← map_map, nhds_within, map_inf_principal_preimage,
(hf'.prod hφ').map_nhds_eq_of_surj htop],
exact map_snd_nhds_within _ },
exact hextr.not_nhds_le_map A.ge
end
/-- Lagrange multipliers theorem: if `φ : E → ℝ` has a local extremum on the set `{x | f x = f x₀}`
at `x₀`, both `f : E → F` and `φ` are strictly differentiable at `x₀`, and the codomain of `f` is
a complete space, then there exist `Λ : dual ℝ F` and `Λ₀ : ℝ` such that `(Λ, Λ₀) ≠ 0` and
`Λ (f' x) + Λ₀ • φ' x = 0` for all `x`. -/
lemma is_local_extr_on.exists_linear_map_of_has_strict_fderiv_at
(hextr : is_local_extr_on φ {x | f x = f x₀} x₀) (hf' : has_strict_fderiv_at f f' x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
∃ (Λ : module.dual ℝ F) (Λ₀ : ℝ), (Λ, Λ₀) ≠ 0 ∧ ∀ x, Λ (f' x) + Λ₀ • φ' x = 0 :=
begin
rcases submodule.exists_le_ker_of_lt_top _
(lt_top_iff_ne_top.2 $ hextr.range_ne_top_of_has_strict_fderiv_at hf' hφ') with ⟨Λ', h0, hΛ'⟩,
set e : ((F →ₗ[ℝ] ℝ) × ℝ) ≃ₗ[ℝ] (F × ℝ →ₗ[ℝ] ℝ) :=
((linear_equiv.refl ℝ (F →ₗ[ℝ] ℝ)).prod (linear_map.ring_lmap_equiv_self ℝ ℝ ℝ).symm).trans
(linear_map.coprod_equiv ℝ),
rcases e.surjective Λ' with ⟨⟨Λ, Λ₀⟩, rfl⟩,
refine ⟨Λ, Λ₀, e.map_ne_zero_iff.1 h0, λ x, _⟩,
convert linear_map.congr_fun (linear_map.range_le_ker_iff.1 hΛ') x using 1,
-- squeezed `simp [mul_comm]` to speed up elaboration
simp only [linear_map.coprod_equiv_apply, linear_equiv.refl_apply,
linear_map.ring_lmap_equiv_self_symm_apply, linear_map.comp_apply,
continuous_linear_map.coe_coe, continuous_linear_map.prod_apply,
linear_equiv.trans_apply, linear_equiv.prod_apply, linear_map.coprod_apply,
linear_map.smul_right_apply, linear_map.one_apply, smul_eq_mul, mul_comm]
end
/-- Lagrange multipliers theorem. Let `f : ι → E → ℝ` be a finite family of functions.
Suppose that `φ : E → ℝ` has a local extremum on the set `{x | ∀ i, f i x = f i x₀}` at `x₀`.
Suppose that all functions `f i` as well as `φ` are strictly differentiable at `x₀`.
Then the derivatives `f' i : E → L[ℝ] ℝ` and `φ' : E →L[ℝ] ℝ` are linearly dependent:
there exist `Λ : ι → ℝ` and `Λ₀ : ℝ`, `(Λ, Λ₀) ≠ 0`, such that `∑ i, Λ i • f' i + Λ₀ • φ' = 0`.
See also `is_local_extr_on.linear_dependent_of_has_strict_fderiv_at` for a version that
states `¬linear_independent ℝ _` instead of existence of `Λ` and `Λ₀`. -/
lemma is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at {ι : Type*} [fintype ι]
{f : ι → E → ℝ} {f' : ι → E →L[ℝ] ℝ}
(hextr : is_local_extr_on φ {x | ∀ i, f i x = f i x₀} x₀)
(hf' : ∀ i, has_strict_fderiv_at (f i) (f' i) x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
∃ (Λ : ι → ℝ) (Λ₀ : ℝ), (Λ, Λ₀) ≠ 0 ∧ ∑ i, Λ i • f' i + Λ₀ • φ' = 0 :=
begin
letI := classical.dec_eq ι,
replace hextr : is_local_extr_on φ {x | (λ i, f i x) = (λ i, f i x₀)} x₀,
by simpa only [function.funext_iff] using hextr,
rcases hextr.exists_linear_map_of_has_strict_fderiv_at
(has_strict_fderiv_at_pi.2 (λ i, hf' i)) hφ'
with ⟨Λ, Λ₀, h0, hsum⟩,
rcases (linear_equiv.pi_ring ℝ ℝ ι ℝ).symm.surjective Λ with ⟨Λ, rfl⟩,
refine ⟨Λ, Λ₀, _, _⟩,
{ simpa only [ne.def, prod.ext_iff, linear_equiv.map_eq_zero_iff, prod.fst_zero] using h0 },
{ ext x, simpa [mul_comm] using hsum x }
end
/-- Lagrange multipliers theorem. Let `f : ι → E → ℝ` be a finite family of functions.
Suppose that `φ : E → ℝ` has a local extremum on the set `{x | ∀ i, f i x = f i x₀}` at `x₀`.
Suppose that all functions `f i` as well as `φ` are strictly differentiable at `x₀`.
Then the derivatives `f' i : E → L[ℝ] ℝ` and `φ' : E →L[ℝ] ℝ` are linearly dependent.
See also `is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at` for a version that
that states existence of Lagrange multipliers `Λ` and `Λ₀` instead of using
`¬linear_independent ℝ _` -/
lemma is_local_extr_on.linear_dependent_of_has_strict_fderiv_at {ι : Type*} [fintype ι]
{f : ι → E → ℝ} {f' : ι → E →L[ℝ] ℝ}
(hextr : is_local_extr_on φ {x | ∀ i, f i x = f i x₀} x₀)
(hf' : ∀ i, has_strict_fderiv_at (f i) (f' i) x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
¬linear_independent ℝ (λ i, option.elim i φ' f' : option ι → E →L[ℝ] ℝ) :=
begin
rw [fintype.linear_independent_iff], push_neg,
rcases hextr.exists_multipliers_of_has_strict_fderiv_at hf' hφ' with ⟨Λ, Λ₀, hΛ, hΛf⟩,
refine ⟨λ i, option.elim i Λ₀ Λ, _, _⟩,
{ simpa [add_comm] using hΛf },
{ simpa [function.funext_iff, not_and_distrib, or_comm, option.exists] using hΛ }
end
|
3f911bf149803463c240fd11691b1f99e587168a | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/ind5.lean | 77a65d18bd58d5a54e2512d46eb99a8c11632cb3 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 191 | lean | definition Prop [inline] : Type.{1} := Type.{0}
inductive or (A B : Prop) : Prop :=
| or_intro_left : A → or A B
| or_intro_right : B → or A B
check or
check or_intro_left
check or_rec |
c46dd0f79fa5e15f15a596702ba70c213a293d80 | e61a235b8468b03aee0120bf26ec615c045005d2 | /stage0/src/Init/Lean/Compiler/IR/Checker.lean | 9a763aa92d3c0c37bd1838c65a241f4b24ceff4a | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,638 | 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.Compiler.IR.CompilerM
import Init.Lean.Compiler.IR.Format
namespace Lean
namespace IR
namespace Checker
structure CheckerContext :=
(env : Environment) (localCtx : LocalContext := {}) (decls : Array Decl)
structure CheckerState :=
(foundVars : IndexSet := {})
abbrev M := ReaderT CheckerContext (ExceptT String (StateT CheckerState Id))
def markIndex (i : Index) : M Unit := do
s ← get;
when (s.foundVars.contains i) $ throw ("variable / joinpoint index " ++ toString i ++ " has already been used");
modify $ fun s => { s with foundVars := s.foundVars.insert i }
def markVar (x : VarId) : M Unit :=
markIndex x.idx
def markJP (j : JoinPointId) : M Unit :=
markIndex j.idx
def getDecl (c : Name) : M Decl := do
ctx ← read;
match findEnvDecl' ctx.env c ctx.decls with
| none => throw ("unknown declaration '" ++ toString c ++ "'")
| some d => pure d
def checkVar (x : VarId) : M Unit := do
ctx ← read;
unless (ctx.localCtx.isLocalVar x.idx || ctx.localCtx.isParam x.idx) $ throw ("unknown variable '" ++ toString x ++ "'")
def checkJP (j : JoinPointId) : M Unit := do
ctx ← read;
unless (ctx.localCtx.isJP j.idx) $ throw ("unknown join point '" ++ toString j ++ "'")
def checkArg (a : Arg) : M Unit :=
match a with
| Arg.var x => checkVar x
| other => pure ()
def checkArgs (as : Array Arg) : M Unit :=
as.forM checkArg
@[inline] def checkEqTypes (ty₁ ty₂ : IRType) : M Unit :=
unless (ty₁ == ty₂) $ throw ("unexpected type")
@[inline] def checkType (ty : IRType) (p : IRType → Bool) : M Unit :=
unless (p ty) $ throw ("unexpected type '" ++ toString ty ++ "'")
def checkObjType (ty : IRType) : M Unit := checkType ty IRType.isObj
def checkScalarType (ty : IRType) : M Unit := checkType ty IRType.isScalar
def getType (x : VarId) : M IRType := do
ctx ← read;
match ctx.localCtx.getType x with
| some ty => pure ty
| none => throw ("unknown variable '" ++ toString x ++ "'")
@[inline] def checkVarType (x : VarId) (p : IRType → Bool) : M Unit := do
ty ← getType x; checkType ty p
def checkObjVar (x : VarId) : M Unit :=
checkVarType x IRType.isObj
def checkScalarVar (x : VarId) : M Unit :=
checkVarType x IRType.isScalar
def checkFullApp (c : FunId) (ys : Array Arg) : M Unit := do
when (c == `hugeFuel) $
throw ("the auxiliary constant `hugeFuel` cannot be used in code, it is used internally for compiling `partial` definitions");
decl ← getDecl c;
unless (ys.size == decl.params.size) $
throw ("incorrect number of arguments to '" ++ toString c ++ "', " ++ toString ys.size ++ " provided, " ++ toString decl.params.size ++ " expected");
checkArgs ys
def checkPartialApp (c : FunId) (ys : Array Arg) : M Unit := do
decl ← getDecl c;
unless (ys.size < decl.params.size) $
throw ("too many arguments too partial application '" ++ toString c ++ "', num. args: " ++ toString ys.size ++ ", arity: " ++ toString decl.params.size);
checkArgs ys
def checkExpr (ty : IRType) : Expr → M Unit
| Expr.pap f ys => checkPartialApp f ys *> checkObjType ty -- partial applications should always produce a closure object
| Expr.ap x ys => checkObjVar x *> checkArgs ys
| Expr.fap f ys => checkFullApp f ys
| Expr.ctor c ys => when (!ty.isStruct && !ty.isUnion && c.isRef) (checkObjType ty) *> checkArgs ys
| Expr.reset _ x => checkObjVar x *> checkObjType ty
| Expr.reuse x i u ys => checkObjVar x *> checkArgs ys *> checkObjType ty
| Expr.box xty x => checkObjType ty *> checkScalarVar x *> checkVarType x (fun t => t == xty)
| Expr.unbox x => checkScalarType ty *> checkObjVar x
| Expr.proj i x => do xType ← getType x;
match xType with
| IRType.object => checkObjType ty
| IRType.tobject => checkObjType ty
| IRType.struct _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index"
| IRType.union _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index"
| other => throw ("unexpected IR type '" ++ toString xType ++ "'")
| Expr.uproj _ x => checkObjVar x *> checkType ty (fun t => t == IRType.usize)
| Expr.sproj _ _ x => checkObjVar x *> checkScalarType ty
| Expr.isShared x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8)
| Expr.isTaggedPtr x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8)
| Expr.lit (LitVal.str _) => checkObjType ty
| Expr.lit _ => pure ()
@[inline] def withParams (ps : Array Param) (k : M Unit) : M Unit := do
ctx ← read;
localCtx ← ps.foldlM (fun (ctx : LocalContext) p => do
markVar p.x;
pure $ ctx.addParam p) ctx.localCtx;
adaptReader (fun _ => { ctx with localCtx := localCtx }) k
partial def checkFnBody : FnBody → M Unit
| FnBody.vdecl x t v b => do
checkExpr t v;
markVar x;
ctx ← read;
adaptReader (fun (ctx : CheckerContext) => { ctx with localCtx := ctx.localCtx.addLocal x t v }) (checkFnBody b)
| FnBody.jdecl j ys v b => do
markJP j;
withParams ys (checkFnBody v);
ctx ← read;
adaptReader (fun (ctx : CheckerContext) => { ctx with localCtx := ctx.localCtx.addJP j ys v }) (checkFnBody b)
| FnBody.set x _ y b => checkVar x *> checkArg y *> checkFnBody b
| FnBody.uset x _ y b => checkVar x *> checkVar y *> checkFnBody b
| FnBody.sset x _ _ y _ b => checkVar x *> checkVar y *> checkFnBody b
| FnBody.setTag x _ b => checkVar x *> checkFnBody b
| FnBody.inc x _ _ _ b => checkVar x *> checkFnBody b
| FnBody.dec x _ _ _ b => checkVar x *> checkFnBody b
| FnBody.del x b => checkVar x *> checkFnBody b
| FnBody.mdata _ b => checkFnBody b
| FnBody.jmp j ys => checkJP j *> checkArgs ys
| FnBody.ret x => checkArg x
| FnBody.case _ x _ alts => checkVar x *> alts.forM (fun alt => checkFnBody alt.body)
| FnBody.unreachable => pure ()
def checkDecl : Decl → M Unit
| Decl.fdecl f xs t b => withParams xs (checkFnBody b)
| Decl.extern f xs t _ => withParams xs (pure ())
end Checker
def checkDecl (decls : Array Decl) (decl : Decl) : CompilerM Unit := do
env ← getEnv;
match (Checker.checkDecl decl { env := env, decls := decls }).run' {} with
| Except.error msg => throw ("IR check failed at '" ++ toString decl.name ++ "', error: " ++ msg)
| other => pure ()
def checkDecls (decls : Array Decl) : CompilerM Unit :=
decls.forM (checkDecl decls)
end IR
end Lean
|
1075e016c369662a3dbf7af482537bb4ec342de7 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/algebra/module/submodule_lattice.lean | 3f1c3acc74c1b4a3d37e34ac82d32030bfa77068 | [
"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 | 8,788 | 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, Kevin Buzzard, Yury Kudryashov
-/
import algebra.module.submodule
import algebra.punit_instances
/-!
# The lattice structure on `submodule`s
This file defines the lattice structure on submodules, `submodule.complete_lattice`, with `⊥`
defined as `{0}` and `⊓` defined as intersection of the underlying carrier.
If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`.
Many results about operations on this lattice structure are defined in `linear_algebra/basic.lean`,
most notably those which use `span`.
## Implementation notes
This structure should match the `add_submonoid.complete_lattice` structure, and we should try
to unify the APIs where possible.
-/
variables {R S M : Type*}
section add_comm_monoid
variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M]
variables [has_scalar S R] [is_scalar_tower S R M]
variables {p q : submodule R M}
namespace submodule
/-- The set `{0}` is the bottom element of the lattice of submodules. -/
instance : has_bot (submodule R M) :=
⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩
instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩
@[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl
@[simp] lemma bot_to_add_submonoid : (⊥ : submodule R M).to_add_submonoid = ⊥ := rfl
section
variables (R)
@[simp] lemma restrict_scalars_bot : restrict_scalars S (⊥ : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot {x : M} : x ∈ (⊥ : submodule R M) ↔ x = 0 := set.mem_singleton_iff
end
instance unique_bot : unique (⊥ : submodule R M) :=
⟨infer_instance, λ x, subtype.ext $ (mem_bot R).1 x.mem⟩
lemma nonzero_mem_of_bot_lt {I : submodule R M} (bot_lt : ⊥ < I) : ∃ a : I, a ≠ 0 :=
begin
have h := (set_like.lt_iff_le_and_exists.1 bot_lt).2,
tidy,
end
instance : order_bot (submodule R M) :=
{ bot := ⊥,
bot_le := λ p x, by simp {contextual := tt},
..set_like.partial_order }
protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) :=
⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx,
λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩
@[ext] protected lemma bot_ext (x y : (⊥ : submodule R M)) : x = y :=
begin
rcases x with ⟨x, xm⟩, rcases y with ⟨y, ym⟩, congr,
rw (submodule.eq_bot_iff _).mp rfl x xm,
rw (submodule.eq_bot_iff _).mp rfl y ym,
end
protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) :=
by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] }
/-- The bottom submodule is linearly equivalent to punit as an `R`-module. -/
@[simps] def bot_equiv_punit : (⊥ : submodule R M) ≃ₗ[R] punit :=
{ to_fun := λ x, punit.star,
inv_fun := λ x, 0,
map_add' := by { intros, ext, },
map_smul' := by { intros, ext, },
left_inv := by { intro x, ext, },
right_inv := by { intro x, ext, }, }
/-- The universal set is the top element of the lattice of submodules. -/
instance : has_top (submodule R M) :=
⟨{ carrier := set.univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩
@[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = set.univ := rfl
@[simp] lemma top_to_add_submonoid : (⊤ : submodule R M).to_add_submonoid = ⊤ := rfl
@[simp] lemma mem_top {x : M} : x ∈ (⊤ : submodule R M) := trivial
section
variables (R)
@[simp] lemma restrict_scalars_top : restrict_scalars S (⊤ : submodule R M) = ⊤ := rfl
end
instance : order_top (submodule R M) :=
{ top := ⊤,
le_top := λ p x _, trivial,
..set_like.partial_order }
lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, h trivial, λ h x _, h x⟩
/-- The top submodule is linearly equivalent to the module. -/
@[simps] def top_equiv_self : (⊤ : submodule R M) ≃ₗ[R] M :=
{ to_fun := λ x, x,
inv_fun := λ x, ⟨x, by simp⟩,
map_add' := by { intros, refl, },
map_smul' := by { intros, refl, },
left_inv := by { intro x, ext, refl, },
right_inv := by { intro x, refl, }, }
instance : has_Inf (submodule R M) :=
⟨λ S, {
carrier := ⋂ s ∈ S, (s : set M),
zero_mem' := by simp,
add_mem' := by simp [add_mem] {contextual := tt},
smul_mem' := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p :=
set.bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule R M)} {p} : (∀q ∈ S, p ≤ q) → p ≤ Inf S :=
set.subset_bInter
instance : has_inf (submodule R M) :=
⟨λ p q, {
carrier := p ∩ q,
zero_mem' := by simp,
add_mem' := by simp [add_mem] {contextual := tt},
smul_mem' := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule R M) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, set.subset_inter,
inf_le_left := λ a b, set.inter_subset_left _ _,
inf_le_right := λ a b, set.inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ q hq, hq _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.order_top,
..submodule.order_bot }
@[simp] theorem inf_coe : ↑(p ⊓ q) = (p ∩ q : set M) := rfl
@[simp] theorem mem_inf {p q : submodule R M} {x : M} :
x ∈ p ⊓ q ↔ x ∈ p ∧ x ∈ q := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem infi_coe {ι} (p : ι → submodule R M) :
(↑⨅ i, p i : set M) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p :=
set.mem_bInter_iff
@[simp] theorem mem_infi {ι} (p : ι → submodule R M) {x} :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← set_like.mem_coe, infi_coe, set.mem_Inter]; refl
lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
lemma add_mem_sup {S T : submodule R M} {s t : M} (hs : s ∈ S) (ht : t ∈ T) : s + t ∈ S ⊔ T :=
add_mem _ (mem_sup_left hs) (mem_sup_right ht)
lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) :
b ∈ (⨆i, p i) :=
have p i ≤ (⨆i, p i) := le_supr p i,
@this b h
open_locale big_operators
lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M}
(h : ∀ i, f i ∈ p i) :
∑ i, f i ∈ ⨆ i, p i :=
sum_mem _ $ λ i hi, mem_supr_of_mem i (h i)
lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M}
(h : ∀ i ∈ s, f i ∈ p i) :
∑ i in s, f i ∈ ⨆ i ∈ s, p i :=
sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi)
/-! Note that `submodule.mem_supr` is provided in `linear_algebra/basic.lean`. -/
lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M}
(hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
end submodule
section nat_submodule
/-- An additive submonoid is equivalent to a ℕ-submodule. -/
def add_submonoid.to_nat_submodule : add_submonoid M ≃o submodule ℕ M :=
{ to_fun := λ S,
{ smul_mem' := λ r s hs, S.nsmul_mem hs _, ..S },
inv_fun := submodule.to_add_submonoid,
left_inv := λ ⟨S, _, _⟩, rfl,
right_inv := λ ⟨S, _, _, _⟩, rfl,
map_rel_iff' := λ a b, iff.rfl }
@[simp]
lemma add_submonoid.to_nat_submodule_symm :
⇑(add_submonoid.to_nat_submodule.symm : _ ≃o add_submonoid M) = submodule.to_add_submonoid := rfl
@[simp]
lemma add_submonoid.coe_to_nat_submodule (S : add_submonoid M) :
(S.to_nat_submodule : set M) = S := rfl
@[simp]
lemma add_submonoid.to_nat_submodule_to_add_submonoid (S : add_submonoid M) :
S.to_nat_submodule.to_add_submonoid = S :=
add_submonoid.to_nat_submodule.symm_apply_apply S
@[simp]
lemma submodule.to_add_submonoid_to_nat_submodule (S : submodule ℕ M) :
S.to_add_submonoid.to_nat_submodule = S :=
add_submonoid.to_nat_submodule.apply_symm_apply S
end nat_submodule
end add_comm_monoid
|
5969b2f58742075cc79c20330ef8dd9560a801f0 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/omega/prove_unsats.lean | 12d317591e0a05c45f06fe0f176a0c669b22c2cd | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 1,841 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
A tactic which constructs exprs to discharge
goals of the form `clauses.unsat cs`.
-/
import tactic.omega.find_ees
import tactic.omega.find_scalars
import tactic.omega.lin_comb
namespace omega
open tactic
meta def prove_neg : int → tactic expr
| (int.of_nat _) := failed
| -[1+ m] := return `(int.neg_succ_lt_zero %%`(m))
lemma forall_mem_repeat_zero_eq_zero (m : nat) :
(∀ x ∈ (list.repeat (0 : int) m), x = (0 : int)) :=
λ x, list.eq_of_mem_repeat
meta def prove_forall_mem_eq_zero (is : list int) : tactic expr :=
return `(forall_mem_repeat_zero_eq_zero is.length)
meta def prove_unsat_lin_comb (ks : list nat) (ts : list term) : tactic expr :=
let ⟨b,as⟩ := lin_comb ks ts in
do x1 ← prove_neg b,
x2 ← prove_forall_mem_eq_zero as,
to_expr ``(unsat_lin_comb_of %%`(ks) %%`(ts) %%x1 %%x2)
/- Given a (([],les) : clause), return the
expr of a term (t : clause.unsat ([],les)). -/
meta def prove_unsat_ef : clause → tactic expr
| ((_::_), _) := failed
| ([], les) :=
do ks ← find_scalars les,
x ← prove_unsat_lin_comb ks les,
return `(unsat_of_unsat_lin_comb %%`(ks) %%`(les) %%x)
/- Given a (c : clause), return the
expr of a term (t : clause.unsat c) -/
meta def prove_unsat (c : clause) : tactic expr :=
do ee ← find_ees c,
x ← prove_unsat_ef (eq_elim ee c),
return `(unsat_of_unsat_eq_elim %%`(ee) %%`(c) %%x)
/- Given a (cs : list clause), return the
expr of a term (t : clauses.unsat cs) -/
meta def prove_unsats : list clause → tactic expr
| [] := return `(clauses.unsat_nil)
| (p::ps) :=
do x ← prove_unsat p,
xs ← prove_unsats ps,
to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs)
end omega |
ac350eaf5f6f63910ca95ab523653d6962e63e6b | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/big_operators/finsupp.lean | 74ff7980abf3870fc2686bc6560464b904f96790 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 1,621 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import data.finsupp.basic
import algebra.big_operators.pi
import algebra.big_operators.ring
/-!
# Big operators for finsupps
This file contains theorems relevant to big operators in finitely supported functions.
-/
open_locale big_operators
variables {α ι γ A B C : Type*} [add_comm_monoid A] [add_comm_monoid B] [add_comm_monoid C]
variables {t : ι → A → C} (h0 : ∀ i, t i 0 = 0) (h1 : ∀ i x y, t i (x + y) = t i x + t i y)
variables {s : finset α} {f : α → (ι →₀ A)} (i : ι)
variables (g : ι →₀ A) (k : ι → A → γ → B) (x : γ)
theorem finset.sum_apply' : (∑ k in s, f k) i = ∑ k in s, f k i :=
(finsupp.apply_add_hom i : (ι →₀ A) →+ A).map_sum f s
theorem finsupp.sum_apply' : g.sum k x = g.sum (λ i b, k i b x) :=
finset.sum_apply _ _ _
section
include h0 h1
open_locale classical
theorem finsupp.sum_sum_index' : (∑ x in s, f x).sum t = ∑ x in s, (f x).sum t :=
finset.induction_on s rfl $ λ a s has ih,
by simp_rw [finset.sum_insert has, finsupp.sum_add_index h0 h1, ih]
end
section
variables {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S]
lemma finsupp.sum_mul (b : S) (s : α →₀ R) {f : α → R → S} :
(s.sum f) * b = s.sum (λ a c, (f a c) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma finsupp.mul_sum (b : S) (s : α →₀ R) {f : α → R → S} :
b * (s.sum f) = s.sum (λ a c, b * (f a c)) :=
by simp only [finsupp.sum, finset.mul_sum]
end
|
6c0d86ccc24a44fce8f5b1d4270974fd13d63593 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/polynomial/scale_roots.lean | 5c7d9c18bed7cf5e667e845469e8104227546121 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,192 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Devon Tuma
-/
import ring_theory.non_zero_divisors
import data.polynomial.algebra_map
/-!
# Scaling the roots of a polynomial
This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to
be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it.
-/
section scale_roots
variables {A K R S : Type*} [comm_ring A] [is_domain A] [field K] [comm_ring R] [comm_ring S]
variables {M : submonoid A}
open polynomial
open_locale big_operators polynomial
/-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/
noncomputable def scale_roots (p : R[X]) (s : R) : R[X] :=
∑ i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i))
@[simp] lemma coeff_scale_roots (p : R[X]) (s : R) (i : ℕ) :
(scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) :=
by simp [scale_roots, coeff_monomial] {contextual := tt}
lemma coeff_scale_roots_nat_degree (p : R[X]) (s : R) :
(scale_roots p s).coeff p.nat_degree = p.leading_coeff :=
by rw [leading_coeff, coeff_scale_roots, tsub_self, pow_zero, mul_one]
@[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp }
lemma scale_roots_ne_zero {p : R[X]} (hp : p ≠ 0) (s : R) :
scale_roots p s ≠ 0 :=
begin
intro h,
have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp,
have : (scale_roots p s).coeff p.nat_degree = 0 :=
congr_fun (congr_arg (coeff : R[X] → ℕ → R) h) p.nat_degree,
rw [coeff_scale_roots_nat_degree] at this,
contradiction
end
lemma support_scale_roots_le (p : R[X]) (s : R) :
(scale_roots p s).support ≤ p.support :=
by { intro, simpa using left_ne_zero_of_mul }
lemma support_scale_roots_eq (p : R[X]) {s : R} (hs : s ∈ non_zero_divisors R) :
(scale_roots p s).support = p.support :=
le_antisymm (support_scale_roots_le p s)
begin
intro i,
simp only [coeff_scale_roots, polynomial.mem_support_iff],
intros p_ne_zero ps_zero,
have := pow_mem hs (p.nat_degree - i) _ ps_zero,
contradiction
end
@[simp] lemma degree_scale_roots (p : R[X]) {s : R} :
degree (scale_roots p s) = degree p :=
begin
haveI := classical.prop_decidable,
by_cases hp : p = 0,
{ rw [hp, zero_scale_roots] },
have := scale_roots_ne_zero hp s,
refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _),
rw coeff_scale_roots_nat_degree,
intro h,
have := leading_coeff_eq_zero.mp h,
contradiction,
end
@[simp] lemma nat_degree_scale_roots (p : R[X]) (s : R) :
nat_degree (scale_roots p s) = nat_degree p :=
by simp only [nat_degree, degree_scale_roots]
lemma monic_scale_roots_iff {p : R[X]} (s : R) :
monic (scale_roots p s) ↔ monic p :=
by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree]
lemma scale_roots_eval₂_eq_zero {p : S[X]} (f : S →+* R)
{r : R} {s : S} (hr : eval₂ f r p = 0) :
eval₂ f (f s * r) (scale_roots p s) = 0 :=
calc eval₂ f (f s * r) (scale_roots p s) =
(scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
by simp [eval₂_eq_sum, sum_def]
... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
finset.sum_subset (support_scale_roots_le p s)
(λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 :=
by simpa using hi' in by simp [this])
... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) :
finset.sum_congr rfl
(λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc])
... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) :
finset.sum_congr rfl
(λ i hi, by { rw [mul_assoc, mul_left_comm, tsub_add_cancel_of_le],
exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) })
... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm
... = f s ^ p.nat_degree * eval₂ f r p : by { simp [eval₂_eq_sum, sum_def] }
... = 0 : by rw [hr, _root_.mul_zero]
lemma scale_roots_aeval_eq_zero [algebra S R] {p : S[X]}
{r : R} {s : S} (hr : aeval r p = 0) :
aeval (algebra_map S R s * r) (scale_roots p s) = 0 :=
scale_roots_eval₂_eq_zero (algebra_map S R) hr
lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero
{p : A[X]} {f : A →+* K} (hf : function.injective f)
{r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) :
eval₂ f (f r) (scale_roots p s) = 0 :=
begin
convert scale_roots_eval₂_eq_zero f hr,
rw [←mul_div_assoc, mul_comm, mul_div_cancel],
exact map_ne_zero_of_mem_non_zero_divisors _ hf hs
end
lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K]
(inj : function.injective (algebra_map A K)) {p : A[X]} {r s : A}
(hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) :
aeval (algebra_map A K r) (scale_roots p s) = 0 :=
scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs
end scale_roots
|
fa866c0ccb46cfb4a2f739dd115b033347b8e567 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/big_operators/pi.lean | 782beadf6e664412a4ca8e0d7f2675446ba92b96 | [
"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 | 3,871 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import algebra.big_operators.basic
import algebra.ring.pi
/-!
# Big operators for Pi Types
This file contains theorems relevant to big operators in binary and arbitrary product
of monoids and groups
-/
open_locale big_operators
namespace pi
@[to_additive]
lemma list_prod_apply {α : Type*} {β : α → Type*} [Πa, monoid (β a)] (a : α) (l : list (Πa, β a)) :
l.prod a = (l.map (λf:Πa, β a, f a)).prod :=
(eval_monoid_hom β a).map_list_prod _
@[to_additive]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
(eval_monoid_hom β a).map_multiset_prod _
end pi
@[simp, to_additive]
lemma finset.prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a :=
(pi.eval_monoid_hom β a).map_prod _ _
/-- An 'unapplied' analogue of `finset.prod_apply`. -/
@[to_additive "An 'unapplied' analogue of `finset.sum_apply`."]
lemma finset.prod_fn {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)]
(s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) = (λ a, ∏ c in s, g c a) :=
funext (λ a, finset.prod_apply _ _ _)
@[simp, to_additive]
lemma fintype.prod_apply {α : Type*} {β : α → Type*} {γ : Type*} [fintype γ]
[∀a, comm_monoid (β a)] (a : α) (g : γ → Πa, β a) : (∏ c, g c) a = ∏ c, g c a :=
finset.prod_apply a finset.univ g
@[to_additive prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
section single
variables {I : Type*} [decidable_eq I] {Z : I → Type*}
variables [Π i, add_comm_monoid (Z i)]
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) :
∑ i, pi.single i (f i) = f :=
by { ext a, simp }
lemma add_monoid_hom.functions_ext [fintype I] (G : Type*)
[add_comm_monoid G] (g h : (Π i, Z i) →+ G)
(w : ∀ (i : I) (x : Z i), g (pi.single i x) = h (pi.single i x)) : g = h :=
begin
ext k,
rw [← finset.univ_sum_single k, g.map_sum, h.map_sum],
simp only [w]
end
/-- This is used as the ext lemma instead of `add_monoid_hom.functions_ext` for reasons explained in
note [partially-applied ext lemmas]. -/
@[ext]
lemma add_monoid_hom.functions_ext' [fintype I] (M : Type*) [add_comm_monoid M]
(g h : (Π i, Z i) →+ M)
(H : ∀ i, g.comp (add_monoid_hom.single Z i) = h.comp (add_monoid_hom.single Z i)) :
g = h :=
have _ := λ i, add_monoid_hom.congr_fun (H i), -- elab without an expected type
g.functions_ext M h this
end single
section ring_hom
open pi
variables {I : Type*} [decidable_eq I] {f : I → Type*}
variables [Π i, non_assoc_semiring (f i)]
@[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [non_assoc_semiring G]
(g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
ring_hom.coe_add_monoid_hom_injective $
add_monoid_hom.functions_ext G (g : (Π i, f i) →+ G) h w
end ring_hom
namespace prod
variables {α β γ : Type*} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β}
@[to_additive]
lemma fst_prod : (∏ c in s, f c).1 = ∏ c in s, (f c).1 :=
(monoid_hom.fst α β).map_prod f s
@[to_additive]
lemma snd_prod : (∏ c in s, f c).2 = ∏ c in s, (f c).2 :=
(monoid_hom.snd α β).map_prod f s
end prod
|
27b402bddcbe20f6acc508164444c7a2278cec32 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/run/one.lean | fbc8a71ca76dedfda505045d3ea23ca9c329325f | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 326 | lean | inductive one.{l} : Type.{max 1 l} :=
unit : one.{l}
set_option pp.universes true
check one
inductive one2.{l} : Type.{max 1 l} :=
unit : one2
check one2
context foo
universe l2
parameter A : Type.{l2}
inductive wrapper.{l} : Type.{max 1 l l2} :=
mk : A → wrapper.{l2 l}
check wrapper
end foo
check wrapper
|
3b675c52435417a45edffb33e88440551a71a18c | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/analysis/specific_limits.lean | 7cc154757c540d76a4847c9361ad60c8cc256fc4 | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 7,018 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
A collection of specific limit computations.
-/
import analysis.normed_space.basic
import topology.instances.ennreal
noncomputable theory
local attribute [instance] classical.prop_decidable
open classical function lattice filter finset metric
variables {α : Type*} {β : Type*} {ι : Type*}
lemma has_sum_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) → has_sum f
| ⟨r, hr⟩ :=
begin
refine has_sum_of_has_sum_norm ⟨r, (is_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top :=
tendsto_infi.2 $ assume p, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in
have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n,
have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption,
have p ≤ r ^ n,
from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm
... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn
... ≤ 1 + n * (r - 1) : le_add_of_nonneg_of_le zero_le_one (le_refl _)
... = 1 + add_monoid.smul n (r - 1) : by rw [add_monoid.smul_eq_mul]
... ≤ (1 + (r - 1)) ^ n : pow_ge_one_add_mul (le_of_lt this) _
... ≤ r ^ n : by simp; exact le_refl _,
show {n | p ≤ r ^ n} ∈ at_top,
from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩
lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) :=
tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu,
mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb,
have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb,
⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this,
lt_of_one_div_lt_one_div hu $
begin
rw [inv_eq_one_div],
simp [-one_div_eq_inv, div_div_eq_mul_div, div_one],
simp [this]
end⟩⟩
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (nhds 0) :=
by_cases
(assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0),
from (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂).comp
tendsto_inverse_at_top_nhds_0,
tendsto.congr' (univ_mem_sets' $ by simp *) this)
lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) :
tendsto (λn:ℕ, k ^ n) at_top at_top :=
tendsto_coe_nat_real_at_top_iff.1 $
have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h,
by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (nhds 0) :=
tendsto.comp (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) tendsto_inverse_at_top_nhds_0
lemma tendsto_one_div_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1/(n : ℝ)) at_top (nhds 0) :=
by simpa only [inv_eq_one_div] using tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (nhds 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (nhds 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 tendsto_one_div_at_top_nhds_0_nat
lemma is_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
is_sum (λn:ℕ, r ^ n) (1 / (1 - r)) :=
have r ≠ 1, from ne_of_lt h₂,
have r + -1 ≠ 0,
by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)),
from tendsto_mul
(tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds,
(is_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma is_sum_geometric_two (a : ℝ) : is_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert is_sum_mul_left (a / 2) (is_sum_geometric
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp,
rw ← pow_inv; [refl, exact two_ne_zero] },
{ norm_num, rw div_mul_cancel _ two_ne_zero }
end
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, is_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : is_sum f ε := is_sum_geometric_two _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases has_sum_comp_of_has_sum_of_injective f (has_sum_spec hf) (@encodable.encode_injective ι _)
with ⟨c, hg⟩,
refine ⟨c, hg, is_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
lemma cauchy_seq_of_le_geometric [metric_space α] (r C : ℝ) (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) : cauchy_seq f :=
begin
refine cauchy_seq_of_has_sum_dist (has_sum_of_norm_bounded (λn, C * r^n) _ _),
{ by_cases h : C = 0,
{ simp [h, has_sum_zero] },
{ have Cpos : C > 0,
{ have := le_trans dist_nonneg (hu 0),
simp only [mul_one, pow_zero] at this,
exact lt_of_le_of_ne this (ne.symm h) },
have rnonneg: r ≥ 0,
{ have := le_trans dist_nonneg (hu 1),
simp only [pow_one] at this,
exact nonneg_of_mul_nonneg_left this Cpos },
refine has_sum_mul_left C _,
exact has_sum_spec (@is_sum_geometric r rnonneg hr) }},
show ∀n, abs (dist (f n) (f (n+1))) ≤ C * r^n,
{ assume n, rw abs_of_nonneg (dist_nonneg), exact hu n }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, is_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt.2 $ hε' i,
⟨c, is_sum_le (assume i, le_of_lt $ hε' i) is_sum_zero hc ⟩, nnreal.is_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
|
db08c4fd5ca24d642000bf62c493695ebc1735b6 | 8c02fed42525b65813b55c064afe2484758d6d09 | /src/main.lean | e37a6a6ca20ceced63df73d3266271842310269d | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | microsoft/AliveInLean | 3eac351a34154efedd3ffc4fe2fa4ec01b219e0d | 4b739dd6e4266b26a045613849df221374119871 | refs/heads/master | 1,691,419,737,939 | 1,689,365,567,000 | 1,689,365,568,000 | 131,156,103 | 23 | 18 | NOASSERTION | 1,660,342,040,000 | 1,524,747,538,000 | Lean | UTF-8 | Lean | false | false | 6,093 | lean | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT license.
import system.io
import system.random
import .freevar
import .langparser
import .lang
import .lang_tostr
import .irsem
import .irsem_smt
import .irsem_exec
import .irtype
import .vcgen
import .verifyopt
import smt2.solvers.z3
open io
open parser
open irsem
def string.starts_with (s1:string) (sprefix:string): bool :=
list.is_prefix_of (sprefix.to_list) (s1.to_list)
def exec_emitter:vcgen.emitter irsem_exec :=
⟨irsem_exec.val_to_smt,
irsem_exec.poison_to_smt, irsem_exec.bool_to_smt⟩
meta def smt_emitter:vcgen.emitter irsem_smt :=
⟨irsem_smt.val_to_smt,
irsem_smt.poison_to_smt, irsem_smt.bool_to_smt⟩
-- Runs a single program.
namespace singleprog
meta def print_result {α:Type} [has_to_string α] (result_state:option α)
: io (option α) :=
match result_state with
| none := do
io.print_ln "Stuck",
return none
| some finalresult := do
io.print_ln (finalresult),
return (some finalresult)
end
-- Executes a program and check whether SMT formula generated
-- from the program encodes the final state.
meta def run_and_emit_smt2 (typedp:program) : io unit :=
do
let gen := mk_std_gen,
print_ln "=== Free Variables ===",
let freevars := freevar.get typedp,
print_ln $ "free vars:" ++ to_string freevars,
print_ln "=== Run-EXE ===",
let (init_st, gen) := freevar.create_init_state_exec freevars gen,
final_st ← print_result (bigstep irsem_exec init_st typedp),
print_ln "=== Run-SMT ===",
let init_st' := freevar.create_init_state_smt freevars,
final_st' ← print_result (bigstep irsem_smt init_st' typedp),
match final_st, final_st' with
| (some final_st), (some final_st') :=
do
print_ln "=== SMT Code Gen ===",
let smtcode := vcgen.emit_smt typedp
freevars init_st' final_st final_st'
exec_emitter smt_emitter,
print_ln smtcode,
print_ln "=== Z3 Result ===",
z3i ← z3_instance.start,
smtres ← z3_instance.raw z3i smtcode.to_string,
print_ln smtres,
return ()
| _, _ := return ()
end
-- Reads an input, concretizes its type, emit SMT code, and run it
meta def check (filename:string) (encode_poison:bool): io unit := do
hl ← mk_file_handle filename (io.mode.read) ff,
charbuf ← io.fs.read_to_end hl,
-- Parse the input.
match (run ReadProgram charbuf) with
| sum.inl errmsg := put_str errmsg -- Parsing failed.
| sum.inr prog :=
let runf := λ p (encode_poison:bool), run_and_emit_smt2 p in
do
_ ← put_str (to_string prog),
match (concretize_type prog) with
| list.nil := put_str "Cannot find well-typed program with given input."
| x := -- Just run one among them.
monad.foldl (λ a typed_prog, do
print_ln "-------- Next Example ----------",
print_ln "=== After type concretization ===",
print_ln typed_prog,
runf typed_prog encode_poison)
() x
end
end
end singleprog
-- Verifies optimizations.
namespace verifyopt
def root_name (p:program): string :=
match p.insts.reverse with
| [] := ""
| (instruction.binop _ (reg.r r) _ _ _ _)::_ := r
| (instruction.icmpop _ (reg.r r) _ _ _)::_ := r
| (instruction.selectop (reg.r r) _ _ _ _ _)::_ := r
| (instruction.unaryop (reg.r r) _ _ _ _)::_ := r
end
meta def check_one (t:transformation) (n:nat) (verbose:bool): io unit := do
let debug_ln (str:format) :=
if verbose then print_ln str else return (),
debug_ln format!"--------{t.name}-------{n}--",
let (lp1, lp2) := (concretize_type t.src, concretize_type t.tgt),
let gen := mk_std_gen,
match lp1, lp2 with
| p1::_, p2::_ := do
let freevars := freevar.get p1,
let (init_st, gen) := freevar.create_init_state_exec freevars gen,
let init_st' := freevar.create_init_state_smt freevars,
let r := root_name p1,
debug_ln (format!"Root variable:{r}"),
debug_ln "=== Does it refine? (EXE) ===",
let ob_exec := opt.check_single_reg irsem_exec p1 p2 r init_st,
debug_ln (to_string ob_exec),
debug_ln "=== Does it refine? (SMT) ===",
let ob_smt := opt.check_single_reg irsem_smt p1 p2 r init_st',
debug_ln (to_string ob_smt),
match ob_smt with
| some smtobj := do
debug_ln "=== Z3 Result ===",
let smtcode := vcgen.emit_refine_smt p1 p2
freevars smtobj smt_emitter,
debug_ln smtcode,
z3i ← z3_instance.start,
smtres ← z3_instance.raw z3i smtcode.to_string,
debug_ln (smtres ++ "(Unsat means the opt. is correct)"),
debug_ln "",
if smtres = "unsat\n" then
print_ln "Correct"
else
print_ln "Incorrect"
| none := return ()
end
| _, _ := return ()
end
-- Reads transformations and checks them.
meta def check (filename:string) (parseonly:bool) (verbose:bool): io unit := do
hl ← mk_file_handle filename (io.mode.read) ff,
charbuf ← io.fs.read_to_end hl,
match (run ReadTransformations charbuf) with
| sum.inl errmsg := put_str errmsg
| sum.inr tfs :=
if parseonly then do
print_ln "Parsing done.",
_ ← monad.foldl (λ n tf, do
print_ln (to_string tf), print_ln "", return (n+1)) 1 tfs,
return ()
else do
_ ← monad.foldl (λ n tf, do
check_one tf n verbose, return (n+1)) 1 tfs,
return ()
end
end verifyopt
meta def main : io unit :=
do args ← io.cmdline_args,
let cmd := list.head args in
let args := list.tail args in
let get_verbose (l:list string): bool :=
match l with | [] := ff | l :=
if list.head (list.reverse l) = "-verbose" then tt else ff end in
match cmd with
| "-input" := singleprog.check (list.head args) ff
| "-input2" := singleprog.check (list.head args) tt
| "-parseopt" := verifyopt.check (list.head args) tt
(get_verbose (list.tail args))
| "-verifyopt" := verifyopt.check (list.head args) ff
(get_verbose (list.tail args))
| _ := print_ln ("Unknown argument: " ++ cmd)
end |
902d58fb5eb679de388e29189f7dfddb2f6a5d68 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/abelian/pseudoelements.lean | 406c9ea56766c55e136aa74e4749db5ddf8752bb | [
"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 | 18,539 | 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.abelian.exact
import category_theory.over
/-!
# Pseudoelements in abelian categories
A *pseudoelement* of an object `X` in an abelian category `C` is an equivalence class of arrows
ending in `X`, where two arrows are considered equivalent if we can find two epimorphisms with a
common domain making a commutative square with the two arrows. While the construction shows that
pseudoelements are actually subobjects of `X` rather than "elements", it is possible to chase these
pseudoelements through commutative diagrams in an abelian category to prove exactness properties.
This is done using some "diagram-chasing metatheorems" proved in this file. In many cases, a proof
in the category of abelian groups can more or less directly be converted into a proof using
pseudoelements.
A classic application of pseudoelements are diagram lemmas like the four lemma or the snake lemma.
Pseudoelements are in some ways weaker than actual elements in a concrete category. The most
important limitation is that there is no extensionality principle: If `f g : X ⟶ Y`, then
`∀ x ∈ X, f x = g x` does not necessarily imply that `f = g` (however, if `f = 0` or `g = 0`,
it does). A corollary of this is that we can not define arrows in abelian categories by dictating
their action on pseudoelements. Thus, a usual style of proofs in abelian categories is this:
First, we construct some morphism using universal properties, and then we use diagram chasing
of pseudoelements to verify that is has some desirable property such as exactness.
It should be noted that the Freyd-Mitchell embedding theorem gives a vastly stronger notion of
pseudoelement (in particular one that gives extensionality). However, this theorem is quite
difficult to prove and probably out of reach for a formal proof for the time being.
## Main results
We define the type of pseudoelements of an object and, in particular, the zero pseudoelement.
We prove that every morphism maps the zero pseudoelement to the zero pseudoelement (`apply_zero`)
and that a zero morphism maps every pseudoelement to the zero pseudoelement (`zero_apply`)
Here are the metatheorems we provide:
* A morphism `f` is zero if and only if it is the zero function on pseudoelements.
* A morphism `f` is an epimorphism if and only if it is surjective on pseudoelements.
* A morphism `f` is a monomorphism if and only if it is injective on pseudoelements
if and only if `∀ a, f a = 0 → f = 0`.
* A sequence `f, g` of morphisms is exact if and only if
`∀ a, g (f a) = 0` and `∀ b, g b = 0 → ∃ a, f a = b`.
* If `f` is a morphism and `a, a'` are such that `f a = f a'`, then there is some
pseudoelement `a''` such that `f a'' = 0` and for every `g` we have
`g a' = 0 → g a = g a''`. We can think of `a''` as `a - a'`, but don't get too carried away
by that: pseudoelements of an object do not form an abelian group.
## Notations
We introduce coercions from an object of an abelian category to the set of its pseudoelements
and from a morphism to the function it induces on pseudoelements.
These coercions must be explicitly enabled via local instances:
`local attribute [instance] object_to_sort hom_to_fun`
## Implementation notes
It appears that sometimes the coercion from morphisms to functions does not work, i.e.,
writing `g a` raises a "function expected" error. This error can be fixed by writing
`(g : X ⟶ Y) a`.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
open category_theory
open category_theory.limits
open category_theory.abelian
open category_theory.preadditive
universes v u
namespace category_theory.abelian
variables {C : Type u} [category.{v} C]
local attribute [instance] over.coe_from_hom
/-- This is just composition of morphisms in `C`. Another way to express this would be
`(over.map f).obj a`, but our definition has nicer definitional properties. -/
def app {P Q : C} (f : P ⟶ Q) (a : over P) : over Q :=
a.hom ≫ f
@[simp] lemma app_hom {P Q : C} (f : P ⟶ Q) (a : over P) : (app f a).hom = a.hom ≫ f := rfl
/-- Two arrows `f : X ⟶ P` and `g : Y ⟶ P` are called pseudo-equal if there is some object
`R` and epimorphisms `p : R ⟶ X` and `q : R ⟶ Y` such that `p ≫ f = q ≫ g`. -/
def pseudo_equal (P : C) (f g : over P) : Prop :=
∃ (R : C) (p : R ⟶ f.1) (q : R ⟶ g.1) [epi p] [epi q], p ≫ f.hom = q ≫ g.hom
lemma pseudo_equal_refl {P : C} : reflexive (pseudo_equal P) :=
λ f, ⟨f.1, 𝟙 f.1, 𝟙 f.1, by apply_instance, by apply_instance, by simp⟩
lemma pseudo_equal_symm {P : C} : symmetric (pseudo_equal P) :=
λ f g ⟨R, p, q, ep, eq, comm⟩, ⟨R, q, p, eq, ep, comm.symm⟩
variables [abelian.{v} C]
section
/-- Pseudoequality is transitive: Just take the pullback. The pullback morphisms will
be epimorphisms since in an abelian category, pullbacks of epimorphisms are epimorphisms. -/
lemma pseudo_equal_trans {P : C} : transitive (pseudo_equal P) :=
λ f g h ⟨R, p, q, ep, eq, comm⟩ ⟨R', p', q', ep', eq', comm'⟩,
begin
refine ⟨pullback q p', pullback.fst ≫ p, pullback.snd ≫ q', _, _, _⟩,
{ resetI, exact epi_comp _ _ },
{ resetI, exact epi_comp _ _ },
{ rw [category.assoc, comm, ←category.assoc, pullback.condition,
category.assoc, comm', category.assoc] }
end
end
/-- The arrows with codomain `P` equipped with the equivalence relation of being pseudo-equal. -/
def pseudoelement.setoid (P : C) : setoid (over P) :=
⟨_, ⟨pseudo_equal_refl, pseudo_equal_symm, pseudo_equal_trans⟩⟩
local attribute [instance] pseudoelement.setoid
/-- A `pseudoelement` of `P` is just an equivalence class of arrows ending in `P` by being
pseudo-equal. -/
def pseudoelement (P : C) : Type (max u v) := quotient (pseudoelement.setoid P)
namespace pseudoelement
/-- A coercion from an object of an abelian category to its pseudoelements. -/
def object_to_sort : has_coe_to_sort C :=
{ S := Type (max u v),
coe := λ P, pseudoelement P }
local attribute [instance] object_to_sort
/-- A coercion from an arrow with codomain `P` to its associated pseudoelement. -/
def over_to_sort {P : C} : has_coe (over P) (pseudoelement P) :=
⟨quot.mk (pseudo_equal P)⟩
local attribute [instance] over_to_sort
lemma over_coe_def {P Q : C} (a : Q ⟶ P) : (a : pseudoelement P) = ⟦a⟧ := rfl
/-- If two elements are pseudo-equal, then their composition with a morphism is, too. -/
lemma pseudo_apply_aux {P Q : C} (f : P ⟶ Q) (a b : over P) :
a ≈ b → app f a ≈ app f b :=
λ ⟨R, p, q, ep, eq, comm⟩,
⟨R, p, q, ep, eq, show p ≫ a.hom ≫ f = q ≫ b.hom ≫ f, by rw reassoc_of comm⟩
/-- A morphism `f` induces a function `pseudo_apply f` on pseudoelements. -/
def pseudo_apply {P Q : C} (f : P ⟶ Q) : P → Q :=
quotient.map (λ (g : over P), app f g) (pseudo_apply_aux f)
/-- A coercion from morphisms to functions on pseudoelements -/
def hom_to_fun {P Q : C} : has_coe_to_fun (P ⟶ Q) := ⟨_, pseudo_apply⟩
local attribute [instance] hom_to_fun
lemma pseudo_apply_mk {P Q : C} (f : P ⟶ Q) (a : over P) : f ⟦a⟧ = ⟦a.hom ≫ f⟧ :=
rfl
/-- Applying a pseudoelement to a composition of morphisms is the same as composing
with each morphism. Sadly, this is not a definitional equality, but at least it is
true. -/
theorem comp_apply {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) (a : P) : (f ≫ g) a = g (f a) :=
quotient.induction_on a $ λ x, quotient.sound $
by { unfold app, rw [←category.assoc, over.coe_hom] }
/-- Composition of functions on pseudoelements is composition of morphisms. -/
theorem comp_comp {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : g ∘ f = f ≫ g :=
funext $ λ x, (comp_apply _ _ _).symm
section zero
/-!
In this section we prove that for every `P` there is an equivalence class that contains
precisely all the zero morphisms ending in `P` and use this to define *the* zero
pseudoelement.
-/
section
local attribute [instance] has_binary_biproducts.of_has_binary_products
/-- The arrows pseudo-equal to a zero morphism are precisely the zero morphisms -/
lemma pseudo_zero_aux {P : C} (Q : C) (f : over P) : f ≈ (0 : Q ⟶ P) ↔ f.hom = 0 :=
⟨λ ⟨R, p, q, ep, eq, comm⟩, by exactI zero_of_epi_comp p (by simp [comm]),
λ hf, ⟨biprod f.1 Q, biprod.fst, biprod.snd, by apply_instance, by apply_instance,
by rw [hf, over.coe_hom, has_zero_morphisms.comp_zero, has_zero_morphisms.comp_zero]⟩⟩
end
lemma zero_eq_zero' {P Q R : C} :
⟦((0 : Q ⟶ P) : over P)⟧ = ⟦((0 : R ⟶ P) : over P)⟧ :=
quotient.sound $ (pseudo_zero_aux R _).2 rfl
/-- The zero pseudoelement is the class of a zero morphism -/
def pseudo_zero {P : C} : P := ⟦(0 : P ⟶ P)⟧
instance {P : C} : has_zero P := ⟨pseudo_zero⟩
instance {P : C} : inhabited (pseudoelement P) := ⟨0⟩
lemma pseudo_zero_def {P : C} : (0 : pseudoelement P) = ⟦(0 : P ⟶ P)⟧ := rfl
@[simp] lemma zero_eq_zero {P Q : C} : ⟦((0 : Q ⟶ P) : over P)⟧ = (0 : pseudoelement P) :=
zero_eq_zero'
/-- The pseudoelement induced by an arrow is zero precisely when that arrow is zero -/
lemma pseudo_zero_iff {P : C} (a : over P) : (a : P) = 0 ↔ a.hom = 0 :=
by { rw ←pseudo_zero_aux P a, exact quotient.eq }
end zero
/-- Morphisms map the zero pseudoelement to the zero pseudoelement -/
@[simp] theorem apply_zero {P Q : C} (f : P ⟶ Q) : f 0 = 0 :=
by { rw [pseudo_zero_def, pseudo_apply_mk], simp }
/-- The zero morphism maps every pseudoelement to 0. -/
@[simp] theorem zero_apply {P : C} (Q : C) (a : P) : (0 : P ⟶ Q) a = 0 :=
quotient.induction_on a $ λ a',
by { rw [pseudo_zero_def, pseudo_apply_mk], simp }
/-- An extensionality lemma for being the zero arrow. -/
@[ext] theorem zero_morphism_ext {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0) → f = 0 :=
λ h, by { rw ←category.id_comp f, exact (pseudo_zero_iff ((𝟙 P ≫ f) : over Q)).1 (h (𝟙 P)) }
@[ext] theorem zero_morphism_ext' {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0) → 0 = f :=
eq.symm ∘ zero_morphism_ext f
theorem eq_zero_iff {P Q : C} (f : P ⟶ Q) : f = 0 ↔ ∀ a, f a = 0 :=
⟨λ h a, by simp [h], zero_morphism_ext _⟩
/-- A monomorphism is injective on pseudoelements. -/
theorem pseudo_injective_of_mono {P Q : C} (f : P ⟶ Q) [mono f] : function.injective f :=
λ abar abar', quotient.induction_on₂ abar abar' $ λ a a' ha, quotient.sound $
have ⟦(a.hom ≫ f : over Q)⟧ = ⟦a'.hom ≫ f⟧, by convert ha,
match quotient.exact this with ⟨R, p, q, ep, eq, comm⟩ :=
⟨R, p, q, ep, eq, (cancel_mono f).1 $ by { simp only [category.assoc], exact comm }⟩
end
/-- A morphism that is injective on pseudoelements only maps the zero element to zero. -/
lemma zero_of_map_zero {P Q : C} (f : P ⟶ Q) : function.injective f → ∀ a, f a = 0 → a = 0 :=
λ h a ha, by { rw ←apply_zero f at ha, exact h ha }
/-- A morphism that only maps the zero pseudoelement to zero is a monomorphism. -/
theorem mono_of_zero_of_map_zero {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0 → a = 0) → mono f :=
λ h, (mono_iff_cancel_zero _).2 $ λ R g hg, (pseudo_zero_iff (g : over P)).1 $ h _ $
show f g = 0, from (pseudo_zero_iff (g ≫ f : over Q)).2 hg
section
/-- An epimorphism is surjective on pseudoelements. -/
theorem pseudo_surjective_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : function.surjective f :=
λ qbar, quotient.induction_on qbar $ λ q, ⟨((pullback.fst : pullback f q.hom ⟶ P) : over P),
quotient.sound $ ⟨pullback f q.hom, 𝟙 (pullback f q.hom), pullback.snd, by apply_instance,
by apply_instance, by rw [category.id_comp, ←pullback.condition, app_hom, over.coe_hom]⟩⟩
end
/-- A morphism that is surjective on pseudoelements is an epimorphism. -/
theorem epi_of_pseudo_surjective {P Q : C} (f : P ⟶ Q) : function.surjective f → epi f :=
λ h, match h (𝟙 Q) with ⟨pbar, hpbar⟩ :=
match quotient.exists_rep pbar with ⟨p, hp⟩ :=
have ⟦(p.hom ≫ f : over Q)⟧ = ⟦𝟙 Q⟧, by { rw ←hp at hpbar, exact hpbar },
match quotient.exact this with ⟨R, x, y, ex, ey, comm⟩ :=
@epi_of_epi_fac _ _ _ _ _ (x ≫ p.hom) f y ey $
by { dsimp at comm, rw [category.assoc, comm], apply category.comp_id }
end
end
end
section
/-- Two morphisms in an exact sequence are exact on pseudoelements. -/
theorem pseudo_exact_of_exact {P Q R : C} {f : P ⟶ Q} {g : Q ⟶ R} [exact f g] :
(∀ a, g (f a) = 0) ∧ (∀ b, g b = 0 → ∃ a, f a = b) :=
⟨λ a, by { rw [←comp_apply, exact.w], exact zero_apply _ _ },
λ b', quotient.induction_on b' $ λ b hb,
have hb' : b.hom ≫ g = 0, from (pseudo_zero_iff _).1 hb,
begin
-- By exactness, b factors through im f = ker g via some c
obtain ⟨c, hc⟩ := kernel_fork.is_limit.lift' (is_limit_image f g) _ hb',
-- We compute the pullback of the map into the image and c.
-- The pseudoelement induced by the first pullback map will be our preimage.
use (pullback.fst : pullback (images.factor_thru_image f) c ⟶ P),
-- It remains to show that the image of this element under f is pseudo-equal to b.
apply quotient.sound,
-- pullback.snd is an epimorphism because the map onto the image is!
refine ⟨pullback (images.factor_thru_image f) c, 𝟙 _, pullback.snd,
by apply_instance, by apply_instance, _⟩,
-- Now we can verify that the diagram commutes.
calc 𝟙 (pullback (images.factor_thru_image f) c) ≫ pullback.fst ≫ f = pullback.fst ≫ f
: category.id_comp _
... = pullback.fst ≫ images.factor_thru_image f ≫ kernel.ι (cokernel.π f)
: by rw images.image.fac
... = (pullback.snd ≫ c) ≫ kernel.ι (cokernel.π f)
: by rw [←category.assoc, pullback.condition]
... = pullback.snd ≫ b.hom
: by { rw category.assoc, congr' }
end⟩
end
lemma apply_eq_zero_of_comp_eq_zero {P Q R : C} (f : Q ⟶ R) (a : P ⟶ Q) : a ≫ f = 0 → f a = 0 :=
λ h, by simp [over_coe_def, pseudo_apply_mk, over.coe_hom, h]
section
/-- If two morphisms are exact on pseudoelements, they are exact. -/
theorem exact_of_pseudo_exact {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) :
(∀ a, g (f a) = 0) ∧ (∀ b, g b = 0 → ∃ a, f a = b) → exact f g :=
λ ⟨h₁, h₂⟩, (abelian.exact_iff _ _).2 ⟨zero_morphism_ext _ $ λ a, by rw [comp_apply, h₁ a],
begin
-- If we apply g to the pseudoelement induced by its kernel, we get 0 (of course!).
have : g (kernel.ι g) = 0 := apply_eq_zero_of_comp_eq_zero _ _ (kernel.condition _),
-- By pseudo-exactness, we get a preimage.
obtain ⟨a', ha⟩ := h₂ _ this,
obtain ⟨a, ha'⟩ := quotient.exists_rep a',
rw ←ha' at ha,
obtain ⟨Z, r, q, er, eq, comm⟩ := quotient.exact ha,
-- Consider the pullback of kernel.ι (cokernel.π f) and kernel.ι g.
-- The commutative diagram given by the pseudo-equality f a = b induces
-- a cone over this pullback, so we get a factorization z.
obtain ⟨z, hz₁, hz₂⟩ := @pullback.lift' _ _ _ _ _ _ (kernel.ι (cokernel.π f)) (kernel.ι g) _
(r ≫ a.hom ≫ images.factor_thru_image f) q
(by { simp only [category.assoc, images.image.fac], exact comm }),
-- Let's give a name to the second pullback morphism.
let j : pullback (kernel.ι (cokernel.π f)) (kernel.ι g) ⟶ kernel g := pullback.snd,
-- Since q is an epimorphism, in particular this means that j is an epimorphism.
haveI pe : epi j := by exactI epi_of_epi_fac hz₂,
-- But is is also a monomorphism, because kernel.ι (cokernel.π f) is: A kernel is
-- always a monomorphism and the pullback of a monomorphism is a monomorphism.
-- But mono + epi = iso, so j is an isomorphism.
haveI : is_iso j := is_iso_of_mono_of_epi _,
-- But then kernel.ι g can be expressed using all of the maps of the pullback square, and we
-- are done.
rw (iso.eq_inv_comp (as_iso j)).2 pullback.condition.symm,
simp only [category.assoc, kernel.condition, has_zero_morphisms.comp_zero]
end⟩
end
/-- If two pseudoelements `x` and `y` have the same image under some morphism `f`, then we can form
their "difference" `z`. This pseudoelement has the properties that `f z = 0` and for all
morphisms `g`, if `g y = 0` then `g z = g x`. -/
theorem sub_of_eq_image {P Q : C} (f : P ⟶ Q) (x y : P) : f x = f y →
∃ z, f z = 0 ∧ ∀ (R : C) (g : P ⟶ R), (g : P ⟶ R) y = 0 → g z = g x :=
quotient.induction_on₂ x y $ λ a a' h,
match quotient.exact h with ⟨R, p, q, ep, eq, comm⟩ :=
let a'' : R ⟶ P := p ≫ a.hom - q ≫ a'.hom in ⟨a'',
⟨show ⟦((p ≫ a.hom - q ≫ a'.hom) ≫ f : over Q)⟧ = ⟦(0 : Q ⟶ Q)⟧,
by { dsimp at comm, simp [sub_eq_zero.2 comm] },
λ Z g hh,
begin
obtain ⟨X, p', q', ep', eq', comm'⟩ := quotient.exact hh,
have : a'.hom ≫ g = 0,
{ apply (epi_iff_cancel_zero _).1 ep' _ (a'.hom ≫ g),
simpa using comm' },
apply quotient.sound,
-- Can we prevent quotient.sound from giving us this weird `coe_b` thingy?
change app g (a'' : over P) ≈ app g a,
exact ⟨R, 𝟙 R, p, by apply_instance, ep, by simp [sub_eq_add_neg, this]⟩
end⟩⟩
end
variable [limits.has_pullbacks C]
/-- If `f : P ⟶ R` and `g : Q ⟶ R` are morphisms and `p : P` and `q : Q` are pseudoelements such
that `f p = g q`, then there is some `s : pullback f g` such that `fst s = p` and `snd s = q`.
Remark: Borceux claims that `s` is unique. I was unable to transform his proof sketch into
a pen-and-paper proof of this fact, so naturally I was not able to formalize the proof. -/
theorem pseudo_pullback {P Q R : C} {f : P ⟶ R} {g : Q ⟶ R} {p : P} {q : Q} : f p = g q →
∃ s, (pullback.fst : pullback f g ⟶ P) s = p ∧ (pullback.snd : pullback f g ⟶ Q) s = q :=
quotient.induction_on₂ p q $ λ x y h,
begin
obtain ⟨Z, a, b, ea, eb, comm⟩ := quotient.exact h,
obtain ⟨l, hl₁, hl₂⟩ := @pullback.lift' _ _ _ _ _ _ f g _ (a ≫ x.hom) (b ≫ y.hom)
(by { simp only [category.assoc], exact comm }),
exact ⟨l, ⟨quotient.sound ⟨Z, 𝟙 Z, a, by apply_instance, ea, by rwa category.id_comp⟩,
quotient.sound ⟨Z, 𝟙 Z, b, by apply_instance, eb, by rwa category.id_comp⟩⟩⟩
end
end pseudoelement
end category_theory.abelian
|
c95abb95b48cdecadc1c4a77161e377ba07c4f21 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/model_theory/basic.lean | 4b4bcf682c69b094f18ea0ad55cbff5dd5a5294d | [
"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 | 29,884 | lean | /-
Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import category_theory.concrete_category.bundled
import data.fin.tuple.basic
import data.fin.vec_notation
import logic.encodable.basic
import logic.small
import set_theory.cardinal.basic
/-!
# Basics on First-Order Structures
This file defines first-order languages and structures in the style of the
[Flypitch project](https://flypitch.github.io/), as well as several important maps between
structures.
## Main Definitions
* A `first_order.language` defines a language as a pair of functions from the natural numbers to
`Type l`. One sends `n` to the type of `n`-ary functions, and the other sends `n` to the type of
`n`-ary relations.
* A `first_order.language.Structure` interprets the symbols of a given `first_order.language` in the
context of a given type.
* A `first_order.language.hom`, denoted `M →[L] N`, is a map from the `L`-structure `M` to the
`L`-structure `N` that commutes with the interpretations of functions, and which preserves the
interpretations of relations (although only in the forward direction).
* A `first_order.language.embedding`, denoted `M ↪[L] N`, is an embedding from the `L`-structure `M`
to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves
the interpretations of relations in both directions.
* A `first_order.language.elementary_embedding`, denoted `M ↪ₑ[L] N`, is an embedding from the
`L`-structure `M` to the `L`-structure `N` that commutes with the realizations of all formulas.
* A `first_order.language.equiv`, denoted `M ≃[L] N`, is an equivalence from the `L`-structure `M`
to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves
the interpretations of relations in both directions.
## References
For the Flypitch project:
- [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*]
[flypitch_cpp]
- [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of
the continuum hypothesis*][flypitch_itp]
-/
universes u v u' v' w w'
open_locale cardinal
open cardinal
namespace first_order
/-! ### Languages and Structures -/
/-- A first-order language consists of a type of functions of every natural-number arity and a
type of relations of every natural-number arity. -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
structure language :=
(functions : ℕ → Type u) (relations : ℕ → Type v)
/-- Used to define `first_order.language₂`. -/
@[simp] def sequence₂ (a₀ a₁ a₂ : Type u) : ℕ → Type u
| 0 := a₀
| 1 := a₁
| 2 := a₂
| _ := pempty
namespace sequence₂
variables (a₀ a₁ a₂ : Type u)
instance inhabited₀ [h : inhabited a₀] : inhabited (sequence₂ a₀ a₁ a₂ 0) := h
instance inhabited₁ [h : inhabited a₁] : inhabited (sequence₂ a₀ a₁ a₂ 1) := h
instance inhabited₂ [h : inhabited a₂] : inhabited (sequence₂ a₀ a₁ a₂ 2) := h
instance {n : ℕ} : is_empty (sequence₂ a₀ a₁ a₂ (n + 3)) := pempty.is_empty
@[simp] lemma lift_mk {i : ℕ} :
cardinal.lift (# (sequence₂ a₀ a₁ a₂ i)) = # (sequence₂ (ulift a₀) (ulift a₁) (ulift a₂) i) :=
begin
rcases i with (_ | _ | _ | i);
simp only [sequence₂, mk_ulift, mk_fintype, fintype.card_of_is_empty, nat.cast_zero, lift_zero],
end
@[simp] lemma sum_card :
cardinal.sum (λ i, # (sequence₂ a₀ a₁ a₂ i)) = # a₀ + # a₁ + # a₂ :=
begin
rw [sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ],
simp [add_assoc],
end
end sequence₂
namespace language
/-- A constructor for languages with only constants, unary and binary functions, and
unary and binary relations. -/
@[simps] protected def mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) : language :=
⟨sequence₂ c f₁ f₂, sequence₂ pempty r₁ r₂⟩
/-- The empty language has no symbols. -/
protected def empty : language := ⟨λ _, empty, λ _, empty⟩
instance : inhabited language := ⟨language.empty⟩
/-- The sum of two languages consists of the disjoint union of their symbols. -/
protected def sum (L : language.{u v}) (L' : language.{u' v'}) : language :=
⟨λn, L.functions n ⊕ L'.functions n, λ n, L.relations n ⊕ L'.relations n⟩
variable (L : language.{u v})
/-- The type of constants in a given language. -/
@[nolint has_inhabited_instance] protected def «constants» := L.functions 0
@[simp] lemma constants_mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) :
(language.mk₂ c f₁ f₂ r₁ r₂).constants = c :=
rfl
/-- The type of symbols in a given language. -/
@[nolint has_inhabited_instance] def symbols := (Σl, L.functions l) ⊕ (Σl, L.relations l)
/-- The cardinality of a language is the cardinality of its type of symbols. -/
def card : cardinal := # L.symbols
/-- A language is countable when it has countably many symbols. -/
class countable : Prop := (card_le_aleph_0' : L.card ≤ ℵ₀)
lemma card_le_aleph_0 [L.countable] : L.card ≤ ℵ₀ := countable.card_le_aleph_0'
/-- A language is relational when it has no function symbols. -/
class is_relational : Prop :=
(empty_functions : ∀ n, is_empty (L.functions n))
/-- A language is algebraic when it has no relation symbols. -/
class is_algebraic : Prop :=
(empty_relations : ∀ n, is_empty (L.relations n))
/-- A language is countable when it has countably many symbols. -/
class countable_functions : Prop := (card_functions_le_aleph_0' : # (Σ l, L.functions l) ≤ ℵ₀)
lemma card_functions_le_aleph_0 [L.countable_functions] : #(Σ l, L.functions l) ≤ ℵ₀ :=
countable_functions.card_functions_le_aleph_0'
variables {L} {L' : language.{u' v'}}
lemma card_eq_card_functions_add_card_relations :
L.card = cardinal.sum (λ l, (cardinal.lift.{v} (#(L.functions l)))) +
cardinal.sum (λ l, cardinal.lift.{u} (#(L.relations l))) :=
by simp [card, symbols]
instance [L.is_relational] {n : ℕ} : is_empty (L.functions n) := is_relational.empty_functions n
instance [L.is_algebraic] {n : ℕ} : is_empty (L.relations n) := is_algebraic.empty_relations n
instance is_relational_of_empty_functions {symb : ℕ → Type*} : is_relational ⟨λ _, empty, symb⟩ :=
⟨λ _, empty.is_empty⟩
instance is_algebraic_of_empty_relations {symb : ℕ → Type*} : is_algebraic ⟨symb, λ _, empty⟩ :=
⟨λ _, empty.is_empty⟩
instance is_relational_empty : is_relational language.empty :=
language.is_relational_of_empty_functions
instance is_algebraic_empty : is_algebraic language.empty :=
language.is_algebraic_of_empty_relations
instance is_relational_sum [L.is_relational] [L'.is_relational] : is_relational (L.sum L') :=
⟨λ n, sum.is_empty⟩
instance is_algebraic_sum [L.is_algebraic] [L'.is_algebraic] : is_algebraic (L.sum L') :=
⟨λ n, sum.is_empty⟩
instance is_relational_mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
[h0 : is_empty c] [h1 : is_empty f₁] [h2 : is_empty f₂] :
is_relational (language.mk₂ c f₁ f₂ r₁ r₂) :=
⟨λ n, nat.cases_on n h0 (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ _, pempty.is_empty)))⟩
instance is_algebraic_mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
[h1 : is_empty r₁] [h2 : is_empty r₂] :
is_algebraic (language.mk₂ c f₁ f₂ r₁ r₂) :=
⟨λ n, nat.cases_on n pempty.is_empty
(λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ _, pempty.is_empty)))⟩
instance subsingleton_mk₂_functions {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
[h0 : subsingleton c] [h1 : subsingleton f₁] [h2 : subsingleton f₂] {n : ℕ} :
subsingleton ((language.mk₂ c f₁ f₂ r₁ r₂).functions n) :=
nat.cases_on n h0 (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ n, ⟨λ x, pempty.elim x⟩)))
instance subsingleton_mk₂_relations {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
[h1 : subsingleton r₁] [h2 : subsingleton r₂] {n : ℕ} :
subsingleton ((language.mk₂ c f₁ f₂ r₁ r₂).relations n) :=
nat.cases_on n ⟨λ x, pempty.elim x⟩
(λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ n, ⟨λ x, pempty.elim x⟩)))
lemma encodable.countable [h : encodable L.symbols] : L.countable :=
⟨cardinal.encodable_iff.1 ⟨h⟩⟩
@[simp] lemma empty_card : language.empty.card = 0 :=
by simp [card_eq_card_functions_add_card_relations]
instance countable_empty : language.empty.countable :=
⟨by simp⟩
@[priority 100] instance countable.countable_functions [L.countable] : L.countable_functions :=
⟨begin
refine lift_le_aleph_0.1 (trans _ L.card_le_aleph_0),
rw [card, symbols, mk_sum],
exact le_self_add
end⟩
lemma encodable.countable_functions [h : encodable (Σl, L.functions l)] : L.countable_functions :=
⟨cardinal.encodable_iff.1 ⟨h⟩⟩
@[priority 100] instance is_relational.countable_functions [L.is_relational] :
L.countable_functions :=
encodable.countable_functions
@[simp] lemma card_functions_sum (i : ℕ) :
#((L.sum L').functions i) = (#(L.functions i)).lift + cardinal.lift.{u} (#(L'.functions i)) :=
by simp [language.sum]
@[simp] lemma card_relations_sum (i : ℕ) :
#((L.sum L').relations i) = (#(L.relations i)).lift + cardinal.lift.{v} (#(L'.relations i)) :=
by simp [language.sum]
@[simp] lemma card_sum :
(L.sum L').card = cardinal.lift.{max u' v'} L.card + cardinal.lift.{max u v} L'.card :=
begin
simp only [card_eq_card_functions_add_card_relations, card_functions_sum, card_relations_sum,
sum_add_distrib', lift_add, lift_sum, lift_lift],
rw [add_assoc, ←add_assoc (cardinal.sum (λ i, (# (L'.functions i)).lift)),
add_comm (cardinal.sum (λ i, (# (L'.functions i)).lift)), add_assoc, add_assoc]
end
@[simp] lemma card_mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) :
(language.mk₂ c f₁ f₂ r₁ r₂).card =
cardinal.lift.{v} (# c) + cardinal.lift.{v} (# f₁) + cardinal.lift.{v} (# f₂)
+ cardinal.lift.{u} (# r₁) + cardinal.lift.{u} (# r₂) :=
by simp [card_eq_card_functions_add_card_relations, add_assoc]
variables (L) (M : Type w)
/-- A first-order structure on a type `M` consists of interpretations of all the symbols in a given
language. Each function of arity `n` is interpreted as a function sending tuples of length `n`
(modeled as `(fin n → M)`) to `M`, and a relation of arity `n` is a function from tuples of length
`n` to `Prop`. -/
@[ext] class Structure :=
(fun_map : ∀{n}, L.functions n → (fin n → M) → M)
(rel_map : ∀{n}, L.relations n → (fin n → M) → Prop)
variables (N : Type w') [L.Structure M] [L.Structure N]
open Structure
/-- Used for defining `first_order.language.Theory.Model.inhabited`. -/
def trivial_unit_structure : L.Structure unit := ⟨default, default⟩
/-! ### Maps -/
/-- A homomorphism between first-order structures is a function that commutes with the
interpretations of functions and maps tuples in one structure where a given relation is true to
tuples in the second structure where that relation is still true. -/
structure hom :=
(to_fun : M → N)
(map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously)
(map_rel' : ∀{n} (r : L.relations n) x, rel_map r x → rel_map r (to_fun ∘ x) . obviously)
localized "notation A ` →[`:25 L `] ` B := first_order.language.hom L A B" in first_order
/-- An embedding of first-order structures is an embedding that commutes with the
interpretations of functions and relations. -/
@[ancestor function.embedding] structure embedding extends M ↪ N :=
(map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously)
(map_rel' : ∀{n} (r : L.relations n) x, rel_map r (to_fun ∘ x) ↔ rel_map r x . obviously)
localized "notation A ` ↪[`:25 L `] ` B := first_order.language.embedding L A B" in first_order
/-- An equivalence of first-order structures is an equivalence that commutes with the
interpretations of functions and relations. -/
structure equiv extends M ≃ N :=
(map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously)
(map_rel' : ∀{n} (r : L.relations n) x, rel_map r (to_fun ∘ x) ↔ rel_map r x . obviously)
localized "notation A ` ≃[`:25 L `] ` B := first_order.language.equiv L A B" in first_order
variables {L M N} {P : Type*} [L.Structure P] {Q : Type*} [L.Structure Q]
instance : has_coe_t L.constants M :=
⟨λ c, fun_map c default⟩
lemma fun_map_eq_coe_constants {c : L.constants} {x : fin 0 → M} :
fun_map c x = c := congr rfl (funext fin.elim0)
/-- Given a language with a nonempty type of constants, any structure will be nonempty. This cannot
be a global instance, because `L` becomes a metavariable. -/
lemma nonempty_of_nonempty_constants [h : nonempty L.constants] : nonempty M :=
h.map coe
/-- The function map for `first_order.language.Structure₂`. -/
def fun_map₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
(c' : c → M) (f₁' : f₁ → M → M) (f₂' : f₂ → M → M → M) :
∀{n}, (language.mk₂ c f₁ f₂ r₁ r₂).functions n → (fin n → M) → M
| 0 f _ := c' f
| 1 f x := f₁' f (x 0)
| 2 f x := f₂' f (x 0) (x 1)
| (n + 3) f _ := pempty.elim f
/-- The relation map for `first_order.language.Structure₂`. -/
def rel_map₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
(r₁' : r₁ → set M) (r₂' : r₂ → M → M → Prop) :
∀{n}, (language.mk₂ c f₁ f₂ r₁ r₂).relations n → (fin n → M) → Prop
| 0 r _ := pempty.elim r
| 1 r x := (x 0) ∈ r₁' r
| 2 r x := r₂' r (x 0) (x 1)
| (n + 3) r _ := pempty.elim r
/-- A structure constructor to match `first_order.language₂`. -/
protected def Structure.mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
(c' : c → M) (f₁' : f₁ → M → M) (f₂' : f₂ → M → M → M)
(r₁' : r₁ → set M) (r₂' : r₂ → M → M → Prop) :
(language.mk₂ c f₁ f₂ r₁ r₂).Structure M :=
⟨λ _, fun_map₂ c' f₁' f₂', λ _, rel_map₂ r₁' r₂'⟩
namespace Structure
variables {c f₁ f₂ : Type u} {r₁ r₂ : Type v}
variables {c' : c → M} {f₁' : f₁ → M → M} {f₂' : f₂ → M → M → M}
variables {r₁' : r₁ → set M} {r₂' : r₂ → M → M → Prop}
@[simp] lemma fun_map_apply₀ (c₀ : c) {x : fin 0 → M} :
@Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 0 c₀ x = c' c₀ := rfl
@[simp] lemma fun_map_apply₁ (f : f₁) (x : M) :
@Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 1 f (![x]) = f₁' f x := rfl
@[simp] lemma fun_map_apply₂ (f : f₂) (x y : M) :
@Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 2 f (![x,y]) = f₂' f x y := rfl
@[simp] lemma rel_map_apply₁ (r : r₁) (x : M) :
@Structure.rel_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 1 r (![x]) = (x ∈ r₁' r) := rfl
@[simp] lemma rel_map_apply₂ (r : r₂) (x y : M) :
@Structure.rel_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 2 r (![x,y]) = r₂' r x y := rfl
end Structure
/-- `hom_class L F M N` states that `F` is a type of `L`-homomorphisms. You should extend this
typeclass when you extend `first_order.language.hom`. -/
class hom_class (L : out_param language) (F : Type*)
(M N : out_param $ Type*) [fun_like F M (λ _, N)] [L.Structure M] [L.Structure N] :=
(map_fun : ∀ (φ : F) {n} (f : L.functions n) x, φ (fun_map f x) = fun_map f (φ ∘ x))
(map_rel : ∀ (φ : F) {n} (r : L.relations n) x, rel_map r x → rel_map r (φ ∘ x))
/-- `strong_hom_class L F M N` states that `F` is a type of `L`-homomorphisms which preserve
relations in both directions. -/
class strong_hom_class (L : out_param language) (F : Type*) (M N : out_param $ Type*)
[fun_like F M (λ _, N)] [L.Structure M] [L.Structure N] :=
(map_fun : ∀ (φ : F) {n} (f : L.functions n) x, φ (fun_map f x) = fun_map f (φ ∘ x))
(map_rel : ∀ (φ : F) {n} (r : L.relations n) x, rel_map r (φ ∘ x) ↔ rel_map r x)
@[priority 100] instance strong_hom_class.hom_class
{F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [strong_hom_class L F M N] :
hom_class L F M N :=
{ map_fun := strong_hom_class.map_fun,
map_rel := λ φ n R x, (strong_hom_class.map_rel φ R x).2 }
/-- Not an instance to avoid a loop. -/
def hom_class.strong_hom_class_of_is_algebraic [L.is_algebraic]
{F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [hom_class L F M N] :
strong_hom_class L F M N :=
{ map_fun := hom_class.map_fun,
map_rel := λ φ n R x, (is_algebraic.empty_relations n).elim R }
lemma hom_class.map_constants {F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)]
[hom_class L F M N]
(φ : F) (c : L.constants) : φ (c) = c :=
(hom_class.map_fun φ c default).trans (congr rfl (funext default))
namespace hom
instance fun_like : fun_like (M →[L] N) M (λ _, N) :=
{ coe := hom.to_fun,
coe_injective' := λ f g h, by {cases f, cases g, cases h, refl} }
instance hom_class : hom_class L (M →[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel' }
instance [L.is_algebraic] : strong_hom_class L (M →[L] N) M N :=
hom_class.strong_hom_class_of_is_algebraic
instance has_coe_to_fun : has_coe_to_fun (M →[L] N) (λ _, M → N) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe {f : M →[L] N} : f.to_fun = (f : M → N) := rfl
@[ext]
lemma ext ⦃f g : M →[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
fun_like.ext f g h
lemma ext_iff {f g : M →[L] N} : f = g ↔ ∀ x, f x = g x :=
fun_like.ext_iff
@[simp] lemma map_fun (φ : M →[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
hom_class.map_fun φ f x
@[simp] lemma map_constants (φ : M →[L] N) (c : L.constants) : φ c = c :=
hom_class.map_constants φ c
@[simp] lemma map_rel (φ : M →[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r x → rel_map r (φ ∘ x) :=
hom_class.map_rel φ r x
variables (L) (M)
/-- The identity map from a structure to itself -/
@[refl] def id : M →[L] M :=
{ to_fun := id }
variables {L} {M}
instance : inhabited (M →[L] M) := ⟨id L M⟩
@[simp] lemma id_apply (x : M) :
id L M x = x := rfl
/-- Composition of first-order homomorphisms -/
@[trans] def comp (hnp : N →[L] P) (hmn : M →[L] N) : M →[L] P :=
{ to_fun := hnp ∘ hmn,
map_rel' := λ _ _ _ h, by simp [h] }
@[simp] lemma comp_apply (g : N →[L] P) (f : M →[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order homomorphisms is associative. -/
lemma comp_assoc (f : M →[L] N) (g : N →[L] P) (h : P →[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end hom
/-- Any element of a `hom_class` can be realized as a first_order homomorphism. -/
def hom_class.to_hom {F M N} [L.Structure M] [L.Structure N]
[fun_like F M (λ _, N)] [hom_class L F M N] :
F → (M →[L] N) :=
λ φ, ⟨φ, λ _, hom_class.map_fun φ, λ _, hom_class.map_rel φ⟩
namespace embedding
instance embedding_like : embedding_like (M ↪[L] N) M N :=
{ coe := λ f, f.to_fun,
injective' := λ f, f.to_embedding.injective,
coe_injective' := λ f g h, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x end }
instance strong_hom_class : strong_hom_class L (M ↪[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel' }
instance has_coe_to_fun : has_coe_to_fun (M ↪[L] N) (λ _, M → N) :=
fun_like.has_coe_to_fun
@[simp] lemma map_fun (φ : M ↪[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
hom_class.map_fun φ f x
@[simp] lemma map_constants (φ : M ↪[L] N) (c : L.constants) : φ c = c :=
hom_class.map_constants φ c
@[simp] lemma map_rel (φ : M ↪[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (φ ∘ x) ↔ rel_map r x :=
strong_hom_class.map_rel φ r x
/-- A first-order embedding is also a first-order homomorphism. -/
def to_hom : (M ↪[L] N) → M →[L] N := hom_class.to_hom
@[simp]
lemma coe_to_hom {f : M ↪[L] N} : (f.to_hom : M → N) = f := rfl
lemma coe_injective : @function.injective (M ↪[L] N) (M → N) coe_fn
| f g h :=
begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x,
end
@[ext]
lemma ext ⦃f g : M ↪[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
coe_injective (funext h)
lemma ext_iff {f g : M ↪[L] N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
lemma injective (f : M ↪[L] N) : function.injective f := f.to_embedding.injective
/-- In an algebraic language, any injective homomorphism is an embedding. -/
@[simps] def of_injective [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) : M ↪[L] N :=
{ inj' := hf,
map_rel' := λ n r x, strong_hom_class.map_rel f r x,
.. f }
@[simp] lemma coe_fn_of_injective [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) :
(of_injective hf : M → N) = f := rfl
@[simp] lemma of_injective_to_hom [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) :
(of_injective hf).to_hom = f :=
by { ext, simp }
variables (L) (M)
/-- The identity embedding from a structure to itself -/
@[refl] def refl : M ↪[L] M :=
{ to_embedding := function.embedding.refl M }
variables {L} {M}
instance : inhabited (M ↪[L] M) := ⟨refl L M⟩
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of first-order embeddings -/
@[trans] def comp (hnp : N ↪[L] P) (hmn : M ↪[L] N) : M ↪[L] P :=
{ to_fun := hnp ∘ hmn,
inj' := hnp.injective.comp hmn.injective }
@[simp] lemma comp_apply (g : N ↪[L] P) (f : M ↪[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order embeddings is associative. -/
lemma comp_assoc (f : M ↪[L] N) (g : N ↪[L] P) (h : P ↪[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma comp_to_hom (hnp : N ↪[L] P) (hmn : M ↪[L] N) :
(hnp.comp hmn).to_hom = hnp.to_hom.comp hmn.to_hom :=
by { ext, simp only [coe_to_hom, comp_apply, hom.comp_apply] }
end embedding
/-- Any element of an injective `strong_hom_class` can be realized as a first_order embedding. -/
def strong_hom_class.to_embedding {F M N} [L.Structure M] [L.Structure N]
[embedding_like F M N] [strong_hom_class L F M N] :
F → (M ↪[L] N) :=
λ φ, ⟨⟨φ, embedding_like.injective φ⟩,
λ _, strong_hom_class.map_fun φ, λ _, strong_hom_class.map_rel φ⟩
namespace equiv
instance : equiv_like (M ≃[L] N) M N :=
{ coe := λ f, f.to_fun,
inv := λ f, f.inv_fun,
left_inv := λ f, f.left_inv,
right_inv := λ f, f.right_inv,
coe_injective' := λ f g h₁ h₂, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h₁ x,
end, }
instance : strong_hom_class L (M ≃[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel', }
/-- The inverse of a first-order equivalence is a first-order equivalence. -/
@[symm] def symm (f : M ≃[L] N) : N ≃[L] M :=
{ map_fun' := λ n f' x, begin
simp only [equiv.to_fun_as_coe],
rw [equiv.symm_apply_eq],
refine eq.trans _ (f.map_fun' f' (f.to_equiv.symm ∘ x)).symm,
rw [← function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id]
end,
map_rel' := λ n r x, begin
simp only [equiv.to_fun_as_coe],
refine (f.map_rel' r (f.to_equiv.symm ∘ x)).symm.trans _,
rw [← function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id]
end,
.. f.to_equiv.symm }
instance has_coe_to_fun : has_coe_to_fun (M ≃[L] N) (λ _, M → N) :=
fun_like.has_coe_to_fun
@[simp]
lemma apply_symm_apply (f : M ≃[L] N) (a : N) : f (f.symm a) = a := f.to_equiv.apply_symm_apply a
@[simp]
lemma symm_apply_apply (f : M ≃[L] N) (a : M) : f.symm (f a) = a := f.to_equiv.symm_apply_apply a
@[simp] lemma map_fun (φ : M ≃[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
hom_class.map_fun φ f x
@[simp] lemma map_constants (φ : M ≃[L] N) (c : L.constants) : φ c = c :=
hom_class.map_constants φ c
@[simp] lemma map_rel (φ : M ≃[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (φ ∘ x) ↔ rel_map r x :=
strong_hom_class.map_rel φ r x
/-- A first-order equivalence is also a first-order embedding. -/
def to_embedding : (M ≃[L] N) → M ↪[L] N := strong_hom_class.to_embedding
/-- A first-order equivalence is also a first-order homomorphism. -/
def to_hom : (M ≃[L] N) → M →[L] N := hom_class.to_hom
@[simp] lemma to_embedding_to_hom (f : M ≃[L] N) : f.to_embedding.to_hom = f.to_hom := rfl
@[simp]
lemma coe_to_hom {f : M ≃[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl
@[simp] lemma coe_to_embedding (f : M ≃[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl
lemma coe_injective : @function.injective (M ≃[L] N) (M → N) coe_fn :=
fun_like.coe_injective
@[ext]
lemma ext ⦃f g : M ≃[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
coe_injective (funext h)
lemma ext_iff {f g : M ≃[L] N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
lemma bijective (f : M ≃[L] N) : function.bijective f := equiv_like.bijective f
lemma injective (f : M ≃[L] N) : function.injective f := equiv_like.injective f
lemma surjective (f : M ≃[L] N) : function.surjective f := equiv_like.surjective f
variables (L) (M)
/-- The identity equivalence from a structure to itself -/
@[refl] def refl : M ≃[L] M :=
{ to_equiv := equiv.refl M }
variables {L} {M}
instance : inhabited (M ≃[L] M) := ⟨refl L M⟩
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of first-order equivalences -/
@[trans] def comp (hnp : N ≃[L] P) (hmn : M ≃[L] N) : M ≃[L] P :=
{ to_fun := hnp ∘ hmn,
.. (hmn.to_equiv.trans hnp.to_equiv) }
@[simp] lemma comp_apply (g : N ≃[L] P) (f : M ≃[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order homomorphisms is associative. -/
lemma comp_assoc (f : M ≃[L] N) (g : N ≃[L] P) (h : P ≃[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end equiv
/-- Any element of a bijective `strong_hom_class` can be realized as a first_order isomorphism. -/
def strong_hom_class.to_equiv {F M N} [L.Structure M] [L.Structure N]
[equiv_like F M N] [strong_hom_class L F M N] :
F → (M ≃[L] N) :=
λ φ, ⟨⟨φ, equiv_like.inv φ, equiv_like.left_inv φ, equiv_like.right_inv φ⟩,
λ _, hom_class.map_fun φ, λ _, strong_hom_class.map_rel φ⟩
section sum_Structure
variables (L₁ L₂ : language) (S : Type*) [L₁.Structure S] [L₂.Structure S]
instance sum_Structure :
(L₁.sum L₂).Structure S :=
{ fun_map := λ n, sum.elim fun_map fun_map,
rel_map := λ n, sum.elim rel_map rel_map, }
variables {L₁ L₂ S}
@[simp] lemma fun_map_sum_inl {n : ℕ} (f : L₁.functions n) :
@fun_map (L₁.sum L₂) S _ n (sum.inl f) = fun_map f := rfl
@[simp] lemma fun_map_sum_inr {n : ℕ} (f : L₂.functions n) :
@fun_map (L₁.sum L₂) S _ n (sum.inr f) = fun_map f := rfl
@[simp] lemma rel_map_sum_inl {n : ℕ} (R : L₁.relations n) :
@rel_map (L₁.sum L₂) S _ n (sum.inl R) = rel_map R := rfl
@[simp] lemma rel_map_sum_inr {n : ℕ} (R : L₂.relations n) :
@rel_map (L₁.sum L₂) S _ n (sum.inr R) = rel_map R := rfl
end sum_Structure
section empty
section
variables [language.empty.Structure M] [language.empty.Structure N]
@[simp] lemma empty.nonempty_embedding_iff :
nonempty (M ↪[language.empty] N) ↔ cardinal.lift.{w'} (# M) ≤ cardinal.lift.{w} (# N) :=
trans ⟨nonempty.map (λ f, f.to_embedding), nonempty.map (λ f, {to_embedding := f})⟩
cardinal.lift_mk_le'.symm
@[simp] lemma empty.nonempty_equiv_iff :
nonempty (M ≃[language.empty] N) ↔ cardinal.lift.{w'} (# M) = cardinal.lift.{w} (# N) :=
trans ⟨nonempty.map (λ f, f.to_equiv), nonempty.map (λ f, {to_equiv := f})⟩
cardinal.lift_mk_eq'.symm
end
instance empty_Structure : language.empty.Structure M :=
⟨λ _, empty.elim, λ _, empty.elim⟩
instance : unique (language.empty.Structure M) :=
⟨⟨language.empty_Structure⟩, λ a, begin
ext n f,
{ exact empty.elim f },
{ exact subsingleton.elim _ _ },
end⟩
@[priority 100] instance strong_hom_class_empty {F M N} [fun_like F M (λ _, N)] :
strong_hom_class language.empty F M N :=
⟨λ _ _ f, empty.elim f, λ _ _ r, empty.elim r⟩
/-- Makes a `language.empty.hom` out of any function. -/
@[simps] def _root_.function.empty_hom (f : M → N) : (M →[language.empty] N) :=
{ to_fun := f }
/-- Makes a `language.empty.embedding` out of any function. -/
@[simps] def _root_.embedding.empty (f : M ↪ N) : (M ↪[language.empty] N) :=
{ to_embedding := f }
/-- Makes a `language.empty.equiv` out of any function. -/
@[simps] def _root_.equiv.empty (f : M ≃ N) : (M ≃[language.empty] N) :=
{ to_equiv := f }
end empty
end language
end first_order
namespace equiv
open first_order first_order.language first_order.language.Structure
open_locale first_order
variables {L : language} {M : Type*} {N : Type*} [L.Structure M]
/-- A structure induced by a bijection. -/
@[simps] def induced_Structure (e : M ≃ N) : L.Structure N :=
⟨λ n f x, e (fun_map f (e.symm ∘ x)), λ n r x, rel_map r (e.symm ∘ x)⟩
/-- A bijection as a first-order isomorphism with the induced structure on the codomain. -/
@[simps] def induced_Structure_equiv (e : M ≃ N) :
@language.equiv L M N _ (induced_Structure e) :=
{ map_fun' := λ n f x, by simp [← function.comp.assoc e.symm e x],
map_rel' := λ n r x, by simp [← function.comp.assoc e.symm e x],
.. e }
end equiv
|
c7a5d40b23c89f3f54edca86ea7d92fea2e1bec7 | 367134ba5a65885e863bdc4507601606690974c1 | /src/measure_theory/lebesgue_measure.lean | ea3d83cd84ab1bf62d1e52ca970ae8aa73939bd9 | [
"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 | 21,984 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import measure_theory.pi
/-!
# Lebesgue measure on the real line and on `ℝⁿ`
-/
noncomputable theory
open classical set filter
open ennreal (of_real)
open_locale big_operators ennreal
namespace measure_theory
/-!
### Preliminary definitions
-/
/-- Length of an interval. This is the largest monotonic function which correctly
measures all intervals. -/
def lebesgue_length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma lebesgue_length_Ico (a b : ℝ) :
lebesgue_length (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _))
(le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), apply zero_le },
cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂,
exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) :
lebesgue_length s₁ ≤ lebesgue_length s₂ :=
infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩
lemma lebesgue_length_eq_infi_Ioo (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) :=
begin
refine le_antisymm
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _,
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le
(subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _),
rw ← sub_add,
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Ioo (a b : ℝ) :
lebesgue_length (Ioo a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _,
rw lebesgue_length_eq_infi_Ioo (Ioo a b),
refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _),
cases le_or_lt b a with ab ab, {simp [ab]},
cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂,
rw [lebesgue_length_Ico],
exact ennreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_eq_infi_Icc (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) :=
begin
refine le_antisymm _
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩),
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le
(subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _),
rw [← sub_add_eq_add_sub],
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Icc (a b : ℝ) :
lebesgue_length (Icc a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self),
rw lebesgue_length_eq_infi_Icc (Icc a b),
exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp [le_refl]))
end
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s :=
outer_measure.of_function_le _
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) :
(of_real (b - a) : ℝ≥0∞) ≤ ∑' i, of_real (d i - c i) :=
begin
suffices : ∀ (s:finset ℕ) b
(cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)),
(of_real (b - a) : ℝ≥0∞) ≤ ∑ i in s, of_real (d i - c i),
{ rcases compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩,
have e : (⋃ i ∈ (↑hf.to_finset:set ℕ),
Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]},
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa [e]) },
clear ss b,
refine λ s, finset.strong_induction_on s (λ s IH b cv, _),
cases le_total b a with ab ab,
{ rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 ab), exact zero_le _ },
have := cv ⟨ab, le_refl _⟩, simp at this,
rcases this with ⟨i, is, cb, bd⟩,
rw [← finset.insert_erase is] at cv ⊢,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _),
{ refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (le_of_lt bd) _ },
{ rintro x ⟨h₁, h₂⟩,
refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left
(mt and.left (not_lt_of_le h₂)) }
end
@[simp] lemma lebesgue_outer_Icc (a b : ℝ) :
lebesgue_outer (Icc a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length)
(le_binfi $ λ f hf, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ℝ≥0∞) <
lebesgue_length (f i) + ε' i,
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo},
simpa [infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2),
exact lebesgue_length_subadditive (subset.trans hf $
Union_subset_Union $ λ i, (hg i).1)
end
@[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 :=
by simpa using lebesgue_outer_Icc a a
@[simp] lemma lebesgue_outer_Ico (a b : ℝ) :
lebesgue_outer (Ico a b) = of_real (b - a) :=
by rw [← Icc_diff_right, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _),
lebesgue_outer_Icc]
@[simp] lemma lebesgue_outer_Ioo (a b : ℝ) :
lebesgue_outer (Ioo a b) = of_real (b - a) :=
by rw [← Ico_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Ico]
@[simp] lemma lebesgue_outer_Ioc (a b : ℝ) :
lebesgue_outer (Ioc a b) = of_real (b - a) :=
by rw [← Icc_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc]
lemma is_lebesgue_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.measurable_set' (Iio c) :=
outer_measure.of_function_caratheodory $ λ t,
le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin
refine le_trans (add_le_add
(lebesgue_length_mono $ inter_subset_inter_left _ h)
(lebesgue_length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, -sub_eq_add_neg, sub_add_sub_cancel', le_refl],
{ simp [*, ← ennreal.of_real_add, -sub_eq_add_neg, sub_add_sub_cancel', le_refl] },
{ simp only [ennreal.of_real_eq_zero.2 (sub_nonpos.2 (le_trans hbc hca)), zero_add, le_refl] }
end
theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer :=
begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
refine le_infi (λ f, le_infi $ λ hf,
ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ s, f i ⊆ s ∧ measurable_set s ∧
lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i),
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length},
simp only [infi_lt_iff] at this,
rcases this with ⟨a, b, h₁, h₂⟩,
rw ← lebesgue_outer_Ico at h₂,
exact ⟨_, h₁, measurable_set_Ico, le_of_lt $ by simpa using h₂⟩ },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _,
apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _,
exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2)
end
lemma borel_le_lebesgue_measurable : borel ℝ ≤ lebesgue_outer.caratheodory :=
begin
rw real.borel_eq_generate_from_Iio_rat,
refine measurable_space.generate_from_le _,
simp [is_lebesgue_measurable_Iio] { contextual := tt }
end
/-!
### Definition of the Lebesgue measure and lengths of intervals
-/
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
instance real.measure_space : measure_space ℝ :=
⟨{to_outer_measure := lebesgue_outer,
m_Union := λ f hf, lebesgue_outer.Union_eq_of_caratheodory $
λ i, borel_le_lebesgue_measurable _ (hf i),
trimmed := lebesgue_outer_trim }⟩
@[simp] theorem lebesgue_to_outer_measure :
(volume : measure ℝ).to_outer_measure = lebesgue_outer := rfl
end measure_theory
open measure_theory
namespace real
variables {ι : Type*} [fintype ι]
open_locale topological_space
theorem volume_val (s) : volume s = lebesgue_outer s := rfl
instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) :=
⟨lebesgue_outer_singleton⟩
@[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := lebesgue_outer_Ico a b
@[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := lebesgue_outer_Icc a b
@[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := lebesgue_outer_Ioo a b
@[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := lebesgue_outer_Ioc a b
@[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := lebesgue_outer_singleton a
@[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (abs (b - a)) :=
by rw [interval, volume_Icc, max_sub_min_eq_abs]
@[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp
... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self
@[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ :=
by simp [← measure_congr Ioi_ae_eq_Ici]
@[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp
... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self
@[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ :=
by simp [← measure_congr Iio_ae_eq_Iic]
instance locally_finite_volume : locally_finite_measure (volume : measure ℝ) :=
⟨λ x, ⟨Ioo (x - 1) (x + 1),
mem_nhds_sets is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩,
by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩
/-!
### Volume of a box in `ℝⁿ`
-/
lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) :=
begin
rw [← pi_univ_Icc, volume_pi_pi],
{ simp only [real.volume_Icc] },
{ exact λ i, measurable_set_Icc }
end
@[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (Icc a b)).to_real = ∏ i, (b i - a i) :=
by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioo {a b : ι → ℝ} :
volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioc {a b : ι → ℝ} :
volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ico {a b : ι → ℝ} :
volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
/-!
### Images of the Lebesgue measure under translation/multiplication/...
-/
lemma map_volume_add_left (a : ℝ) : measure.map ((+) a) volume = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [measure.map_apply (measurable_add_left a) measurable_set_Ioo, sub_sub_sub_cancel_right]
lemma map_volume_add_right (a : ℝ) : measure.map (+ a) volume = volume :=
by simpa only [add_comm] using real.map_volume_add_left a
lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map ((*) a) volume = volume :=
begin
refine (real.measure_ext_Ioo_rat $ λ p q, _).symm,
cases lt_or_gt_of_ne h with h h,
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h),
measure.map_apply (measurable_mul_left a) measurable_set_Ioo, neg_sub_neg,
← neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub,
mul_div_cancel' _ (ne_of_lt h)] },
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h),
measure.map_apply (measurable_mul_left a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h,
abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] }
end
lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
measure.map ((*) a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul,
← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one,
one_smul] }
lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map (* a) volume = volume :=
by simpa only [mul_comm] using real.smul_map_volume_mul_left h
lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
measure.map (* a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by simpa only [mul_comm] using real.map_volume_mul_left h
@[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure ℝ) = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [show measure.map has_neg.neg volume (Ioo (p : ℝ) q) = _,
from measure.map_apply measurable_neg measurable_set_Ioo]
end real
open_locale topological_space
lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) :
(0 : ℝ≥0∞) < volume {x | p x} :=
begin
rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩,
refine lt_of_lt_of_le _ (measure_mono hs),
simpa [-mem_Ioo] using hx.1.trans hx.2
end
section region_between
open_locale classical
variable {α : Type*}
/-- The region between two real-valued functions on an arbitrary set. -/
def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) :=
{p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)}
lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s.prod univ :=
by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left
variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α}
/-- The region between two measurable functions on a measurable set is measurable. -/
lemma measurable_set_region_between
(hf : measurable f) (hg : measurable g) (hs : measurable_set s) :
measurable_set (region_between f g s) :=
begin
dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and],
refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter
(measurable_set_lt measurable_snd (hg.comp measurable_fst))),
convert hs.prod measurable_set.univ,
simp only [and_true, mem_univ],
end
theorem volume_region_between_eq_lintegral'
(hf : measurable f) (hg : measurable g) (hs : measurable_set s) :
μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ :=
begin
rw measure.prod_apply,
{ have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)})
= s.indicator (λ x, ennreal.of_real (g x - f x)),
{ funext x,
rw indicator_apply,
split_ifs,
{ have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo],
simp only [hx, real.volume_Ioo, sub_zero] },
{ have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h],
simp only [hx, measure_empty] } },
dsimp only [region_between, preimage_set_of_eq],
rw [h, lintegral_indicator];
simp only [hs, pi.sub_apply] },
{ exact measurable_set_region_between hf hg hs },
end
/-- The volume of the region between two almost everywhere measurable functions on a measurable set
can be represented as a Lebesgue integral. -/
theorem volume_region_between_eq_lintegral [sigma_finite μ]
(hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s))
(hs : measurable_set s) :
μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ :=
begin
have h₁ : (λ y, ennreal.of_real ((g - f) y))
=ᵐ[μ.restrict s]
λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) :=
eventually_eq.fun_comp (eventually_eq.sub hg.ae_eq_mk hf.ae_eq_mk) _,
have h₂ : (μ.restrict s).prod volume (region_between f g s) =
(μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s),
{ apply measure_congr,
apply eventually_eq.inter, { refl },
exact eventually_eq.inter
(eventually_eq.comp₂ (ae_eq_comp' measurable_fst hf.ae_eq_mk
measure.prod_fst_absolutely_continuous) _ eventually_eq.rfl)
(eventually_eq.comp₂ eventually_eq.rfl _
(ae_eq_comp' measurable_fst hg.ae_eq_mk measure.prod_fst_absolutely_continuous)) },
rw [lintegral_congr_ae h₁,
← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs],
convert h₂ using 1,
{ rw measure.restrict_prod_eq_prod_univ,
exacts [ (measure.restrict_eq_self_of_subset_of_measurable (hs.prod measurable_set.univ)
(region_between_subset f g s)).symm, hs], },
{ rw measure.restrict_prod_eq_prod_univ,
exacts [(measure.restrict_eq_self_of_subset_of_measurable (hs.prod measurable_set.univ)
(region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm, hs] },
end
theorem volume_region_between_eq_integral' [sigma_finite μ]
(f_int : integrable_on f s μ) (g_int : integrable_on g s μ)
(hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) :
μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) :=
begin
have h : g - f =ᵐ[μ.restrict s] (λ x, nnreal.of_real (g x - f x)),
{ apply hfg.mono,
simp only [nnreal.of_real, max, sub_nonneg, pi.sub_apply],
intros x hx,
split_ifs,
refl },
rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs,
integral_congr_ae h, lintegral_congr_ae,
lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))],
simpa only,
end
/-- If two functions are integrable on a measurable set, and one function is less than
or equal to the other on that set, then the volume of the region
between the two functions can be represented as an integral. -/
theorem volume_region_between_eq_integral [sigma_finite μ]
(f_int : integrable_on f s μ) (g_int : integrable_on g s μ)
(hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) :
μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) :=
volume_region_between_eq_integral' f_int g_int hs
((ae_restrict_iff' hs).mpr (eventually_of_forall hfg))
end region_between
/-
section vitali
def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y :=
⟨x, h, 0, by simp⟩
def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ :=
classical.some (vitali_aux_h x h)
theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 :=
Exists.fst (classical.some_spec (vitali_aux_h x h):_)
theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ q:ℚ, ↑q = x - vitali_aux x h :=
Exists.snd (classical.some_spec (vitali_aux_h x h):_)
def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h}
theorem vitali_nonmeasurable : ¬ null_measurable_set measure_space.μ vitali :=
sorry
end vitali
-/
|
34f65a12498654ef9cdf3a9efcd3560ad39cd187 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/set/pointwise/finite.lean | 48814b4e7cc3f6c608bb3072c88479084fa80a0c | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 3,749 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import data.set.finite
import data.set.pointwise.smul
/-! # Finiteness lemmas for pointwise operations on sets -/
open_locale pointwise
variables {F α β γ : Type*}
namespace set
section has_involutive_inv
variables [has_involutive_inv α] {s : set α}
@[to_additive] lemma finite.inv (hs : s.finite) : s⁻¹.finite :=
hs.preimage $ inv_injective.inj_on _
end has_involutive_inv
section has_mul
variables [has_mul α] {s t : set α}
@[to_additive] lemma finite.mul : s.finite → t.finite → (s * t).finite := finite.image2 _
/-- Multiplication preserves finiteness. -/
@[to_additive "Addition preserves finiteness."]
def fintype_mul [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s * t : set α) :=
set.fintype_image2 _ _ _
end has_mul
section monoid
variables [monoid α] {s t : set α}
@[to_additive]
instance decidable_mem_mul [fintype α] [decidable_eq α] [decidable_pred (∈ s)]
[decidable_pred (∈ t)] :
decidable_pred (∈ s * t) :=
λ _, decidable_of_iff _ mem_mul.symm
@[to_additive]
instance decidable_mem_pow [fintype α] [decidable_eq α] [decidable_pred (∈ s)] (n : ℕ) :
decidable_pred (∈ (s ^ n)) :=
begin
induction n with n ih,
{ simp_rw [pow_zero, mem_one], apply_instance },
{ letI := ih, rw pow_succ, apply_instance }
end
end monoid
section has_smul
variables [has_smul α β] {s : set α} {t : set β}
@[to_additive] lemma finite.smul : s.finite → t.finite → (s • t).finite := finite.image2 _
end has_smul
section has_smul_set
variables [has_smul α β] {s : set β} {a : α}
@[to_additive] lemma finite.smul_set : s.finite → (a • s).finite := finite.image _
end has_smul_set
section vsub
variables [has_vsub α β] {s t : set β}
include α
lemma finite.vsub (hs : s.finite) (ht : t.finite) : set.finite (s -ᵥ t) := hs.image2 _ ht
end vsub
end set
open set
namespace group
variables {G : Type*} [group G] [fintype G] (S : set G)
@[to_additive]
lemma card_pow_eq_card_pow_card_univ [∀ (k : ℕ), decidable_pred (∈ (S ^ k))] :
∀ k, fintype.card G ≤ k → fintype.card ↥(S ^ k) = fintype.card ↥(S ^ (fintype.card G)) :=
begin
have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩,
by_cases hS : S = ∅,
{ refine λ k hk, fintype.card_congr _,
rw [hS, empty_pow (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow (ne_of_gt hG)] },
obtain ⟨a, ha⟩ := set.nonempty_iff_ne_empty.2 hS,
classical!,
have key : ∀ a (s t : set G), (∀ b : G, b ∈ s → a * b ∈ t) → fintype.card s ≤ fintype.card t,
{ refine λ a s t h, fintype.card_le_of_injective (λ ⟨b, hb⟩, ⟨a * b, h b hb⟩) _,
rintro ⟨b, hb⟩ ⟨c, hc⟩ hbc,
exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) },
have mono : monotone (λ n, fintype.card ↥(S ^ n) : ℕ → ℕ) :=
monotone_nat_of_le_succ (λ n, key a _ _ (λ b hb, set.mul_mem_mul ha hb)),
convert card_pow_eq_card_pow_card_univ_aux mono (λ n, set_fintype_card_le_univ (S ^ n))
(λ n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)),
{ simp only [finset.filter_congr_decidable, fintype.card_of_finset] },
replace h : {a} * S ^ n = S ^ (n + 1),
{ refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _),
{ exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl },
{ convert key a (S ^ n) ({a} * S ^ n) (λ b hb, set.mul_mem_mul (set.mem_singleton a) hb) } },
rw [pow_succ', ←h, mul_assoc, ←pow_succ', h],
rintro _ ⟨b, c, hb, hc, rfl⟩,
rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left],
end
end group
|
f0aacf284ff216d58ea170699c8dc456aedc56e8 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/linear/default.lean | 67e77659dc42abb453ad91a6bdb18a02787eec76 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 4,322 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.preadditive
import algebra.module.linear_map
import algebra.invertible
import linear_algebra.basic
import algebra.algebra.basic
/-!
# Linear categories
An `R`-linear category is a category in which `X ⟶ Y` is an `R`-module in such a way that
composition of morphisms is `R`-linear in both variables.
## Implementation
Corresponding to the fact that we need to have an `add_comm_group X` structure in place
to talk about a `module R X` structure,
we need `preadditive C` as a prerequisite typeclass for `linear R C`.
This makes for longer signatures than would be ideal.
## Future work
It would be nice to have a usable framework of enriched categories in which this just became
a category enriched in `Module R`.
-/
universes w v u
open category_theory.limits
open linear_map
namespace category_theory
/-- A category is called `R`-linear if `P ⟶ Q` is an `R`-module such that composition is
`R`-linear in both variables. -/
class linear (R : Type w) [semiring R] (C : Type u) [category.{v} C] [preadditive C] :=
(hom_module : Π X Y : C, module R (X ⟶ Y) . tactic.apply_instance)
(smul_comp' : ∀ (X Y Z : C) (r : R) (f : X ⟶ Y) (g : Y ⟶ Z),
(r • f) ≫ g = r • (f ≫ g) . obviously)
(comp_smul' : ∀ (X Y Z : C) (f : X ⟶ Y) (r : R) (g : Y ⟶ Z),
f ≫ (r • g) = r • (f ≫ g) . obviously)
attribute [instance] linear.hom_module
restate_axiom linear.smul_comp'
restate_axiom linear.comp_smul'
attribute [simp,reassoc] linear.smul_comp
attribute [reassoc, simp] linear.comp_smul -- (the linter doesn't like `simp` on the `_assoc` lemma)
end category_theory
open category_theory
namespace category_theory.linear
variables {C : Type u} [category.{v} C] [preadditive C]
instance preadditive_nat_linear : linear ℕ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_nsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_nsmul g r, }
instance preadditive_int_linear : linear ℤ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_gsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_gsmul g r, }
section End
variables {R : Type w} [comm_ring R] [linear R C]
instance (X : C) : module R (End X) := by { dsimp [End], apply_instance, }
instance (X : C) : algebra R (End X) :=
algebra.of_module (λ r f g, comp_smul _ _ _ _ _ _) (λ r f g, smul_comp _ _ _ _ _ _)
end End
section
variables {R : Type w} [semiring R] [linear R C]
section induced_category
universes u'
variables {C} {D : Type u'} (F : D → C)
instance induced_category.category : linear.{w v} R (induced_category C F) :=
{ hom_module := λ X Y, @linear.hom_module R _ C _ _ _ (F X) (F Y),
smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _,
comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, }
end induced_category
variables (R)
/-- Composition by a fixed left argument as an `R`-linear map. -/
@[simps]
def left_comp {X Y : C} (Z : C) (f : X ⟶ Y) : (Y ⟶ Z) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ g, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
/-- Composition by a fixed right argument as an `R`-linear map. -/
@[simps]
def right_comp (X : C) {Y Z : C} (g : Y ⟶ Z) : (X ⟶ Y) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ f, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
instance {X Y : C} (f : X ⟶ Y) [epi f] (r : R) [invertible r] : epi (r • f) :=
⟨λ R g g' H, begin
rw [smul_comp, smul_comp, ←comp_smul, ←comp_smul, cancel_epi] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
instance {X Y : C} (f : X ⟶ Y) [mono f] (r : R) [invertible r] : mono (r • f) :=
⟨λ R g g' H, begin
rw [comp_smul, comp_smul, ←smul_comp, ←smul_comp, cancel_mono] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
end
section
variables {S : Type w} [comm_semiring S] [linear S C]
/-- Composition as a bilinear map. -/
@[simps]
def comp (X Y Z : C) : (X ⟶ Y) →ₗ[S] ((Y ⟶ Z) →ₗ[S] (X ⟶ Z)) :=
{ to_fun := λ f, left_comp S Z f,
map_add' := by { intros, ext, simp, },
map_smul' := by { intros, ext, simp, }, }
end
end category_theory.linear
|
0099aa895f5c2beb68006071848c5bc5a8d8b0ce | 4727251e0cd73359b15b664c3170e5d754078599 | /test/abel.lean | 5cb28d799f150775f7fd6dc465bda022f11cc7f7 | [
"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 | 909 | lean | import tactic.abel
variables {α : Type*} {a b : α}
example [add_comm_monoid α] : a + (b + a) = a + a + b := by abel
example [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel
example [add_comm_group α] (x : α) : x - 0 = x := by abel
example [add_comm_monoid α] (x : α) : (3 : ℕ) • a = a + (2 : ℕ) • a := by abel
example [add_comm_group α] : (3 : ℤ) • a = a + (2 : ℤ) • a := by abel
example [add_comm_group α] (a b : α) : a-2•b = a -2•b := by abel
example [add_comm_group α] (a : α) : 0 + a = a := by abel1
example [add_comm_group α] (n : ℕ) (a : α) : n • a = n • a := by abel1
example [add_comm_group α] (n : ℕ) (a : α) : 0 + n • a = n • a := by abel1
-- `abel!` should see through terms that are definitionally equal,
def id' (x : α) := x
example [add_comm_group α] : a + b - b - id' a = 0 :=
begin
success_if_fail { abel; done },
abel!
end
|
ab29e6f6ff33e5d4d27a5053e97aec67e51f7227 | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world2/level5.lean | 5c482cf36b12cb2556b4596a425f3281851be2b5 | [] | no_license | kckennylau/natural_number_game | 019f4a5f419c9681e65234ecd124c564f9a0a246 | ad8c0adaa725975be8a9f978c8494a39311029be | refs/heads/master | 1,598,784,137,722 | 1,571,905,156,000 | 1,571,905,156,000 | 218,354,686 | 0 | 0 | null | 1,572,373,319,000 | 1,572,373,318,000 | null | UTF-8 | Lean | false | false | 1,482 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world2.level4 -- hide
namespace mynat -- hide
/-
# World 2 -- Addition World
## Level 5 -- `succ_eq_add_one`
You have these:
* `zero_ne_succ : ∀ (a : mynat), zero ≠ succ(a)`
* `succ_inj : ∀ a b : mynat, succ(a) = succ(b) → a = b`
* `add_zero : ∀ a : mynat, a + 0 = a`
* `add_succ : ∀ a b : mynat, a + succ(b) = succ(a + b)`
* `zero_add : ∀ a : mynat, 0 + a = a`
* `add_assoc : ∀ a b c : mynat, (a + b) + c = a + (b + c)`
* `succ_add : ∀ a b : mynat, succ a + b = succ (a + b)`
* `add_comm : ∀ a b : mynat, a + b = b + a`
-/
/-
Levels 5 and 6 are the two last levels in this world
which you should really do before you go on to multiplication world.
Level 5 involves the number 1. The theorem that 1 = succ(0) is called
`one_eq_succ_zero : 1 = succ(0)`
and you've had it all along -- we just never saw 1 before so
I never mentioned it. When you see a 1 in your goal,
you can write `rw one_eq_succ_zero` to get back
to `0`. This is a good move because 0 is easier to
manipulate than 1 right now, because you have
some theorems about 0 (`zero_add`, `add_zero`) and
no theorems at all which mention 1. Let's prove one now.
-/
/- Theorem
For any natural number $n$, we have
$$ \operatorname{succ}(n) = n+1. $$
-/
theorem succ_eq_add_one (n : mynat) : succ n = n + 1 :=
begin [less_leaky]
rw one_eq_succ_zero,
rw add_succ,
rw add_zero,
refl,
end
end mynat -- hide
|
3c1be4a33d8eaa4c7888dcff20d1e8df9b07957d | a339bc2ac96174381fb610f4b2e1ba42df2be819 | /hott/cubical/square.hlean | 5079e793802d9f9eebfb0a3763433e4ebc458c86 | [
"Apache-2.0"
] | permissive | kalfsvag/lean2 | 25b2dccc07a98e5aa20f9a11229831f9d3edf2e7 | 4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7 | refs/heads/master | 1,610,513,122,164 | 1,483,135,198,000 | 1,483,135,198,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,852 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jakob von Raumer
Squares in a type
-/
import types.eq
open eq equiv is_equiv sigma
namespace eq
variables {A B : Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A}
/-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/
{p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂}
/-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/
{p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄}
/-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/
inductive square {A : Type} {a₀₀ : A}
: Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type :=
ids : square idp idp idp idp
/- square top bottom left right -/
variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁}
{s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃}
definition ids [reducible] [constructor] := @square.ids
definition idsquare [reducible] [constructor] (a : A) := @square.ids A a
definition hrefl [unfold 4] (p : a = a') : square idp idp p p :=
by induction p; exact ids
definition vrefl [unfold 4] (p : a = a') : square p p idp idp :=
by induction p; exact ids
definition hrfl [reducible] [unfold 4] {p : a = a'} : square idp idp p p :=
!hrefl
definition vrfl [reducible] [unfold 4] {p : a = a'} : square p p idp idp :=
!vrefl
definition hdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square idp idp p q :=
by induction r;apply hrefl
definition vdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square p q idp idp :=
by induction r;apply vrefl
definition hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl :=
by cases p; reflexivity
definition vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl :=
by cases p; reflexivity
definition hconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁)
: square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ :=
by induction s₃₁; exact s₁₁
definition vconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃)
: square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) :=
by induction s₁₃; exact s₁₁
definition dconcat [unfold 14] {p₀₀ : a₀₀ = a} {p₂₂ : a = a₂₂}
(s₂₁ : square p₀₀ p₁₂ p₀₁ p₂₂) (s₁₂ : square p₁₀ p₂₂ p₀₀ p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction s₁₂; exact s₂₁
definition hinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ :=
by induction s₁₁;exact ids
definition vinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ :=
by induction s₁₁;exact ids
definition eq_vconcat [unfold 11] {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) :
square p p₁₂ p₀₁ p₂₁ :=
by induction r; exact s₁₁
definition vconcat_eq [unfold 12] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) :
square p₁₀ p p₀₁ p₂₁ :=
by induction r; exact s₁₁
definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) :
square p₁₀ p₁₂ p p₂₁ :=
by induction r; exact s₁₁
definition hconcat_eq [unfold 12] {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) :
square p₁₀ p₁₂ p₀₁ p :=
by induction r; exact s₁₁
infix ` ⬝h `:75 := hconcat --type using \tr
infix ` ⬝v `:75 := vconcat --type using \tr
infix ` ⬝hp `:75 := hconcat_eq --type using \tr
infix ` ⬝vp `:75 := vconcat_eq --type using \tr
infix ` ⬝ph `:75 := eq_hconcat --type using \tr
infix ` ⬝pv `:75 := eq_vconcat --type using \tr
postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h
postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v
definition transpose [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ :=
by induction s₁₁;exact ids
definition aps [unfold 12] (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) :=
by induction s₁₁;exact ids
/- canceling, whiskering and moving thinks along the sides of the square -/
definition whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ :=
by induction s₁₁;induction p;constructor
definition whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) :=
by induction p;exact s₁₁
definition whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) :=
by induction s₁₁;induction p;constructor
definition whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) :=
by induction s₁₁;induction p;constructor
definition whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ :=
by induction s₁₁;induction p;constructor
definition whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ :=
by induction s₁₁;induction p;constructor
definition cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite +idp_con at s₁₁; exact s₁₁
definition cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p;exact s₁₁
definition cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite idp_con at s₁₁; exact s₁₁
definition cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁
definition cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite idp_con at s₁₁; exact s₁₁
definition cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁
definition move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁)
: square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ :=
by apply cancel_tl p; rewrite con_inv_cancel_left; exact s
definition move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁)
: square (p ⬝ p₁₀) p₁₂ q p₂₁ :=
by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s
definition move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁)
: square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ :=
by apply cancel_tl p; rewrite con_inv_cancel_left; exact s
definition move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁)
: square q p₁₂ (p ⬝ p₀₁) p₂₁ :=
by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s
definition move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q))
: square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p :=
by apply cancel_br q; rewrite inv_con_cancel_right; exact s
definition move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹))
: square p₁₀ (p₁₂ ⬝ q) p₀₁ p :=
by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s
definition move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁)
: square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) :=
by apply cancel_br q; rewrite inv_con_cancel_right; exact s
definition move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁)
: square p₁₀ p p₀₁ (p₂₁ ⬝ q) :=
by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s
definition move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q))
: square (p₁₀ ⬝ p) p₁₂ p₀₁ q :=
by apply cancel_rt p; rewrite con_inv_cancel_right; exact s
definition move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁)
: square p p₁₂ p₀₁ (q ⬝ p₂₁) :=
by apply cancel_tr q; rewrite inv_con_cancel_left; exact s
definition move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁)
: square p₁₀ (q ⬝ p₁₂) p p₂₁ :=
by apply cancel_lb q; rewrite inv_con_cancel_left; exact s
definition move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁)
: square p₁₀ q (p₀₁ ⬝ p) p₂₁ :=
by apply cancel_bl p; rewrite con_inv_cancel_right; exact s
/- some higher ∞-groupoid operations -/
definition vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: s₁₁ ⬝v vrefl p₁₂ = s₁₁ :=
by induction s₁₁; reflexivity
definition hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: s₁₁ ⬝h hrefl p₂₁ = s₁₁ :=
by induction s₁₁; reflexivity
/- equivalences -/
definition eq_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ :=
by induction s₁₁; apply idp
definition square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₁₂; esimp at r; induction r; induction p₂₁; induction p₁₀; exact ids
definition eq_top_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ :=
by induction s₁₁; apply idp
definition square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₂₁; induction p₁₂; esimp at r;induction r;induction p₁₀;exact ids
definition eq_bot_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ :=
by induction s₁₁; apply idp
definition square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₂₁; induction p₁₀; esimp at r; induction r; induction p₀₁; exact ids
definition square_equiv_eq [constructor] (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂)
(l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b :=
begin
fapply equiv.MK,
{ exact eq_of_square},
{ exact square_of_eq},
{ intro s, induction b, esimp [concat] at s, induction s, induction r, induction t, apply idp},
{ intro s, induction s, apply idp},
end
definition hdeg_square_equiv' [constructor] (p q : a = a') : square idp idp p q ≃ p = q :=
by transitivity _;apply square_equiv_eq;transitivity _;apply eq_equiv_eq_symm;
apply equiv_eq_closed_right;apply idp_con
definition vdeg_square_equiv' [constructor] (p q : a = a') : square p q idp idp ≃ p = q :=
by transitivity _;apply square_equiv_eq;apply equiv_eq_closed_right; apply idp_con
definition eq_of_hdeg_square [reducible] {p q : a = a'} (s : square idp idp p q) : p = q :=
to_fun !hdeg_square_equiv' s
definition eq_of_vdeg_square [reducible] {p q : a = a'} (s : square p q idp idp) : p = q :=
to_fun !vdeg_square_equiv' s
definition top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃)
: square (l ⬝ b ⬝ r⁻¹) b l r :=
by induction r;induction b;induction l;constructor
definition bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄)
: square t (l⁻¹ ⬝ t ⬝ r) l r :=
by induction r;induction t;induction l;constructor
/-
the following two equivalences have as underlying inverse function the functions
hdeg_square and vdeg_square, respectively.
See example below the definition
-/
definition hdeg_square_equiv [constructor] (p q : a = a') :
square idp idp p q ≃ p = q :=
begin
fapply equiv_change_fun,
{ fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square,
intro s, induction s, induction p, reflexivity},
{ exact eq_of_hdeg_square},
{ reflexivity}
end
definition vdeg_square_equiv [constructor] (p q : a = a') :
square p q idp idp ≃ p = q :=
begin
fapply equiv_change_fun,
{ fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square,
intro s, induction s, induction p, reflexivity},
{ exact eq_of_vdeg_square},
{ reflexivity}
end
example (p q : a = a') : to_inv (hdeg_square_equiv p q) = hdeg_square := idp
/-
characterization of pathovers in a equality type. The type B of the equality is fixed here.
A version where B may also varies over the path p is given in the file squareover
-/
definition eq_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'}
(s : square q r (ap f p) (ap g p)) : q =[p] r :=
by induction p;apply pathover_idp_of_eq;exact eq_of_vdeg_square s
definition eq_pathover_constant_left {g : A → B} {p : a = a'} {b : B} {q : b = g a} {r : b = g a'}
(s : square q r idp (ap g p)) : q =[p] r :=
eq_pathover (ap_constant p b ⬝ph s)
definition eq_pathover_id_left {g : A → A} {p : a = a'} {q : a = g a} {r : a' = g a'}
(s : square q r p (ap g p)) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s)
definition eq_pathover_constant_right {f : A → B} {p : a = a'} {b : B} {q : f a = b} {r : f a' = b}
(s : square q r (ap f p) idp) : q =[p] r :=
eq_pathover (s ⬝hp (ap_constant p b)⁻¹)
definition eq_pathover_id_right {f : A → A} {p : a = a'} {q : f a = a} {r : f a' = a'}
(s : square q r (ap f p) p) : q =[p] r :=
eq_pathover (s ⬝hp (ap_id p)⁻¹)
definition square_of_pathover [unfold 7]
{f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'}
(s : q =[p] r) : square q r (ap f p) (ap g p) :=
by induction p;apply vdeg_square;exact eq_of_pathover_idp s
definition eq_pathover_constant_left_id_right {p : a = a'} {a₀ : A} {q : a₀ = a} {r : a₀ = a'}
(s : square q r idp p) : q =[p] r :=
eq_pathover (ap_constant p a₀ ⬝ph s ⬝hp (ap_id p)⁻¹)
definition eq_pathover_id_left_constant_right {p : a = a'} {a₀ : A} {q : a = a₀} {r : a' = a₀}
(s : square q r p idp) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹)
definition loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹)
/- interaction of equivalences with operations on squares -/
definition eq_pathover_equiv_square [constructor] {f g : A → B}
(p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p] r ≃ square q r (ap f p) (ap g p) :=
equiv.MK square_of_pathover
eq_pathover
begin
intro s, induction p, esimp [square_of_pathover,eq_pathover],
exact ap vdeg_square (to_right_inv !pathover_idp (eq_of_vdeg_square s))
⬝ to_left_inv !vdeg_square_equiv s
end
begin
intro s, induction p, esimp [square_of_pathover,eq_pathover],
exact ap pathover_idp_of_eq (to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s))
⬝ to_left_inv !pathover_idp s
end
definition square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a}
{r : f a' = g a'} (s' : q = q') (s : q' =[p] r)
: square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s :=
by induction s;induction s';reflexivity
definition square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a}
{r r' : f a' = g a'} (s' : r = r') (s : q =[p] r)
: square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' :=
by induction s;induction s';reflexivity
definition square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a}
{q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p] q') (s' : q' =[p'] q'')
: square_of_pathover (s ⬝o s')
= ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ :=
by induction s';induction s;esimp [ap_con,hconcat_eq];exact !vconcat_vrfl⁻¹
definition eq_of_square_hrfl [unfold 4] (p : a = a') : eq_of_square hrfl = idp_con p :=
by induction p;reflexivity
definition eq_of_square_vrfl [unfold 4] (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ :=
by induction p;reflexivity
definition eq_of_square_hdeg_square {p q : a = a'} (r : p = q)
: eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ :=
by induction r;induction p;reflexivity
definition eq_of_square_vdeg_square {p q : a = a'} (r : p = q)
: eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ :=
by induction r;induction p;reflexivity
definition eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: eq_of_square (r ⬝pv s₁₁) = whisker_right p₂₁ r ⬝ eq_of_square s₁₁ :=
by induction s₁₁;cases r;reflexivity
definition eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right p₁₂ r)⁻¹ :=
by induction r;reflexivity
definition eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p)
: eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r :=
by induction r;reflexivity
definition eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p)
: eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ :=
by induction s₁₁; induction r;reflexivity
-- definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) :
-- square p₁₀ p p₀₁ p₂₁ :=
-- by induction r; exact s₁₁
-- definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁)
-- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ :=
-- by induction r; exact s₁₁
-- definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂}
-- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p :=
-- by induction r; exact s₁₁
-- the following definition is very slow, maybe it's interesting to see why?
-- definition eq_pathover_equiv_square' {f g : A → B}(p : a = a') (q : f a = g a) (r : f a' = g a')
-- : square q r (ap f p) (ap g p) ≃ q =[p] r :=
-- equiv.MK eq_pathover
-- square_of_pathover
-- (λs, begin
-- induction p, rewrite [↑[square_of_pathover,eq_pathover],
-- to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s),
-- to_left_inv !pathover_idp s]
-- end)
-- (λs, begin
-- induction p, rewrite [↑[square_of_pathover,eq_pathover],▸*,
-- to_right_inv !(@pathover_idp A) (eq_of_vdeg_square s),
-- to_left_inv !vdeg_square_equiv s]
-- end)
/- recursors for squares where some sides are reflexivity -/
definition rec_on_b [recursor] {a₀₀ : A}
{P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type}
{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}
(s : square t idp l r) (H : P ids) : P s :=
have H2 : P (square_of_eq (eq_of_square s)),
from eq.rec_on (eq_of_square s : t ⬝ r = l) (by induction r; induction t; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ H2
definition rec_on_r [recursor] {a₀₀ : A}
{P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type}
{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}
(s : square t b l idp) (H : P ids) : P s :=
let p : l ⬝ b = t := (eq_of_square s)⁻¹ in
have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹),
from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ !inv_inv ▸ H2
definition rec_on_l [recursor] {a₀₁ : A}
{P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂},
square t b idp r → Type}
{a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}
(s : square t b idp r) (H : P ids) : P s :=
let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in
have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)),
from eq.rec_on p (by induction r; induction t; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ !con_inv_cancel_right ▸ H2
definition rec_on_t [recursor] {a₁₀ : A}
{P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type}
{a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}
(s : square idp b l r) (H : P ids) : P s :=
let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in
have H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)),
from eq.rec_on p (by induction b; induction l; exact H),
have H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)),
from eq.rec_on !con_inv_cancel_right H2,
have H4 : P (square_of_eq (eq_of_square s)),
from eq.rec_on !inv_inv H3,
proof
left_inv (to_fun !square_equiv_eq) s ▸ H4
qed
definition rec_on_tb [recursor] {a : A}
{P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type}
{b : A} {l : a = b} {r : a = b}
(s : square idp idp l r) (H : P ids) : P s :=
have H2 : P (square_of_eq (eq_of_square s)),
from eq.rec_on (eq_of_square s : idp ⬝ r = l) (by induction r; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ H2
definition rec_on_lr [recursor] {a : A}
{P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type}
{a' : A} {t : a = a'} {b : a = a'}
(s : square t b idp idp) (H : P ids) : P s :=
let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in
have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹),
from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H),
to_left_inv (!square_equiv_eq) s ▸ !inv_inv ▸ H2
--we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed
definition whisker_square [unfold 14 15 16 17] (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂')
(r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀' p₁₂' p₀₁' p₂₁' :=
by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s
/- squares commute with some operations on 2-paths -/
definition square_inv2 {p₁ p₂ p₃ p₄ : a = a'}
{t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r)
: square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) :=
by induction s;constructor
definition square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃}
{t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄}
{t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄}
(s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂)
: square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) :=
by induction s₂;induction s₁;constructor
open is_trunc
definition is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ :=
square_of_eq !is_set.elim
definition is_trunc_square [instance] (n : trunc_index) [H : is_trunc n .+2 A]
: is_trunc n (square p₁₀ p₁₂ p₀₁ p₂₁) :=
is_trunc_equiv_closed_rev n !square_equiv_eq
-- definition square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂}
-- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄}
-- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp)
-- : square t b l r :=
-- sorry --by induction s
/- Square fillers -/
-- TODO replace by "more algebraic" fillers?
variables (p₁₀ p₁₂ p₀₁ p₂₁)
definition square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ :=
by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩
definition square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ :=
by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩
definition square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ :=
by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩
definition square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p :=
by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩
/- Squares having an 'ap' term on one face -/
--TODO find better names
definition square_Flr_ap_idp {c : B} {f : A → B} (p : Π a, f a = c)
{a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp :=
by induction q; apply vrfl
definition square_Flr_idp_ap {c : B} {f : A → B} (p : Π a, c = f a)
{a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) :=
by induction q; apply vrfl
definition square_ap_idp_Flr {b : B} {f : A → B} (p : Π a, f a = b)
{a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) :=
by induction q; apply hrfl
/- Matching eq_hconcat with hconcat etc. -/
-- TODO maybe rename hconcat_eq and the like?
variable (s₁₁)
definition ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) :
r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con :=
by cases r; cases s₁₁; esimp
definition hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) :
hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ :=
by cases r; cases s₁₁; esimp
definition hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) :
s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r :=
by cases r; cases s₁₁; esimp
definition pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) :
r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con :=
by cases r; cases s₁₁; esimp
definition vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) :
vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ :=
by cases r; cases s₁₁; esimp
definition vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) :
s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r :=
by cases r; cases s₁₁; esimp
definition natural_square [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') :
square (p a) (p a') (ap f q) (ap g q) :=
square_of_pathover (apd p q)
definition natural_square_tr [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') :
square (ap f q) (ap g q) (p a) (p a') :=
transpose (natural_square p q)
definition natural_square011 {A A' : Type} {B : A → Type}
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b')
{l r : Π⦃a⦄, B a → A'} (g : Π⦃a⦄ (b : B a), l b = r b)
: square (apd011 l p q) (apd011 r p q) (g b) (g b') :=
begin
induction q, exact hrfl
end
definition natural_square0111' {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'}
{c : C b} {c' : C b'} (s : c =[apd011 C p q] c')
{l r : Π⦃a⦄ {b : B a}, C b → A'}
(g : Π⦃a⦄ {b : B a} (c : C b), l c = r c)
: square (apd0111 l p q s) (apd0111 r p q s) (g c) (g c') :=
begin
induction q, esimp at s, induction s using idp_rec_on, exact hrfl
end
-- this can be generalized a bit, by making the domain and codomain of k different, and also have
-- a function at the RHS of s (similar to m)
definition natural_square0111 {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'}
{c : C b} {c' : C b'} (r : c =[apd011 C p q] c')
{k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b))
{f : Π⦃a⦄ {b : B a}, C b → A'}
(s : Π⦃a⦄ {b : B a} (c : C b), f (m c) = f c)
: square (apd0111 (λa b c, f (m c)) p q r) (apd0111 f p q r) (s c) (s c') :=
begin
induction q, esimp at r, induction r using idp_rec_on, exact hrfl
end
end eq
|
8e3e7463ad75304be9d264425f0d61f65b7ef3f8 | 1169362316cbb36a5f4ae286e8419e4e5163f569 | /src/misc/encodable2.lean | 43cf75efe2147fb110c9cf0f6f0bd5c9498fac02 | [] | no_license | fpvandoorn/formal_logic | 21687f7e621fdd9124a06a5b3a5a9c5a6ae40cc6 | adbe6d70399310842525ff05ff97e29f30dd4282 | refs/heads/master | 1,585,666,688,414 | 1,539,046,655,000 | 1,539,046,655,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,474 | lean | import data.encodable data.fin
/-
`Wfin α ar` is the type of finitely branching trees with labels from α, where
a node labeled `a` has `ar a` children.
-/
inductive Wfin {α : Type*} (ar : α → ℕ)
| mk (a : α) (f : fin (ar a) → Wfin) : Wfin
namespace Wfin
variables {α : Type*} {ar : α → ℕ}
def depth : Wfin ar → ℕ
| ⟨a, f⟩ := finset.sup finset.univ (λ n, depth (f n)) + 1
def not_depth_le_zero (t : Wfin ar) : ¬ t.depth ≤ 0 :=
by { cases t, apply nat.not_succ_le_zero }
lemma depth_lt_depth_mk (a : α) (f : fin (ar a) → Wfin ar) (i : fin (ar a)) :
depth (f i) < depth ⟨a, f⟩ :=
nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i))
end Wfin
/-
Show `Wfin` types are encodable.
-/
namespace encodable
@[reducible] private def Wfin' {α : Type*} (ar : α → ℕ) (n : ℕ) :=
{ t : Wfin ar // t.depth ≤ n}
variables {α : Type*} {ar : α → ℕ}
private def encodable_zero : encodable (Wfin' ar 0) :=
let f : Wfin' ar 0 → empty := λ ⟨x, h⟩, absurd h (Wfin.not_depth_le_zero _),
finv : empty → Wfin' ar 0 := by { intro x, cases x} in
have ∀ x, finv (f x) = x, from λ ⟨x, h⟩, absurd h (Wfin.not_depth_le_zero _),
encodable.of_left_inverse f finv this
private def f (n : ℕ) : Wfin' ar (n + 1) → Σ a : α, fin (ar a) → Wfin' ar n
| ⟨t, h⟩ :=
begin
cases t with a f,
have h₀ : ∀ i : fin (ar a), Wfin.depth (f i) ≤ n,
from λ i, nat.le_of_lt_succ (lt_of_lt_of_le (Wfin.depth_lt_depth_mk a f i) h),
exact ⟨a, λ i : fin (ar a), ⟨f i, h₀ i⟩⟩
end
private def finv (n : ℕ) :
(Σ a : α, fin (ar a) → Wfin' ar n) → Wfin' ar (n + 1)
| ⟨a, f⟩ :=
let f' := λ i : fin (ar a), (f i).val in
have Wfin.depth ⟨a, f'⟩ ≤ n + 1,
from add_le_add_right (finset.sup_le (λ b h, (f b).2)) 1,
⟨⟨a, f'⟩, this⟩
variable [encodable α]
private def encodable_succ (n : nat) (h : encodable (Wfin' ar n)) :
encodable (Wfin' ar (n + 1)) :=
encodable.of_left_inverse (f n) (finv n)
(by { intro t, cases t with t h, cases t with a fn, reflexivity })
instance : encodable (Wfin ar) :=
begin
haveI h' : Π n, encodable (Wfin' ar n) :=
λ n, nat.rec_on n encodable_zero encodable_succ,
let f : Wfin ar → Σ n, Wfin' ar n := λ t, ⟨t.depth, ⟨t, le_refl _⟩⟩,
let finv : (Σ n, Wfin' ar n) → Wfin ar := λ p, p.2.1,
have : ∀ t, finv (f t) = t, from λ t, rfl,
exact encodable.of_left_inverse f finv this
end
end encodable
/-
Make it easier to construct funtions from a small `fin`.
-/
namespace fin
variable {α : Type*}
def mk_fn0 : fin 0 → α
| ⟨_, h⟩ := absurd h dec_trivial
def mk_fn1 (t : α) : fin 1 → α
| ⟨0, _⟩ := t
| ⟨n+1, h⟩ := absurd h dec_trivial
def mk_fn2 (s t : α) : fin 2 → α
| ⟨0, _⟩ := s
| ⟨1, _⟩ := t
| ⟨n+2, h⟩ := absurd h dec_trivial
attribute [simp] mk_fn0 mk_fn1 mk_fn2
end fin
/-
Show propositional formulas are encodable.
-/
inductive prop_form (α : Type*)
| var : α → prop_form
| not : prop_form → prop_form
| and : prop_form → prop_form → prop_form
| or : prop_form → prop_form → prop_form
namespace prop_form
private def constructors (α : Type*) := α ⊕ unit ⊕ unit ⊕ unit
local notation `cvar` a := sum.inl a
local notation `cnot` := sum.inr (sum.inl unit.star)
local notation `cand` := sum.inr (sum.inr (sum.inr unit.star))
local notation `cor` := sum.inr (sum.inr (sum.inl unit.star))
@[simp]
private def arity (α : Type*) : constructors α → nat
| (cvar a) := 0
| cnot := 1
| cand := 2
| cor := 2
variable {α : Type*}
private def f : prop_form α → Wfin (arity α)
| (var a) := ⟨cvar a, fin.mk_fn0⟩
| (not p) := ⟨cnot, fin.mk_fn1 (f p)⟩
| (and p q) := ⟨cand, fin.mk_fn2 (f p) (f q)⟩
| (or p q) := ⟨cor, fin.mk_fn2 (f p) (f q)⟩
private def finv : Wfin (arity α) → prop_form α
| ⟨cvar a, fn⟩ := var a
| ⟨cnot, fn⟩ := not (finv (fn ⟨0, dec_trivial⟩))
| ⟨cand, fn⟩ := and (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩))
| ⟨cor, fn⟩ := or (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩))
instance [encodable α] : encodable (prop_form α) :=
begin
haveI : encodable (constructors α) :=
by { unfold constructors, apply_instance },
exact encodable.of_left_inverse f finv
(by { intro p, induction p; simp [f, finv, *] })
end
end prop_form
|
c88e45eb1072afc19df36cd82183f6a3b5399c8f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /archive/imo/imo1998_q2.lean | 3c897525b8abeef689ca78b1f3189b00a529f0f4 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 9,518 | 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 data.fintype.basic
import data.int.parity
import algebra.big_operators.order
import tactic.ring
import tactic.noncomm_ring
/-!
# IMO 1998 Q2
In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each
judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any
two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`.
## Solution
The problem asks us to think about triples consisting of a contestant and two judges whose ratings
agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of
agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We
have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as
the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the
fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`,
and a lower bound from the count for `left`. These two bounds combine to the required result.
First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded
by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`.
Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of
ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this
fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as
evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size
`(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain
the lower bound: `a(b-1)^2/2 ≤ |A|`.
Rearranging gives the result.
-/
open_locale classical
noncomputable theory
/-- An ordered pair of judges. -/
abbreviation judge_pair (J : Type*) := J × J
/-- A triple consisting of contestant together with an ordered pair of judges. -/
abbreviation agreed_triple (C J : Type*) := C × (judge_pair J)
variables {C J : Type*} (r : C → J → Prop)
/-- The first judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst
/-- The second judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd
/-- The proposition that the judges in an ordered pair are distinct. -/
abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂
/-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/
abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂
/-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/
abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst
/-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of
judges. -/
abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd
@[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) :
p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl
/-- The set of contestants on which two judges agree. -/
def agreed_contestants [fintype C] (p : judge_pair J) : finset C :=
finset.univ.filter (λ c, p.agree r c)
section
variables [fintype J] [fintype C]
/-- All incidences of agreement. -/
def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J),
a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct)
lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) :
a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) :=
by simp [A, finset.mem_off_diag]
lemma A_fibre_over_contestant (c : C) :
finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd :=
begin
ext p,
simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop],
split,
{ rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, },
{ intros h, finish, },
end
lemma A_fibre_over_contestant_card (c : C) :
(finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card :=
by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, }
lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) :
agreed_contestants r p =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant :=
begin
dunfold A agreed_contestants, ext c, split; intros h,
{ rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, },
{ finish, },
end
lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) :
(agreed_contestants r p).card =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card :=
by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, }
lemma A_card_upper_bound
{k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) :=
begin
change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )),
rw ← finset.off_diag_card,
apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r),
intros p hp,
have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, },
rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp',
end
end
lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) :
(x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y :=
by noncomm_ring
lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) :
2*z*z + 2*z + 1 ≤ x*x + y*y :=
begin
suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y,
{ rw ← mul_le_mul_left (@zero_lt_two _ _ int.nontrivial), convert this; ring, },
have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, },
rw [← add_sq_add_sq_sub, h', add_le_add_iff_left],
suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, },
rw [mul_self_pos, sub_ne_zero], apply int.ne_of_odd_add ⟨z, h⟩,
end
section
variables [fintype J]
lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card :=
begin
let x := (finset.univ.filter (λ j, r c j)).card,
let y := (finset.univ.filter (λ j, ¬ r c j)).card,
have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y,
{ simp [← finset.filter_product_card], },
rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul],
apply norm_bound_of_odd_sum,
suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], },
rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl,
end
lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card :=
begin
let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c),
let t := finset.univ.filter (λ (p : judge_pair J), p.distinct),
have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, },
have hst : s \ t = finset.univ.diag,
{ ext p, split; intros,
{ finish, },
{ suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, },
have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, },
rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff],
{ rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, },
{ apply finset.sdiff_subset, },
end
lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) :
2*z*z * (fintype.card C) ≤ (A r).card :=
begin
have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, },
apply finset.mul_card_image_le_card_of_maps_to h,
intros c hc,
rw ← A_fibre_over_contestant_card,
apply distinct_judge_pairs_card_lower_bound r hJ,
end
end
lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) :
(b - 1 : ℚ) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) :=
by rw div_le_div_iff; norm_cast; simp [ha, hb]
theorem imo1998_q2 [fintype J] [fintype C]
(a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b)
(hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(b - 1 : ℚ) / (2 * b) ≤ k / a :=
begin
rw clear_denominators ha hb.pos,
obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz,
have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk),
rw [hC, hJ] at h,
-- We are now essentially done; we just need to bash `h` into exactly the right shape.
have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z,
{ simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, },
have hr : 2 * z * z * a = 2 * z * a * z, { ring, },
rw [hl, hr] at h,
cases z,
{ simp, },
{ exact le_of_mul_le_mul_right h z.succ_pos, },
end
|
73f600c427601e31ec75bd215a3ef5c5368bb093 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/quote1.lean | e4b633f5524b00b9d07b8ccacec8a682f2709bfb | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 303 | lean | open tactic list
meta definition foo (a : pexpr) : pexpr :=
`(%%a + %%a + %%a + b)
example (a b : nat) : a = a :=
by do
a ← get_local `a,
t1 ← mk_app `add [a, a],
t2 ← to_expr (foo (to_pexpr t1)),
trace t2,
r ← mk_app (`eq.refl) [a],
exact r
private def f := unit
check ``f
|
09b4a196afa89b90640815cbaa1c43ef1b8cdc92 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/types.lean | d5a418ecfa63aa669c78abc78eb3abb78be3f291 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 10,625 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl
-/
import category_theory.fully_faithful
import data.equiv.basic
/-!
# The category `Type`.
In this section we set up the theory so that Lean's types and functions between them
can be viewed as a `large_category` in our framework.
Lean can not transparently view a function as a morphism in this category,
and needs a hint in order to be able to type check.
We provide the abbreviation `as_hom f` to guide type checking,
as well as a corresponding notation `↾ f`. (Entered as `\upr `.)
We provide various simplification lemmas for functors and natural transformations valued in `Type`.
We define `ulift_functor`, from `Type u` to `Type (max u v)`, and show that it is fully faithful
(but not, of course, essentially surjective).
We prove some basic facts about the category `Type`:
* epimorphisms are surjections and monomorphisms are injections,
* `iso` is both `iso` and `equiv` to `equiv` (at least within a fixed universe),
* every type level `is_lawful_functor` gives a categorical functor `Type ⥤ Type`
(the corresponding fact about monads is in `src/category_theory/monad/types.lean`).
-/
namespace category_theory
universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
instance types : large_category (Type u) :=
{ hom := λ a b, (a → b),
id := λ a, id,
comp := λ _ _ _ f g, g ∘ f }
lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl
lemma types_id (X : Type u) : 𝟙 X = id := rfl
lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl
@[simp]
lemma types_id_apply (X : Type u) (x : X) : ((𝟙 X) : X → X) x = x := rfl
@[simp]
lemma types_comp_apply {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl
@[simp]
lemma hom_inv_id_apply {X Y : Type u} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x :=
congr_fun f.hom_inv_id x
@[simp]
lemma inv_hom_id_apply {X Y : Type u} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y :=
congr_fun f.inv_hom_id y
/-- `as_hom f` helps Lean type check a function as a morphism in the category `Type`. -/
-- Unfortunately without this wrapper we can't use `category_theory` idioms, such as `is_iso f`.
abbreviation as_hom {α β : Type u} (f : α → β) : α ⟶ β := f
-- If you don't mind some notation you can use fewer keystrokes:
notation `↾` f : 200 := as_hom f -- type as \upr in VScode
section -- We verify the expected type checking behaviour of `as_hom`.
variables (α β γ : Type u) (f : α → β) (g : β → γ)
example : α → γ := ↾f ≫ ↾g
example [is_iso ↾f] : mono ↾f := by apply_instance
example [is_iso ↾f] : ↾f ≫ inv ↾f = 𝟙 α := by simp
end
namespace functor
variables {J : Type u} [category.{v} J]
/--
The sections of a functor `J ⥤ Type` are
the choices of a point `u j : F.obj j` for each `j`,
such that `F.map f (u j) = u j` for every morphism `f : j ⟶ j'`.
We later use these to define limits in `Type` and in many concrete categories.
-/
def sections (F : J ⥤ Type w) : set (Π j, F.obj j) :=
{ u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'}
end functor
namespace functor_to_types
variables {C : Type u} [category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C}
variables (σ : F ⟶ G) (τ : G ⟶ H)
@[simp] lemma map_comp_apply (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) :=
by simp [types_comp]
@[simp] lemma map_id_apply (a : F.obj X) : (F.map (𝟙 X)) a = a :=
by simp [types_id]
lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) :=
congr_fun (σ.naturality f) x
@[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl
variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D}
@[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl
@[simp] lemma map_inv_map_hom_apply (f : X ≅ Y) (x : F.obj X) : F.map f.inv (F.map f.hom x) = x :=
congr_fun (F.map_iso f).hom_inv_id x
@[simp] lemma map_hom_map_inv_apply (f : X ≅ Y) (y : F.obj Y) : F.map f.hom (F.map f.inv y) = y :=
congr_fun (F.map_iso f).inv_hom_id y
@[simp] lemma hom_inv_id_app_apply (α : F ≅ G) (X) (x) : α.inv.app X (α.hom.app X x) = x :=
congr_fun (α.hom_inv_id_app X) x
@[simp] lemma inv_hom_id_app_apply (α : F ≅ G) (X) (x) : α.hom.app X (α.inv.app X x) = x :=
congr_fun (α.inv_hom_id_app X) x
end functor_to_types
/--
The isomorphism between a `Type` which has been `ulift`ed to the same universe,
and the original type.
-/
def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy
/--
The functor embedding `Type u` into `Type (max u v)`.
Write this as `ulift_functor.{5 2}` to get `Type 2 ⥤ Type 5`.
-/
def ulift_functor : Type u ⥤ Type (max u v) :=
{ obj := λ X, ulift.{v} X,
map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) }
@[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) :
ulift_functor.map f x = ulift.up (f x.down) := rfl
instance ulift_functor_full : full.{u} ulift_functor :=
{ preimage := λ X Y f x, (f (ulift.up x)).down }
instance ulift_functor_faithful : faithful ulift_functor :=
{ map_injective' := λ X Y f g p, funext $ λ x,
congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) }
/-- Any term `x` of a type `X` corresponds to a morphism `punit ⟶ X`. -/
-- TODO We should connect this to a general story about concrete categories
-- whose forgetful functor is representable.
def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x
lemma hom_of_element_eq_iff {X : Type u} (x y : X) :
hom_of_element x = hom_of_element y ↔ x = y :=
⟨λ H, congr_fun H punit.star, by cc⟩
/--
A morphism in `Type` is a monomorphism if and only if it is injective.
See https://stacks.math.columbia.edu/tag/003C.
-/
lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f :=
begin
split,
{ intros H x x' h,
resetI,
rw ←hom_of_element_eq_iff at ⊢ h,
exact (cancel_mono f).mp h },
{ refine λ H, ⟨λ Z g h H₂, _⟩,
ext z,
replace H₂ := congr_fun H₂ z,
exact H H₂ }
end
/--
A morphism in `Type` is an epimorphism if and only if it is surjective.
See https://stacks.math.columbia.edu/tag/003C.
-/
lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f :=
begin
split,
{ intros H,
let g : Y ⟶ ulift Prop := λ y, ⟨true⟩,
let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩,
suffices : f ≫ g = f ≫ h,
{ resetI,
rw cancel_epi at this,
intro y,
replace this := congr_fun this y,
replace this : true = ∃ x, f x = y := congr_arg ulift.down this,
rw ←this,
trivial },
ext x,
change true ↔ ∃ x', f x' = f x,
rw true_iff,
exact ⟨x, rfl⟩ },
{ intro H,
constructor,
intros Z g h H₂,
apply funext,
rw ←forall_iff_forall_surj H,
intro x,
exact (congr_fun H₂ x : _) }
end
section
/-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This
allows us to use these functors in category theory. -/
def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] :
Type u ⥤ Type v :=
{ obj := m,
map := λα β, _root_.functor.map,
map_id' := assume α, _root_.functor.map_id,
map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ }
variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m]
@[simp]
lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl
@[simp]
lemma of_type_functor_map {α β} (f : α → β) :
(of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl
end
end category_theory
-- Isomorphisms in Type and equivalences.
namespace equiv
universe u
variables {X Y : Type u}
/--
Any equivalence between types in the same universe gives
a categorical isomorphism between those types.
-/
def to_iso (e : X ≃ Y) : X ≅ Y :=
{ hom := e.to_fun,
inv := e.inv_fun,
hom_inv_id' := funext e.left_inv,
inv_hom_id' := funext e.right_inv }
@[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl
@[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl
end equiv
universe u
namespace category_theory.iso
open category_theory
variables {X Y : Type u}
/--
Any isomorphism between types gives an equivalence.
-/
def to_equiv (i : X ≅ Y) : X ≃ Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := λ x, congr_fun i.hom_inv_id x,
right_inv := λ y, congr_fun i.inv_hom_id y }
@[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl
@[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl
@[simp] lemma to_equiv_id (X : Type u) : (iso.refl X).to_equiv = equiv.refl X := rfl
@[simp] lemma to_equiv_comp {X Y Z : Type u} (f : X ≅ Y) (g : Y ≅ Z) :
(f ≪≫ g).to_equiv = f.to_equiv.trans (g.to_equiv) := rfl
end category_theory.iso
namespace category_theory
/-- A morphism in `Type u` is an isomorphism if and only if it is bijective. -/
noncomputable
def is_iso_equiv_bijective {X Y : Type u} (f : X ⟶ Y) : is_iso f ≃ function.bijective f :=
equiv_of_subsingleton_of_subsingleton
(λ i, ({ hom := f, .. i } : X ≅ Y).to_equiv.bijective)
(λ b, { .. (equiv.of_bijective f b).to_iso })
end category_theory
-- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`.
-- (In this order the proofs are handled by `obviously`.)
/-- equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types -/
@[simps] def equiv_iso_iso {X Y : Type u} : (X ≃ Y) ≅ (X ≅ Y) :=
{ hom := λ e, e.to_iso,
inv := λ i, i.to_equiv, }
/-- equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types -/
-- We leave `X` and `Y` as explicit arguments here, because the coercions from `equiv` to a function won't fire without them.
def equiv_equiv_iso (X Y : Type u) : (X ≃ Y) ≃ (X ≅ Y) :=
(equiv_iso_iso).to_equiv
@[simp] lemma equiv_equiv_iso_hom {X Y : Type u} (e : X ≃ Y) : (equiv_equiv_iso X Y) e = e.to_iso := rfl
@[simp] lemma equiv_equiv_iso_inv {X Y : Type u} (e : X ≅ Y) : (equiv_equiv_iso X Y).symm e = e.to_equiv := rfl
|
fe05aab8ff7e813653fde01b66c30bc6fa375059 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/int/cast.lean | 9e1ccf1dfb07d3118e4ddb2c4fb43268f8941f18 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,556 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.basic
import data.nat.cast
open nat
namespace int
/- cast (injection into groups with one) -/
@[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
/-- Coercion `ℕ → ℤ` as a `ring_hom`. -/
def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩
section cast
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α] [has_neg α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
-- see Note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩
@[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n :=
by simp
@[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] :
((1 : ℤ) : α) = 1 := nat.cast_one
@[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) :
((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] :
∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := by simpa only [sub_eq_add_neg] using cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
begin
rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add],
apply congr_arg (λ x:ℕ, -(x:α)),
ac_refl
end
@[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
@[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp [sub_eq_add_neg]
@[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
/-- `coe : ℤ → α` as an `add_monoid_hom`. -/
def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩
@[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl
/-- `coe : ℤ → α` as a `ring_hom`. -/
def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
@[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl
lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x :=
int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left)
lemma cast_comm [ring α] (m : ℤ) (x : α) : (m : α) * x = x * m :=
(cast_commute m x).eq
lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m :=
(m.cast_commute x).symm
@[simp, norm_cast]
theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp}
@[simp, norm_cast]
theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp}
@[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) :=
begin
intros m n h,
rw ← sub_nonneg at h,
lift n - m to ℕ using h with k,
rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat],
exact k.cast_nonneg
end
@[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one,
by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le
@[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) :=
strict_mono_of_le_iff_le $ λ m n, cast_le.symm
@[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) < n ↔ m < n :=
cast_strict_mono.lt_iff_lt
@[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp, norm_cast] theorem cast_min [linear_ordered_ring α] {a b : ℤ} :
(↑(min a b) : α) = min a b :=
monotone.map_min cast_mono
@[simp, norm_cast] theorem cast_max [linear_ordered_ring α] {a b : ℤ} :
(↑(max a b) : α) = max a b :=
monotone.map_max cast_mono
@[simp, norm_cast] theorem cast_abs [linear_ordered_ring α] {q : ℤ} :
((abs q : ℤ) : α) = abs q :=
by simp [abs]
lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (int.cast_ring_hom α) h
end cast
end int
open int
namespace add_monoid_hom
variables {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1,
have ∀ n : ℕ, f n = g n := ext_iff.1 this,
ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1)
variables [add_group A] [has_one A]
theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A :=
ext_int $ by simp [h1]
theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n :=
ext_iff.1 (f.eq_int_cast_hom h1)
end add_monoid_hom
namespace monoid_hom
variables {M : Type*} [monoid M]
open multiplicative
@[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g :=
monoid_hom.ext $ add_monoid_hom.ext_iff.mp $
@add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1
/-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : ℤ →* M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) :
f = g :=
begin
ext (x | x),
{ exact (monoid_hom.congr_fun h_nat x : _), },
{ rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul],
congr' 1,
exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), }
end
end monoid_hom
namespace monoid_with_zero_hom
variables {M : Type*} [monoid_with_zero M]
/-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : monoid_with_zero_hom ℤ M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom =
g.comp int.of_nat_hom.to_monoid_with_zero_hom) :
f = g :=
to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _)
/-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/
theorem ext_int' {φ₁ φ₂ : monoid_with_zero_hom ℤ M}
(h_neg_one : φ₁ (-1) = φ₂ (-1)) (h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ :=
ext_int h_neg_one $ ext_nat h_pos
end monoid_with_zero_hom
namespace ring_hom
variables {α : Type*} {β : Type*} [ring α] [ring β]
@[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n :=
f.to_add_monoid_hom.eq_int_cast f.map_one n
lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α :=
ring_hom.ext f.eq_int_cast
@[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n :=
(f.comp (int.cast_ring_hom α)).eq_int_cast n
lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm
instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) :=
⟨ring_hom.ext_int⟩
end ring_hom
@[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n :=
((ring_hom.id ℤ).eq_int_cast n).symm
namespace pi
variables {α β : Type*}
lemma int_apply [has_zero β] [has_one β] [has_add β] [has_neg β] :
∀ (n : ℤ) (a : α), (n : α → β) a = n
| (n:ℕ) a := pi.nat_apply n a
| -[1+n] a :=
by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, neg_apply, add_apply, one_apply, nat_apply]
@[simp] lemma coe_int [has_zero β] [has_one β] [has_add β] [has_neg β] (n : ℤ) :
(n : α → β) = λ _, n :=
by { ext, rw pi.int_apply }
end pi
|
aeb3ef7ec884dab750dc2e4e68b3d7701cf3ec0f | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/sites/sheaf_of_types.lean | 95c8845dd586b97cba627d0093f211bb0dcc2706 | [
"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 | 35,527 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.pretopology
import category_theory.limits.shapes.types
import category_theory.full_subcategory
/-!
# Sheaves of types on a Grothendieck topology
Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians)
on a category equipped with a Grothendieck topology, as well as a range of equivalent
conditions useful in different situations.
First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular
presieve `R` on `X`:
* A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in
`R`. See `family_of_elements`.
* The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`,
and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of
`x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`.
See `family_of_elements.compatible`.
* An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in
`R`, the restriction of `t` on `f` is `x_f`.
See `family_of_elements.is_amalgamation`.
We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation,
and it is a *sheaf* for `R` if every compatible family has a unique amalgamation.
See `is_separated_for` and `is_sheaf_for`.
In the special case where `R` is a sieve, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of
`x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`).
See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`.
In the special case where `C` has pullbacks, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`,
the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g`
along `π₂ : pullback f g ⟶ Z`.
See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`.
Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the
topology. See `is_sheaf`.
In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for
every sieve in the pretopology. See `is_sheaf_pretopology`.
We also provide equivalent conditions to satisfy alternate definitions given in the literature.
* Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be
equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with
`is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.)
The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the
statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries
the same information as the unique existence.)
* Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf`
are equivalent. There are also alternate definitions given:
- Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in
`yoneda_condition_iff_sheaf_condition`.
- Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence
in `equalizer.sieve.sheaf_condition`.
- Matching family for presieves with pullback: `pullback_compatible_iff`.
- Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous.
- Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition`
combined with the previous.
## Implementation
The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u v)`.
This doesn't seem to make a big difference, other than making a couple of definitions noncomputable,
but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements,
which can be convenient.
## References
* [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk:
Chapter III, Section 4.
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1.
* https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site)
* https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology)
-/
universes v u
namespace category_theory
open opposite category_theory category limits sieve classical
namespace presieve
variables {C : Type u} [category.{v} C]
variables {P : Cᵒᵖ ⥤ Type v}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X`
consists of an element of `P Y` for every `f : Y ⟶ X` in `R`.
A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one
(resp, at most one) amalgamation.
This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete
version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is
more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant].
-/
def family_of_elements (P : Cᵒᵖ ⥤ Type v) (R : presieve X) :=
Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y)
instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩
/--
A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve
`R₁`.
-/
def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) :
family_of_elements P R₂ → family_of_elements P R₁ :=
λ x Y f hf, x f (h _ hf)
/--
A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and
`f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂`
commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and
restricting the element of `P Y₂` along `g₂` are the same.
In special cases, this condition can be simplified, see `pullback_compatible_iff` and
`compatible_iff_sieve_compatible`.
This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab:
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents
-/
def family_of_elements.compatible (x : family_of_elements P R) : Prop :=
∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄
(h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂)
/--
If the category `C` has pullbacks, this is an alternative condition for a family of elements to be
compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the
given elements for `f` and `g` to the pullback agree.
This is equivalent to being compatible (provided `C` has pullbacks), shown in
`pullback_compatible_iff`.
This is the definition for a "matching" family given in [MM92], Chapter III, Section 4,
Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in
https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`,
using the notation defined there.
-/
def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop :=
∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂),
P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂)
lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] :
x.compatible ↔ x.pullback_compatible :=
begin
split,
{ intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂,
apply t,
apply pullback.condition },
{ intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂,
←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] }
end
/-- The restriction of a compatible family is compatible. -/
lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
{x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible :=
λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm
/--
Extend a family of elements to the sieve generated by an arrow set.
This is the construction described as "easy" in Lemma C2.1.3 of [Elephant].
-/
noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) :
family_of_elements P (generate R) :=
λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1)
/-- The extension of a compatible family to the generated sieve is compatible. -/
lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) :
x.sieve_extend.compatible :=
begin
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2,
←assoc, ←assoc] at comm,
dsimp [family_of_elements.sieve_extend],
rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply],
apply hx _ _ _ _ comm,
end
/-- The extension of a family agrees with the original family. -/
lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) :
x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf :=
begin
have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩,
change P.map (some (some_spec h)).op (x _ _) = x f hf,
rw t (some (some_spec h)) (𝟙 _) _ hf _,
{ simp },
simp_rw [id_comp],
apply (some_spec (some_spec (some_spec h))).2,
end
/-- The restriction of an extension is the original. -/
@[simp]
lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) :
x.sieve_extend.restrict (le_generate R) = x :=
begin
ext Y f hf,
exact extend_agrees t hf,
end
/--
If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the
consistency condition can be simplified.
This is an equivalent condition, see `compatible_iff_sieve_compatible`.
This is the notion of "matching" given for families on sieves given in [MM92], Chapter III,
Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family.
See also the discussion before Lemma C2.1.4 of [Elephant].
-/
def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop :=
∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf)
lemma compatible_iff_sieve_compatible (x : family_of_elements P S) :
x.compatible ↔ x.sieve_compatible :=
begin
split,
{ intros h Y Z f g hf,
simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) },
{ intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k,
simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] }
end
lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S}
(t : x.compatible) : x.sieve_compatible :=
(compatible_iff_sieve_compatible x).1 t
/--
Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are
equal when restricted to `R`.
-/
lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)}
(t₁ : x₁.compatible) (t₂ : x₂.compatible) :
x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ :=
begin
intro h,
ext Z f ⟨Y, f, g, hg, rfl⟩,
rw compatible_iff_sieve_compatible at t₁ t₂,
erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩],
congr' 1,
apply congr_fun (congr_fun (congr_fun h _) g) hg,
end
/--
Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted
to `R` and then extended back up to `S`, the resulting extension equals `x`.
-/
@[simp]
lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) :
(x.restrict (le_generate R)).sieve_extend = x :=
begin
apply restrict_inj,
{ exact (t.restrict (le_generate R)).sieve_extend _ },
{ exact t },
rw restrict_extend,
exact t.restrict (le_generate R),
end
/--
The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every
restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`.
This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents,
and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4,
equation (2).
-/
def family_of_elements.is_amalgamation (x : family_of_elements P R)
(t : P.obj (op X)) : Prop :=
∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h
lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R)
(h : ∃ t, x.is_amalgamation t) : x.compatible :=
begin
cases h with t ht,
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm],
simp,
end
lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
(x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
(x.restrict h).is_amalgamation t :=
λ Y f hf, ht f (h Y hf)
lemma is_amalgamation_sieve_extend {R : presieve X}
(x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
x.sieve_extend.is_amalgamation t :=
begin
intros Y f hf,
dsimp [family_of_elements.sieve_extend],
rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2],
end
/-- A presheaf is separated for a presieve if there is at most one amalgamation. -/
def is_separated_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R) (t₁ t₂),
x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂
lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R)
{t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) :
t₁ = t₂ :=
hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl)
lemma is_separated_for_iff_generate :
is_separated_for P R ↔ is_separated_for P (generate R) :=
begin
split,
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.restrict (le_generate R)) t₁ t₂ _ _,
{ exact is_amalgamation_restrict _ x t₁ ht₁ },
{ exact is_amalgamation_restrict _ x t₂ ht₂ } },
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.sieve_extend),
{ exact is_amalgamation_sieve_extend x t₁ ht₁ },
{ exact is_amalgamation_sieve_extend x t₂ ht₂ } }
end
lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type v) : is_separated_for P (⊤ : presieve X) :=
λ x t₁ t₂ h₁ h₂,
begin
have q₁ := h₁ (𝟙 X) (by simp),
have q₂ := h₂ (𝟙 X) (by simp),
simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂,
rw [q₁, q₂],
end
/--
We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique
amalgamation.
This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents.
Using `compatible_iff_sieve_compatible`,
this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4.
-/
def is_sheaf_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t
/--
This is an equivalent condition to be a sheaf, which is useful for the abstraction to local
operators on elementary toposes. However this definition is defined only for sieves, not presieves.
The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`.
This version is also useful to establish that being a sheaf is preserved under isomorphism of
presheaves.
See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of
[Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8.
-/
def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v) (S : sieve X) : Prop :=
∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f
/--
(Implementation). This is a (primarily internal) equivalence between natural transformations
and compatible families.
Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also
the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4.
-/
def nat_trans_equiv_compatible_family :
(S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} :=
{ to_fun := λ α,
begin
refine ⟨λ Y f hf, _, _⟩,
{ apply α.app (op Y) ⟨_, hf⟩ },
{ rw compatible_iff_sieve_compatible,
intros Y Z f g hf,
dsimp,
rw ← functor_to_types.naturality _ _ α g.op,
refl }
end,
inv_fun := λ t,
{ app := λ Y f, t.1 _ f.2,
naturality' := λ Y Z g,
begin
ext ⟨f, hf⟩,
apply t.2.to_sieve_compatible _,
end },
left_inv := λ α,
begin
ext X ⟨_, _⟩,
refl
end,
right_inv :=
begin
rintro ⟨x, hx⟩,
refl,
end }
/-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/
lemma extension_iff_amalgamation (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) :
S.functor_inclusion ≫ g = x ↔
(nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) :=
begin
change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩,
split,
{ rintro rfl Y f hf,
rw yoneda_equiv_naturality,
dsimp,
simp }, -- See note [dsimp, simp].
{ intro h,
ext Y ⟨f, hf⟩,
have : _ = x.app Y _ := h f hf,
rw yoneda_equiv_naturality at this,
rw ← this,
dsimp,
simp }, -- See note [dsimp, simp].
end
/--
The yoneda version of the sheaf condition is equivalent to the sheaf condition.
C2.1.4 of [Elephant].
-/
lemma is_sheaf_for_iff_yoneda_sheaf_condition :
is_sheaf_for P S ↔ yoneda_sheaf_condition P S :=
begin
rw [is_sheaf_for, yoneda_sheaf_condition],
simp_rw [extension_iff_amalgamation],
rw equiv.forall_congr_left' nat_trans_equiv_compatible_family,
rw subtype.forall,
apply ball_congr,
intros x hx,
rw equiv.exists_unique_congr_left _,
simp,
end
/--
If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor)
to `P` can be (uniquely) extended to all of `yoneda.obj X`.
f
S → P
↓ ↗
yX
-/
noncomputable def is_sheaf_for.extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) :
yoneda.obj X ⟶ P :=
classical.some (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists
/--
Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie
that the triangle below commutes, provided `P` is a sheaf for `S`
f
S → P
↓ ↗
yX
-/
@[simp, reassoc]
lemma is_sheaf_for.functor_inclusion_comp_extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) :
S.functor_inclusion ≫ h.extend f = f :=
classical.some_spec (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists
/-- The extension of `f` to `yoneda.obj X` is unique. -/
lemma is_sheaf_for.unique_extend (h : is_sheaf_for P S) {f : S.functor ⟶ P} (t : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t = f) :
t = h.extend f :=
((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f))
/--
If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X`
to `P` agree when restricted to the subfunctor given by `S`, they are equal.
-/
lemma is_sheaf_for.hom_ext (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) :
t₁ = t₂ :=
(h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm
/-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/
lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for :
is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔
is_sheaf_for P R :=
begin
rw [is_separated_for, ←forall_and_distrib],
apply forall_congr,
intro x,
split,
{ intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 },
{ intros h,
refine ⟨_, (exists_of_exists_unique ∘ h)⟩,
intros t₁ t₂ ht₁ ht₂,
apply (h _).unique ht₁ ht₂,
exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ }
end
/--
If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`.
-/
lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) :
(∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) →
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
exact and.intro t,
end
/-- If `P` is a sheaf for `R`, it is separated for `R`. -/
lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R :=
λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1
/-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/
noncomputable def is_sheaf_for.amalgamate
(t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) :
P.obj (op X) :=
classical.some (t x hx).exists
lemma is_sheaf_for.is_amalgamation
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) :
x.is_amalgamation (t.amalgamate x hx) :=
classical.some_spec (t x hx).exists
@[simp]
lemma is_sheaf_for.valid_glue
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) :
P.map f.op (t.amalgamate x hx) = x f Hf :=
t.is_amalgamation hx f Hf
/-- C2.1.3 in [Elephant] -/
lemma is_sheaf_for_iff_generate (R : presieve X) :
is_sheaf_for P R ↔ is_sheaf_for P (generate R) :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_iff_generate,
apply and_congr (iff.refl _),
split,
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))),
intros t ht,
simpa [hx] using is_amalgamation_sieve_extend _ _ ht },
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.sieve_extend _)),
intros t ht,
simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht },
end
/--
Every presheaf is a sheaf for the family {𝟙 X}.
[Elephant] C2.1.5(i)
-/
lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type v) :
is_sheaf_for P (presieve.singleton (𝟙 X)) :=
begin
intros x hx,
refine ⟨x _ (presieve.singleton_self _), _, _⟩,
{ rintro _ _ ⟨rfl, rfl⟩,
simp },
{ intros t ht,
simpa using ht _ (presieve.singleton_self _) }
end
/--
Every presheaf is a sheaf for the maximal sieve.
[Elephant] C2.1.5(ii)
-/
lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type v) :
is_sheaf_for P ((⊤ : sieve X) : presieve X) :=
begin
rw ← generate_of_singleton_split_epi (𝟙 X),
rw ← is_sheaf_for_iff_generate,
apply is_sheaf_for_singleton_iso,
end
/--
If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that
"being a sheaf for a presieve" is a mathematical or hygenic property.
-/
lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R :=
begin
rw [is_sheaf_for_iff_generate R, is_sheaf_for_iff_generate R],
intro h,
rw [is_sheaf_for_iff_yoneda_sheaf_condition],
intro f,
refine ⟨h.extend (f ≫ i.inv) ≫ i.hom, by simp, _⟩,
intros g' hg',
rw [← i.comp_inv_eq, h.unique_extend (g' ≫ i.inv) (by rw reassoc_of hg')],
end
/--
If a presieve `R` on `X` has a subsieve `S` such that:
* `P` is a sheaf for `S`.
* For every `f` in `R`, `P` is separated for the pullback of `S` along `f`,
then `P` is a sheaf for `R`.
This is closely related to [Elephant] C2.1.6(i).
-/
lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(hS : is_sheaf_for P S)
(trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) :
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
split,
{ intros x t₁ t₂ ht₁ ht₂,
exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁)
(is_amalgamation_restrict h x t₂ ht₂) },
{ intros x hx,
use hS.amalgamate _ (hx.restrict h),
intros W j hj,
apply (trans hj).ext,
intros Y f hf,
rw [←functor_to_types.map_comp_apply, ←op_comp,
hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict,
←hx (𝟙 _) f _ _ (id_comp _)],
simp },
end
/--
If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which
contains `S`.
This is closely related to [Elephant] C2.1.6.
-/
lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) :
is_sheaf_for P R :=
is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for)
/-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/
def is_separated (P : Cᵒᵖ ⥤ Type v) : Prop :=
∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S
/--
A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology.
If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to
check the sheaf condition at presieves in the pretopology.
-/
def is_sheaf (P : Cᵒᵖ ⥤ Type v) : Prop :=
∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S
lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type v} (hp : is_sheaf J P)
(R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R :=
(is_sheaf_for_iff_generate R).2 $ hp _ hr
lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type v) {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P :=
λ h t X S hS, t S (h _ hS)
lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type v) (h : is_sheaf J P) : is_separated J P :=
λ X S hS, (h S hS).is_separated_for
/-- The property of being a sheaf is preserved by isomorphism. -/
lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' :=
λ X S hS, is_sheaf_for_iso i (h S hS)
lemma is_sheaf_of_yoneda (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) :
is_sheaf J P :=
λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS)
/--
For a topology generated by a basis, it suffices to check the sheaf condition on the basis
presieves only.
-/
lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) :=
begin
split,
{ intros PJ X R hR,
rw is_sheaf_for_iff_generate,
apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ },
{ rintro PK X S ⟨R, hR, RS⟩,
have gRS : ⇑(generate R) ≤ S,
{ apply gi_generate.gc.monotone_u,
rwa sets_iff_generate },
apply is_sheaf_for_subsieve P gRS _,
intros Y f,
rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate],
exact PK (pullback_arrows f R) (K.pullbacks f R hR) }
end
/-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/
lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P :=
λ X, by simp [is_sheaf_for_top_sieve]
end presieve
namespace equalizer
variables {C : Type v} [small_category C] (P : Cᵒᵖ ⥤ Type v) {X : C} (R : presieve X) (S : sieve X)
noncomputable theory
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def first_obj : Type v :=
∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1))
/-- Show that `first_obj` is isomorphic to `family_of_elements`. -/
@[simps]
def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P :=
{ hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t,
inv := pi.lift (λ f x, x _ f.2.2),
hom_inv_id' :=
begin
ext ⟨Y, f, hf⟩ p,
simpa,
end,
inv_hom_id' :=
begin
ext x Y f hf,
apply limits.types.limit.lift_π_apply,
end }
instance : inhabited (first_obj P (⊥ : presieve X)) :=
((first_obj_eq_family P _).to_equiv).inhabited
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of https://stacks.math.columbia.edu/tag/00VM.
-/
def fork_map : P.obj (op X) ⟶ first_obj P R :=
pi.lift (λ f, P.map f.2.1.op)
/-!
This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and
the definition of `is_sheaf_for`.
-/
namespace sieve
/--
The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used
to check a family is compatible.
-/
def second_obj : Type v :=
∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1))
/-- The map `p` of Equations (3,4) [MM92]. -/
def first_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f}))
instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩
/-- The map `a` of Equations (3,4) [MM92]. -/
def second_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op)
lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S :=
begin
apply limit.hom_ext,
rintro ⟨Y, Z, g, f, hf⟩,
simp [first_map, second_map, fork_map],
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P S) :
((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x :=
begin
rw presieve.compatible_iff_sieve_compatible,
split,
{ intro t,
ext ⟨Y, Z, g, f, hf⟩,
simpa [first_map, second_map] using t _ g hf },
{ intros t Y Z f g hf,
rw types.limit_ext_iff at t,
simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ }
end
/-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/
lemma equalizer_sheaf_condition :
presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) :=
begin
rw [types.type_equalizer_iff_unique,
← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm],
simp_rw ← compatible_iff,
simp only [inv_hom_id_apply, iso.to_equiv_symm_fun],
apply ball_congr,
intros x tx,
apply exists_unique_congr,
intro t,
rw ← iso.to_equiv_symm_fun,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [first_obj_eq_family, fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [first_obj_eq_family, fork_map] }
end
end sieve
/-!
This section establishes the equivalence between the sheaf condition of
https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`.
-/
namespace presieve
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : Type v :=
∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/
def first_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩
/-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/
def second_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map],
simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk,
subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P R) :
((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x :=
begin
rw presieve.pullback_compatible_iff,
split,
{ intro t,
ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩,
simpa [first_map, second_map] using t hf hg },
{ intros t Y Z f g hf hg,
rw types.limit_ext_iff at t,
simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ }
end
/--
`P` is a sheaf for `R`, iff the fork given by `w` is an equalizer.
See https://stacks.math.columbia.edu/tag/00VM.
-/
lemma sheaf_condition :
R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) :=
begin
rw types.type_equalizer_iff_unique,
erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm,
simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply],
apply ball_congr,
intros x hx,
apply exists_unique_congr,
intros t,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [fork_map] }
end
end presieve
end equalizer
variables {C : Type u} [category.{v} C]
variables (J : grothendieck_topology C)
/-- The category of sheaves on a grothendieck topology. -/
@[derive category]
def SheafOfTypes (J : grothendieck_topology C) : Type (max u (v+1)) :=
{P : Cᵒᵖ ⥤ Type v // presieve.is_sheaf J P}
/-- The inclusion functor from sheaves to presheaves. -/
@[simps, derive [full, faithful]]
def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type v) :=
full_subcategory_inclusion (presieve.is_sheaf J)
/--
The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category
of presheaves.
-/
@[simps]
def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type v) :=
{ functor := SheafOfTypes_to_presheaf _,
inverse :=
{ obj := λ P, ⟨P, presieve.is_sheaf_bot⟩,
map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f },
unit_iso :=
{ hom := { app := λ _, 𝟙 _ },
inv := { app := λ _, 𝟙 _ } },
counit_iso := iso.refl _ }
instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) :=
⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩
end category_theory
|
7dc1729cfcc34ed66c671bc6b9589ebbc7c00624 | 6b2a480f27775cba4f3ae191b1c1387a29de586e | /group_rep1/matrix_representation_refondation.lean | 4d9303d7ffc3bfd50675bb6f28c7e11bc4b86d60 | [] | no_license | Or7ando/group_representation | a681de2e19d1930a1e1be573d6735a2f0b8356cb | 9b576984f17764ebf26c8caa2a542d248f1b50d2 | refs/heads/master | 1,662,413,107,324 | 1,590,302,389,000 | 1,590,302,389,000 | 258,130,829 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,998 | lean | import linear_algebra.basic
import linear_algebra.basis
open linear_map
open is_basis
universe variables u v w
namespace classical_basis
set_option trace.simplify.rewrite true
variables {G : Type u} {R : Type v} [group G] [comm_ring R]
variables {X : Type w} [fintype X] [decidable_eq X]
/-!
Definition of classical basis of `X → R`.
`ε x = λ y, if x = y then 1 else 0`.
-/
def ε {R : Type v}[comm_ring R]{X : Type w}(x : X) [fintype X] [decidable_eq X] :
(X → R) := (λ y : X, if x = y then 1 else 0)
variable (x : X)
#check ε x x -- premier probleme est-ce que je dois mettre X et R ?
-- C'est lourd
lemma epsilon_eq (x : X) : ε x x = (1 : R) := --- un meilleur nom !
begin
unfold ε,simp,
end
/-!
On va integrer les sommes pour obtenir une formule du style
pour f : X → R , f = ∑ λ x, f x * (ε x) !
C'est la décomposition dans la base ε !
-/
@[simp]lemma epsilon_ne ( x y : X)(HYP : ¬ y = x) : ε x y = (0 : R) := begin
unfold ε, split_ifs, rw h at HYP, trivial,
exact rfl,
end
@[simp]lemma smul_ite (φ : X → R) ( y : X) : (λ (x : X), φ x • (ε x y)) = (λ x : X, if y = x then φ x else 0) := begin
funext,
split_ifs,
rw h, rw epsilon_eq, exact mul_one (φ x),
rw epsilon_ne x y h,
exact mul_zero (φ x),
end
notation `Σ` := finset.sum finset.univ
lemma gen (φ : X → R) : φ = Σ (λ (x : X), φ x • ε x) :=
begin
funext y,
rw finset.sum_apply,
--change _ = Σ (λ x : X, φ x • ε x y),
erw smul_ite,
erw finset.sum_ite_eq,
split_ifs,exact rfl,
have R : y ∈ finset.univ, exact finset.mem_univ y, trivial,
end
#check is_basis R ε
@[simp]lemma test (g : X → R)(s : finset X)(y ∈ s) :
finset.sum s (λ i : X, g i • (ε i : X → R) ) y = finset.sum s (λ i : X, (g i • ε i) y) :=
begin exact finset.sum_apply (λ (i : X), R) (λ (i : X), g i • ε i) y,
end
@[simp]lemma classical_basis : is_basis R (λ x : X, (ε x : X → R)) := --- c'est un peu chiant
begin
split,
rw linear_independent_iff', intros s, intros φ, intros hyp, intros x, intros hyp_x,
rw function.funext_iff at hyp, specialize hyp x,
rw finset.sum_apply (λ (i : X), R) _ _ at hyp,
change finset.sum s (λ y : X, φ y • (ε y x : R)) = 0 at hyp,
rw smul_ite at hyp,
erw finset.sum_ite_eq at hyp, split_ifs at hyp,assumption,
rw eq_top_iff, rw submodule.le_def',
intros φ, intros,
rw gen φ,
let p := (submodule.span R (set.range (λ (x : X), ε x))),
apply submodule.sum_mem p,
intros x, intros hyp,
apply submodule.smul_mem p,
have r : ε x ∈ set.range (λ (t : X), ε t),
rw set.mem_range,
use x,
have rr : set.range (λ (t : X), ε t) ⊆ ↑p,
exact submodule.subset_span ,
have rrr : ε x ∈ ↑p,
exact set.mem_of_mem_of_subset r rr,
exact rrr,
end
end classical_basis
|
39058b46ad7c4757ac940554141bbe50de25e2d8 | cc5bb0a18c45fa529fc8bf0365b1fbf48464c5a8 | /library/init/meta/tactic.lean | a8031593fd431ca803ba33c8ff61267193fbd932 | [
"Apache-2.0"
] | permissive | mk12/lean | 6bb58b9f3cfe312236b41779478d345399f00918 | 092fc89333160661c4c5a6295f3054cafff4341e | refs/heads/master | 1,609,531,450,083 | 1,501,275,267,000 | 1,501,278,025,000 | 98,760,144 | 0 | 0 | null | 1,501,364,485,000 | 1,501,364,485,000 | null | UTF-8 | Lean | false | false | 47,034 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.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.meta.interaction_monad
meta constant tactic_state : Type
universes u v
namespace tactic_state
/-- Create a tactic state with an empty local context and a dummy goal. -/
meta constant mk_empty : environment → options → tactic_state
meta constant env : tactic_state → environment
/-- Format the given tactic state. If `target_lhs_only` is true and the target
is of the form `lhs ~ rhs`, where `~` is a simplification relation,
then only the `lhs` is displayed.
Remark: the parameter `target_lhs_only` is a temporary hack used to implement
the `conv` monad. It will be removed in the future. -/
meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format
/-- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s).to_string s.get_options⟩
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (hiding failed fail)
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ interaction_monad.monad with
failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _ }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace tactic
variables {α : Type u}
meta def try_core (t : tactic α) : tactic (option α) :=
λ s, result.cases_on (t s)
(λ a, success (some a))
(λ e ref s', success none s)
meta def skip : tactic unit :=
success ()
meta def try (t : tactic α) : tactic unit :=
try_core t >>[tactic] skip
meta def try_lst : list (tactic unit) → tactic unit
| [] := failed
| (tac :: tacs) := λ s,
match tac s with
| result.success _ s' := try (try_lst tacs) s'
| result.exception e p s' :=
match try_lst tacs s' with
| result.exception _ _ _ := result.exception e p s'
| r := r
end
end
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit :=
λ s, result.cases_on (t s)
(λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s)
(λ e ref s', success () s)
meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception _ _ s') := success () s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail combinator failed, given tactic succeeded" none s
end
open nat
/-- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/
meta def repeat_at_most : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := (do t, repeat_at_most n t) <|> skip
/-- (repeat_exactly n t) : execute t n times -/
meta def repeat_exactly : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do t, repeat_exactly n t
meta def repeat : tactic unit → tactic unit :=
repeat_at_most 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/-- Decorate t's exceptions with msg -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
meta def get_options : tactic options :=
do s ← read, return s.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception ._ f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨has_map.map to_fmt ∘ monad.mapm pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance {α} (a : α) : has_to_tactic_format (reflected a) :=
⟨λ h, pp h.to_expr⟩
@[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s).get n
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
assume state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α :=
λ s, timeit desc (t () s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
inductive transparency
| all | semireducible | instances | reducible | none
export transparency (reducible semireducible)
/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/
meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α
/-- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
`do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting. -/
meta constant whnf (e : expr) (md := semireducible) : tactic expr
/-- (head) eta expand the given expression -/
meta constant head_eta_expand : expr → tactic expr
/-- (head) beta reduction -/
meta constant head_beta : expr → tactic expr
/-- (head) zeta reduction -/
meta constant head_zeta : expr → tactic expr
/-- zeta reduction -/
meta constant zeta : expr → tactic expr
/-- (head) eta reduction -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) : tactic unit
/-- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit
/-- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
meta constant get_local : name → tactic expr
/-- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic pexpr
/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
meta constant get_unused_name (n : name) (i : option nat := none) : tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} (a > b) (nat.decidable_gt a b) nat a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/- Given a local constant t, if t has type (lhs = rhs) apply substitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst : expr → tactic unit
/-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr
/-- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/-- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
If `check` is `ff`, then the tactic does not check whether `e`
is definitionally equal to the current target. If it is not,
then the error will only be detected by the kernel type checker. -/
meta constant change (e : expr) (check : bool := tt): tactic unit
/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/
meta constant assert_core : name → expr → tactic unit
/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/
meta constant define_core : name → expr → tactic unit
/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/-- rotate goals to the left -/
meta constant rotate_left : nat → tactic unit
meta constant get_goals : tactic (list expr)
meta constant set_goals : list expr → tactic unit
inductive new_goals
| non_dep_first | non_dep_only | all
/-- Configuration options for the `apply` tactic. -/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(new_goals := new_goals.non_dep_first)
(instances := tt)
(auto_param := tt)
(opt_param := tt)
/-- Apply the expression `e` to the main goal,
the unification is performed using the transparency mode in `cfg`.
If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.
`cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.
If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.
The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).
It returns a list of all introduced meta variables, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr)
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/-- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/-- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
/-- Return true if the given meta-variable is assigned.
Fail if argument is not a meta-variable. -/
meta constant is_assigned : expr → tactic bool
meta constant mk_fresh_name : tactic name
/-- Return a hash code for expr that ignores inst_implicit arguments,
and proofs. -/
meta constant abstract_hash : expr → tactic nat
/-- Return the "weight" of the given expr while ignoring inst_implicit arguments,
and proofs. -/
meta constant abstract_weight : expr → tactic nat
meta constant abstract_eq : expr → expr → tactic bool
/-- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr)))
/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/-- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/-- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/-- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/
meta constant set_env : environment → tactic unit
/-- (doc_string env d k) return the doc string for d (if available) -/
meta constant doc_string : name → tactic string
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
meta constant module_doc_strings : tactic (list (option name × string))
/-- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/-- `unset_attribute attr_name c_name` -/
meta constant unset_attribute : name → name → tactic unit
/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority. -/
meta constant has_attribute : name → name → tactic nat
/-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src` -/
meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit :=
try $ do
prio ← has_attribute attr_name src,
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/-- `save_type_info e ref` save (typeof e) at position associated with ref -/
meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
/-- Blocks the execution of the current thread for at least `msecs` milliseconds.
This tactic is used mainly for debugging purposes. -/
meta constant sleep (msecs : nat) : tactic unit
/-- Type check `e` with respect to the current goal.
Fails if `e` is not type correct. -/
meta constant type_check (e : expr) (md := semireducible) : tactic unit
open list nat
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/-- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit :=
λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = `(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env.get n,
t ← return $ d.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
meta def unsafe_change (e : expr) : tactic unit :=
change e ff
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
meta def intro1 : tactic expr :=
intro `_
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
meta def intro_lst : list name → tactic (list expr)
| [] := return []
| (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs)
/-- Introduces new hypotheses with forward dependencies -/
meta def intros_dep : tactic (list expr) :=
do t ← target,
let proc (b : expr) :=
if b.has_var_idx 0 then
do h ← intro1, hs ← intros_dep, return (h::hs)
else
-- body doesn't depend on new hypothesis
return [],
match t with
| expr.pi _ _ _ b := proc b
| expr.elet _ _ _ b := proc b
| _ := return []
end
meta def introv : list name → tactic (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs')
/-- Returns n fully qualified if it refers to a constant, or else fails. -/
meta def resolve_constant (n : name) : tactic name :=
do (expr.const n _) ← resolve_name n,
pure n
meta def to_expr_strict (q : pexpr) : tactic expr :=
to_expr q
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_iff (e : expr) : tactic (expr × expr) :=
match (expr.is_iff e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an iff"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := (by assumption : p)
/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/
meta def assert (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, swap, return e
/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=
assertv_core h t v >> intro h
/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/
meta def define (h : name) (t : expr) : tactic expr :=
do define_core h t, swap, e ← intro h, swap, return e
/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic expr :=
definev_core h t v >> intro h
/-- Add `h : t := pr` to the current goal -/
meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, definev h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Add `h : t` to the current goal, given a proof `pr : t` -/
meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, assertv h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/-- We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
meta def rotate : nat → tactic unit :=
rotate_left
/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/-- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
match gs with
| [] := fail "solve1 tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs
| gs := fail "solve1 tactic failed, focused goal has not been solved"
end
end
/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/
meta def solve (ts : list (tactic unit)) : tactic unit :=
first $ map solve1 ts
private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] [] rs := set_goals rs
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics",
t,
rs' ← get_goals,
focus_aux ts gs (rs ++ rs')
/-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/
meta def focus (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals_core gs ac) $
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals_core gs (ac ++ new_gs)
/-- Apply the given tactic to all goals. -/
meta def all_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals_core gs ac progress) $
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress)
/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals_core tac gs [] ff
/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, focus tacs2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=
⟨seq⟩
meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=
⟨seq_focus⟩
meta constant is_trace_enabled_for : name → bool
/-- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/-- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/-- Fail if there are unsolved goals. -/
meta def done : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "done tactic failed, there are unsolved goals")
meta def apply_opt_param : tactic unit :=
do `(opt_param %%t %%v) ← target,
exact v
meta def apply_auto_param : tactic unit :=
do `(auto_param %%type %%tac_name_expr) ← target,
change type,
tac_name ← eval_expr name tac_name_expr,
tac ← eval_expr (tactic unit) (expr.const tac_name []),
tac
meta def has_opt_auto_param (ms : list expr) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=
when (cfg.auto_param || cfg.opt_param) $
mwhen (has_opt_auto_param ms) $ do
gs ← get_goals,
ms.mmap' (λ m, set_goals [m] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic unit :=
apply_core e cfg >>= try_apply_opt_auto_param cfg
meta def fapply (e : expr) : tactic unit :=
apply e {new_goals := new_goals.all}
meta def eapply (e : expr) : tactic unit :=
apply e {new_goals := new_goals.non_dep_only}
/-- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/-- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) : tactic unit :=
mk_const c >>= apply
meta def eapplyc (c : name) : tactic unit :=
mk_const c >>= eapply
meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,
and return metavariable `?M : ?T`.
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/-- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/-- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : option name := none) : tactic expr :=
do tgt : expr ← target,
(match_not tgt >> return ())
<|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply)
<|>
fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)",
match H with
| some n := intro n
| none := intro1
end
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit :=
if e.is_local_constant then
cases_core e ids md >> return ()
else do
x ← mk_fresh_name,
n ← revert_kdependencies e dmd,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
(step (cases_core h ids md); intron n)
meta def refine (e : pexpr) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt >>= exact
meta def by_cases (e : expr) (h : name) : tactic unit :=
do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"),
inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"),
t ← target,
tm ← mk_mapp `dite [some e, some inst, some t],
seq (apply tm) (intro h >> skip)
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ repr i) in
if ¬env.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns.any (λ n, n.is_prefix_of d) && env.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
meta def updateex_env (f : environment → exceptional environment) : tactic unit :=
do env ← get_env,
env ← returnex $ f env,
set_env env
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr))
(is_meta : bool := ff) : tactic unit :=
updateex_env $ λe, e.add_inductive n ls p ty is is_meta
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
meta def rename (curr : name) (new : name) : tactic unit :=
do h ← get_local curr,
n ← revert h,
intro new,
intron (n - 1)
/--
"Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof
that (type = new_type). The tactic actually creates a new hypothesis
with the same user facing name, and (tries to) clear `h`.
The `clear` step fails if `h` has forward dependencies. In this case, the old `h`
will remain in the local context. The tactic returns the new hypothesis. -/
meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr :=
do h_type ← infer_type h,
new_h ← assert h.local_pp_name new_type,
mk_eq_mp eq_pr h >>= exact,
try $ clear h,
return new_h
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/-
Define id_locked using meta-programming because we don't have
syntax for setting reducibility_hints.
See module init.meta.declaration.
Remark: id_locked is used in the builtin implementation of tactic.change
-/
run_cmd do
let l := level.param `l,
let Ty : pexpr := expr.sort l,
type ← to_expr ``(Π {α : %%Ty}, α → α),
val ← to_expr ``(λ {α : %%Ty} (a : α), a),
add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt)
lemma id_locked_eq {α : Type u} (a : α) : id_locked a = a :=
rfl
attribute [inline] id_locked
/-
Define id_rhs using meta-programming because we don't have
syntax for setting reducibility_hints.
See module init.meta.declaration.
Remark: id_rhs is used in the equation compiler to address performance
issues when proving equational lemmas.
-/
run_cmd do
let l := level.param `l,
let Ty : pexpr := expr.sort l,
type ← to_expr ``(Π (α : %%Ty), α → α),
val ← to_expr ``(λ (α : %%Ty) (a : α), a),
add_decl (declaration.defn `id_rhs [`l] type val reducibility_hints.abbrev tt)
attribute [reducible, inline] id_rhs
/- Install monad laws tactic and use it to prove some instances. -/
meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact
meta def unsafe_monad_from_pure_bind {m : Type u → Type v}
(pure : Π {α : Type u}, α → m α)
(bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m :=
{pure := @pure, bind := @bind,
id_map := undefined, pure_bind := undefined, bind_assoc := undefined}
meta instance : monad task :=
{map := @task.map, bind := @task.bind, pure := @task.pure,
id_map := undefined, pure_bind := undefined, bind_assoc := undefined,
bind_pure_comp_eq_map := undefined}
namespace tactic
meta def mk_id_locked_proof (prop : expr) (pr : expr) : expr :=
expr.app (expr.app (expr.const ``id_locked [level.zero]) prop) pr
meta def mk_id_locked_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr :=
do prop ← mk_app `eq [lhs, rhs],
return $ mk_id_locked_proof prop pr
meta def replace_target (new_target : expr) (pr : expr) : tactic unit :=
do t ← target,
assert `htarget new_target, swap,
ht ← get_local `htarget,
locked_pr ← mk_id_locked_eq t new_target pr,
mk_eq_mpr locked_pr ht >>= exact
end tactic
|
68a6f249cb4552377f3f720d16dac7d2056f0818 | fce460f0bcc5b026e1889739f7cd993d3ad95bbc | /src/first_file.lean | b8190f35d015134c966c1d86654207592ba8566b | [] | no_license | richardsouthwell/leanpractice | bea95ed6142998691409f4eb8c6577a6720de376 | 027f04835e975a1813c324feeec717304f9b065d | refs/heads/master | 1,671,477,356,658 | 1,602,257,419,000 | 1,602,257,419,000 | 302,679,208 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 146 | lean | import data.real.basic
#check ℝ
#eval 8 + 8
-- https://www.youtube.com/watch?v=b59fpAJ8Mfs&list=PLlF-CfQhukNnxF1S22cNGKyfOrd380NUv&index=7
|
5ecf5500e7ffd5b5840c207bf8a1879a23c3a88d | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/set/lattice.lean | df468db4ae3899674813cdffdccc1928aab172bb | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 58,944 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro
-/
import data.nat.basic
import order.complete_boolean_algebra
import order.directed
import order.galois_connection
/-!
# The set lattice
This file provides usual set notation for unions and intersections, a `complete_lattice` instance
for `set α`, and some more set constructions.
## Main declarations
* `set.Union`: Union of an indexed family of sets.
* `set.Inter`: Intersection of an indexed family of sets.
* `set.sInter`: **s**et **Inter**. Intersection of sets belonging to a set of sets.
* `set.sUnion`: **s**et **Union**. Intersection of sets belonging to a set of sets. This is actually
defined in core Lean.
* `set.sInter_eq_bInter`, `set.sUnion_eq_bInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and
`⋃₀ s = ⋃ x ∈ s, x`.
* `set.complete_boolean_algebra`: `set α` is a `complete_boolean_algebra` with `≤ = ⊆`, `< = ⊂`,
`⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `set.boolean_algebra`.
* `set.kern_image`: For a function `f : α → β`, `s.kern_image f` is the set of `y` such that
`f ⁻¹ y ⊆ s`.
* `set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union
of `f '' t` over all `f ∈ s`, where `t : set α` and `s : set (α → β)`.
* `set.pairwise_disjoint`: `pairwise_disjoint s` states that all sets in `s` are either equal or
disjoint.
* `set.Union_eq_sigma_of_disjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an
indexed family of disjoint sets.
## Notation
* `⋃`: `set.Union`
* `⋂`: `set.Inter`
* `⋃₀`: `set.sUnion`
* `⋂₀`: `set.sInter`
-/
open function tactic set auto
universes u
variables {α β γ : Type*} {ι ι' ι₂ : Sort*}
namespace set
/-! ### Complete lattice and complete Boolean algebra instances -/
instance : has_Inf (set α) := ⟨λ s, {a | ∀ t ∈ s, a ∈ t}⟩
instance : has_Sup (set α) := ⟨sUnion⟩
/-- Intersection of a set of sets. -/
def sInter (S : set (set α)) : set α := Inf S
prefix `⋂₀`:110 := sInter
@[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl
/-- Indexed union of a family of sets -/
def Union (s : ι → set β) : set β := supr s
/-- Indexed intersection of a family of sets -/
def Inter (s : ι → set β) : set β := infi s
notation `⋃` binders `, ` r:(scoped f, Union f) := r
notation `⋂` binders `, ` r:(scoped f, Inter f) := r
@[simp] lemma Sup_eq_sUnion (S : set (set α)) : Sup S = ⋃₀ S := rfl
@[simp] lemma Inf_eq_sInter (S : set (set α)) : Inf S = ⋂₀ S := rfl
@[simp] lemma supr_eq_Union (s : ι → set α) : supr s = Union s := rfl
@[simp] lemma infi_eq_Inter (s : ι → set α) : infi s = Inter s := rfl
@[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i :=
⟨λ ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩,
λ ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩
@[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i :=
⟨λ (h : ∀ a ∈ {a : set β | ∃ i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩,
λ h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩
theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := iff.rfl
instance : complete_boolean_algebra (set α) :=
{ Sup := Sup,
Inf := Inf,
le_Sup := λ s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩,
Sup_le := λ s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in,
le_Inf := λ s t h a a_in t' t'_in, h t' t'_in a_in,
Inf_le := λ s t t_in a h, h _ t_in,
infi_sup_le_sup_Inf := λ s S x, iff.mp $ by simp [forall_or_distrib_left],
inf_Sup_le_supr_inf := λ s S x, iff.mp $ by simp [exists_and_distrib_left],
.. set.boolean_algebra,
.. pi.complete_lattice }
/-- `set.image` is monotone. See `set.image_image` for the statement in terms of `⊆`. -/
lemma monotone_image {f : α → β} : monotone (image f) :=
λ s t, image_subset _
theorem monotone_inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) :=
λ b₁ b₂ h, inter_subset_inter (hf h) (hg h)
theorem monotone_union [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) :=
λ b₁ b₂ h, union_subset_union (hf h) (hg h)
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) :=
λ a a' h b, hp b h
section galois_connection
variables {f : α → β}
protected lemma image_preimage : galois_connection (image f) (preimage f) :=
λ a b, image_subset_iff
/-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/
def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s}
protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) :=
λ a b,
⟨ λ h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this,
λ h x (hx : f x ∈ a), h hx rfl⟩
end galois_connection
/-! ### Union and intersection over an indexed family of sets -/
@[congr] theorem Union_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Union f₁ = Union f₂ :=
supr_congr_Prop pq f
@[congr] theorem Inter_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Inter f₁ = Inter f₂ :=
infi_congr_Prop pq f
lemma Union_prop (f : ι → set α) (p : ι → Prop) (i : ι) [decidable $ p i] :
(⋃ (h : p i), f i) = if p i then f i else ∅ :=
begin
ext x,
rw mem_Union,
split_ifs; tauto,
end
@[simp]
lemma Union_prop_pos {p : ι → Prop} {i : ι} (hi : p i) (f : ι → set α) :
(⋃ (h : p i), f i) = f i :=
begin
classical,
ext x,
rw [Union_prop, if_pos hi]
end
@[simp]
lemma Union_prop_neg {p : ι → Prop} {i : ι} (hi : ¬ p i) (f : ι → set α) :
(⋃ (h : p i), f i) = ∅ :=
begin
classical,
ext x,
rw [Union_prop, if_neg hi]
end
lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β)
(w : (⋃ i ∈ t, s i) = ⊤) (x : β) :
∃ (i ∈ t), x ∈ s i :=
begin
have p : x ∈ ⊤ := set.mem_univ x,
simpa only [←w, set.mem_Union] using p,
end
lemma nonempty_of_union_eq_top_of_nonempty
{ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) :
t.nonempty :=
begin
obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some,
exact ⟨x, m⟩,
end
theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} :=
ext $ λ i, mem_Union.symm
theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} :=
ext $ λ i, mem_Inter.symm
theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t :=
-- TODO: should be simpler when sets' order is based on lattices
@supr_le (set β) _ _ _ _ h
theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) :=
⟨λ h i, subset.trans (le_supr s _) h, Union_subset⟩
theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) :=
mem_Inter.2
theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i :=
@le_infi (set β) _ _ _ _ h
theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i :=
@le_infi_iff (set β) _ _ _ _
theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr
/-- This rather trivial consequence of `subset_Union`is convenient with `apply`, and has `i`
explicit for this purpose. -/
theorem subset_subset_Union
{A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i :=
h.trans (subset_Union s i)
theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le
lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι)
(h : s i ⊆ t) : (⋂ i, s i) ⊆ t :=
set.subset.trans (set.Inter_subset s i) h
lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) :
(⋂ i, s i) ⊆ (⋂ i, t i) :=
set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i)
lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) :
(⋂ i, s i) ⊆ (⋂ j, t j) :=
set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi
lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x}) = {x : α | ∀ i, P i x} :=
by { ext, simp }
lemma Union_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂)
(h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y :=
supr_congr h h1 h2
lemma Inter_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂)
(h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y :=
infi_congr h h1 h2
theorem Union_const [nonempty ι] (s : set β) : (⋃ i : ι, s) = s := supr_const
theorem Inter_const [nonempty ι] (s : set β) : (⋂ i : ι, s) = s := infi_const
@[simp] theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) :=
compl_supr
@[simp] theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) :=
compl_infi
-- classical -- complete_boolean_algebra
theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ :=
by simp only [compl_Inter, compl_compl]
-- classical -- complete_boolean_algebra
theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ :=
by simp only [compl_Union, compl_compl]
theorem inter_Union (s : set β) (t : ι → set β) :
s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i :=
inf_supr_eq _ _
theorem Union_inter (s : set β) (t : ι → set β) :
(⋃ i, t i) ∩ s = ⋃ i, t i ∩ s :=
supr_inf_eq _ _
theorem Union_union_distrib (s : ι → set β) (t : ι → set β) :
(⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) :=
supr_sup_eq
theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) :
(⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) :=
infi_inf_eq
theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) :
s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i :=
sup_supr
theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) :
(⋃ i, t i) ∪ s = ⋃ i, t i ∪ s :=
supr_sup
theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) :
s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i :=
inf_infi
theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) :
(⋂ i, t i) ∩ s = ⋂ i, t i ∩ s :=
infi_inf
-- classical
theorem union_Inter (s : set β) (t : ι → set β) :
s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i :=
sup_infi_eq _ _
theorem Union_diff (s : set β) (t : ι → set β) :
(⋃ i, t i) \ s = ⋃ i, t i \ s :=
Union_inter _ _
theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) :
s \ (⋃ i, t i) = ⋂ i, s \ t i :=
by rw [diff_eq, compl_Union, inter_Inter]; refl
theorem diff_Inter (s : set β) (t : ι → set β) :
s \ (⋂ i, t i) = ⋃ i, s \ t i :=
by rw [diff_eq, compl_Inter, inter_Union]; refl
lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀ x, directed_on r (f x)) : directed_on r (⋃ x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
λ a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) :=
by { rintro x ⟨_, ⟨i, rfl⟩, xs, xt⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨i, rfl⟩, xt⟩ }
lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α}
(hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) :=
begin
ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩,
rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨j, rfl⟩, xt⟩,
exact ⟨_, ⟨i ⊔ j, rfl⟩, hs le_sup_left xs, ht le_sup_right xt⟩
end
/-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/
lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j :=
by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ }
lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) :=
supr_option s
lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) :=
infi_option s
/-! ### Unions and intersections indexed by `Prop` -/
@[simp] theorem Inter_false {s : false → set α} : Inter s = univ := infi_false
@[simp] theorem Union_false {s : false → set α} : Union s = ∅ := supr_false
@[simp] theorem Inter_true {s : true → set α} : Inter s = s trivial := infi_true
@[simp] theorem Union_true {s : true → set α} : Union s = s trivial := supr_true
@[simp] theorem Inter_exists {p : ι → Prop} {f : Exists p → set α} :
(⋂ x, f x) = (⋂ i (h : p i), f ⟨i, h⟩) :=
infi_exists
@[simp] theorem Union_exists {p : ι → Prop} {f : Exists p → set α} :
(⋃ x, f x) = (⋃ i (h : p i), f ⟨i, h⟩) :=
supr_exists
@[simp] lemma Union_empty : (⋃ i : ι, ∅ : set α) = ∅ := supr_bot
@[simp] lemma Inter_univ : (⋂ i : ι, univ : set α) = univ := infi_top
section
variables {s : ι → set α}
@[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot
@[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top
@[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty :=
by simp [← ne_empty_iff_nonempty]
end
@[simp] theorem Inter_Inter_eq_left {b : β} {s : Π x : β, x = b → set α} :
(⋂ x (h : x = b), s x h) = s b rfl :=
infi_infi_eq_left
@[simp] theorem Inter_Inter_eq_right {b : β} {s : Π x : β, b = x → set α} :
(⋂ x (h : b = x), s x h) = s b rfl :=
infi_infi_eq_right
@[simp] theorem Union_Union_eq_left {b : β} {s : Π x : β, x = b → set α} :
(⋃ x (h : x = b), s x h) = s b rfl :=
supr_supr_eq_left
@[simp] theorem Union_Union_eq_right {b : β} {s : Π x : β, b = x → set α} :
(⋃ x (h : b = x), s x h) = s b rfl :=
supr_supr_eq_right
theorem Inter_or {p q : Prop} (s : p ∨ q → set α) :
(⋂ h, s h) = (⋂ h : p, s (or.inl h)) ∩ (⋂ h : q, s (or.inr h)) :=
infi_or
theorem Union_or {p q : Prop} (s : p ∨ q → set α) :
(⋃ h, s h) = (⋃ i, s (or.inl i)) ∪ (⋃ j, s (or.inr j)) :=
supr_or
theorem Union_and {p q : Prop} (s : p ∧ q → set α) :
(⋃ h, s h) = ⋃ hp hq, s ⟨hp, hq⟩ :=
supr_and
theorem Inter_and {p q : Prop} (s : p ∧ q → set α) :
(⋂ h, s h) = ⋂ hp hq, s ⟨hp, hq⟩ :=
infi_and
theorem Union_comm (s : ι → ι' → set α) :
(⋃ i i', s i i') = ⋃ i' i, s i i' :=
supr_comm
theorem Inter_comm (s : ι → ι' → set α) :
(⋂ i i', s i i') = ⋂ i' i, s i i' :=
infi_comm
@[simp] theorem bUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) :
(⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) =
⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ :=
by simp only [Union_and, @Union_comm _ ι']
@[simp] theorem bUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) :
(⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) =
⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ :=
by simp only [Union_and, @Union_comm _ ι]
@[simp] theorem bInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) :
(⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) =
⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ :=
by simp only [Inter_and, @Inter_comm _ ι']
@[simp] theorem bInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) :
(⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) =
⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ :=
by simp only [Inter_and, @Inter_comm _ ι]
@[simp] theorem Union_Union_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} :
(⋃ x h, s x h) = s b (or.inl rfl) ∪ ⋃ x (h : p x), s x (or.inr h) :=
by simp only [Union_or, Union_union_distrib, Union_Union_eq_left]
@[simp] theorem Inter_Inter_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} :
(⋂ x h, s x h) = s b (or.inl rfl) ∩ ⋂ x (h : p x), s x (or.inr h) :=
by simp only [Inter_or, Inter_inter_distrib, Inter_Inter_eq_left]
/-! ### Bounded unions and intersections -/
theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp
lemma mem_bUnion_iff' {p : α → Prop} {t : α → set β} {y : β} :
y ∈ (⋃ i (h : p i), t i) ↔ ∃ i (h : p i), y ∈ t i :=
mem_bUnion_iff
theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp
theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) :
y ∈ ⋃ x ∈ s, t x :=
mem_bUnion_iff.2 ⟨x, ⟨xs, ytx⟩⟩
theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) :
y ∈ ⋂ x ∈ s, t x :=
mem_bInter_iff.2 h
theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) :
(⋃ x ∈ s, u x) ⊆ t :=
Union_subset $ λ x, Union_subset (h x)
theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) :
t ⊆ (⋂ x ∈ s, u x) :=
subset_Inter $ λ x, subset_Inter $ h x
theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) :
u x ⊆ (⋃ x ∈ s, u x) :=
show u x ≤ (⨆ x ∈ s, u x),
from le_supr_of_le x $ le_supr _ xs
theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) :
(⋂ x ∈ s, t x) ⊆ t x :=
show (⨅ x ∈ s, t x) ≤ t x,
from infi_le_of_le x $ infi_le _ xs
theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β}
(h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) :=
bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs))
theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β}
(h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) :=
subset_bInter (λ x xs, bInter_subset_of_mem (h xs))
theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) :=
bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs))
theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) :=
subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs))
theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β}
(h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) :
(⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) :=
begin
simp only [Union_subset_iff],
rintros a a_in x ha,
rcases h a a_in with ⟨c, c_in, hc⟩,
exact mem_bUnion c_in (hc ha)
end
theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) :=
begin
intros x x_in,
simp only [mem_Inter] at *,
exact λ a a_in, h a a_in $ x_in _ (hs a_in)
end
theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) :=
bInter_mono' (subset.refl s) h
theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) :=
bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩)
theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) :
(⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) :=
supr_subtype'
theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) :
(⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) :=
infi_subtype'
theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ :=
infi_emptyset
theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x :=
infi_univ
-- TODO(Jeremy): here is an artifact of the encoding of bounded intersection:
-- without dsimp, the next theorem fails to type check, because there is a lambda
-- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works.
theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a :=
infi_singleton
theorem bInter_union (s t : set α) (u : α → set β) :
(⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) :=
infi_union
theorem bInter_insert (a : α) (s : set α) (t : α → set β) :
(⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) :=
by simp
lemma bInter_lt_succ (f : ℕ → set α) (n : ℕ) : (⋂ i < n.succ, f i) = f n ∩ (⋂ i < n, f i) :=
ext $ λ a, begin
rw mem_inter_iff,
simp_rw [mem_Inter, nat.lt_succ_iff_lt_or_eq, or_imp_distrib],
rw [forall_and_distrib, forall_eq, and_comm],
end
-- TODO(Jeremy): another example of where an annotation is needed
theorem bInter_pair (a b : α) (s : α → set β) :
(⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b :=
by rw [bInter_insert, bInter_singleton]
lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) :
(⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t :=
begin
haveI : nonempty s := hs.to_subtype,
simp [bInter_eq_Inter, ← Inter_inter]
end
lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) :
(⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i :=
begin
rw [inter_comm, ← bInter_inter hs],
simp [inter_comm]
end
theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ :=
supr_emptyset
theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x :=
supr_univ
theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a :=
supr_singleton
@[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s :=
ext $ by simp
theorem bUnion_union (s t : set α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
@[simp] lemma Union_subtype {α β : Type*} (s : set α) (f : α → set β) :
(⋃ (i : s), f i) = ⋃ (i ∈ s), f i :=
(set.bUnion_eq_Union s $ λ x _, f x).symm
-- TODO(Jeremy): once again, simp doesn't do it alone.
theorem bUnion_insert (a : α) (s : set α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
by simp
lemma bUnion_lt_succ (f : ℕ → set α) (n : ℕ) : (⋃ i < n.succ, f i) = f n ∪ (⋃ i < n, f i) :=
ext $ λ a, begin
rw mem_union,
simp_rw [mem_Union, exists_prop, nat.lt_succ_iff_lt_or_eq, or_and_distrib_right],
rw [exists_or_distrib, exists_eq_left, or_comm],
end
theorem bUnion_pair (a b : α) (s : α → set β) :
(⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b :=
by simp
theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) :=
by simp
theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) :=
by simp
theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) :
u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i :=
by simp only [inter_Union]
theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) :
(⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) :=
by simp only [@inter_comm _ _ u, inter_bUnion]
theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) :
x ∈ ⋃₀ S :=
⟨t, ht, hx⟩
-- is this theorem really necessary?
theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)}
(hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t :=
λ h, hx ⟨t, ht, h⟩
theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t :=
Inf_le tS
theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S :=
le_Sup tS
lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u)
(h₂ : u ∈ t) : s ⊆ ⋃₀ t :=
subset.trans h₁ (subset_sUnion_of_mem h₂)
theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t :=
Sup_le h
theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t :=
⟨λ h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩
theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) :=
le_Inf h
theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T :=
sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs)
theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S :=
subset_sInter $ λ s hs, sInter_subset_of_mem (h hs)
@[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty
@[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty
@[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton
@[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton
@[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot
@[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top
@[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s :=
by simp [← ne_empty_iff_nonempty]
lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty :=
let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩
lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty :=
nonempty.of_sUnion $ h.symm ▸ univ_nonempty
theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union
theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union
theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i :=
begin
ext x,
simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib],
split; tauto
end
@[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T :=
Sup_insert
@[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T :=
Inf_insert
theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t :=
Sup_pair
theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t :=
Inf_pair
@[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image
@[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image
@[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl
@[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl
lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i :=
by simp only [eq_univ_iff_forall, mem_Union]
lemma bUnion_eq_univ_iff {f : α → set β} {s : set α} :
(⋃ x ∈ s, f x) = univ ↔ ∀ y, ∃ x ∈ s, y ∈ f x :=
by simp only [Union_eq_univ_iff, mem_Union]
lemma sUnion_eq_univ_iff {c : set (set α)} :
⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b :=
by simp only [eq_univ_iff_forall, mem_sUnion]
theorem compl_sUnion (S : set (set α)) :
(⋃₀ S)ᶜ = ⋂₀ (compl '' S) :=
ext $ λ x, by simp
-- classical
theorem sUnion_eq_compl_sInter_compl (S : set (set α)) :
⋃₀ S = (⋂₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋃₀ S), compl_sUnion]
-- classical
theorem compl_sInter (S : set (set α)) :
(⋂₀ S)ᶜ = ⋃₀ (compl '' S) :=
by rw [sUnion_eq_compl_sInter_compl, compl_compl_image]
-- classical
theorem sInter_eq_comp_sUnion_compl (S : set (set α)) :
⋂₀ S = (⋃₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋂₀ S), compl_sInter]
theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S)
(h : s ∩ ⋃₀ S = ∅) :
s ∩ t = ∅ :=
eq_empty_of_subset_empty $ by rw ← h; exact
inter_subset_inter_right _ (subset_sUnion_of_mem hs)
theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) :
range f = ⋃ a, range (λ b, f ⟨a, b⟩) :=
set.ext $ by simp
theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) :=
by simp [set.ext_iff]
theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) :
(⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s :=
begin
ext x,
simp only [mem_Union, mem_image, mem_preimage],
split,
{ rintro ⟨i, a, h, rfl⟩, exact h },
{ intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ }
end
lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) :=
sUnion_subset $ λ t' ht', subset_sUnion_of_mem $ h ht'
lemma Union_subset_Union {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋃ i, s i) ⊆ (⋃ i, t i) :=
@supr_le_supr (set α) ι _ s t h
lemma Union_subset_Union2 {s : ι → set α} {t : ι₂ → set α} (h : ∀ i, ∃ j, s i ⊆ t j) :
(⋃ i, s i) ⊆ (⋃ i, t i) :=
@supr_le_supr2 (set α) ι ι₂ _ s t h
lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i : ι, s) ⊆ (⋃ j : ι₂, s) :=
@supr_le_supr_const (set α) ι ι₂ _ s h
@[simp] lemma Union_of_singleton (α : Type*) : (⋃ x, {x} : set α) = univ :=
Union_eq_univ_iff.2 $ λ x, ⟨x, rfl⟩
@[simp] lemma Union_of_singleton_coe (s : set α) :
(⋃ (i : s), {i} : set α) = s :=
by simp
theorem bUnion_subset_Union (s : set α) (t : α → set β) :
(⋃ x ∈ s, t x) ⊆ (⋃ x, t x) :=
Union_subset_Union $ λ i, Union_subset $ λ h, by refl
lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) :=
by rw [← sUnion_image, image_id']
lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) :=
by rw [← sInter_image, image_id']
lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) :=
by simp only [←sUnion_range, subtype.range_coe]
lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) :=
by simp only [←sInter_range, subtype.range_coe]
lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ :=
sup_eq_supr s₁ s₂
lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ :=
inf_eq_infi s₁ s₂
lemma sInter_union_sInter {S T : set (set α)} :
(⋂₀ S) ∪ (⋂₀ T) = (⋂ p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) :=
Inf_sup_Inf
lemma sUnion_inter_sUnion {s t : set (set α)} :
(⋃₀ s) ∩ (⋃₀ t) = (⋃ p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) :=
Sup_inf_Sup
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection
of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/
lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)}
(hT : ∀ s ∈ S, s = ⋂₀ T s ‹s ∈ S›) :
⋂₀ (⋃ s ∈ S, T s ‹_›) = ⋂₀ S :=
begin
ext,
simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib],
split,
{ rintro H s sS,
rw [hT s sS, mem_sInter],
exact λ t, H t s sS },
{ rintro H t s sS tTs,
suffices : s ⊆ t, exact this (H s sS),
rw [hT s sS, sInter_eq_bInter],
exact bInter_subset_of_mem tTs }
end
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union
of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/
lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀ s ∈ S, s = ⋃₀ T s ‹_›) :
⋃₀ (⋃ s ∈ S, T s ‹_›) = ⋃₀ S :=
begin
ext,
simp only [exists_prop, set.mem_Union, set.mem_set_of_eq],
split,
{ rintro ⟨t, ⟨s, sS, tTs⟩, xt⟩,
refine ⟨s, sS, _⟩,
rw hT s sS,
exact subset_sUnion_of_mem tTs xt },
{ rintro ⟨s, sS, xs⟩,
rw hT s sS at xs,
rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩,
exact ⟨t, ⟨s, sS, tTs⟩, xt⟩ }
end
lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α))
{f : ∀ (s : C), β → s} (hf : ∀ (s : C), surjective (f s)) :
(⋃ (y : β), range (λ (s : C), (f s y).val)) = ⋃₀ C :=
begin
ext x, split,
{ rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 },
{ rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, _⟩,
exact congr_arg subtype.val hy }
end
lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α)
{f : ∀ (x : ι), β → C x} (hf : ∀ (x : ι), surjective (f x)) :
(⋃ (y : β), range (λ (x : ι), (f x y).val)) = ⋃ x, C x :=
begin
ext x, rw [mem_Union, mem_Union], split,
{ rintro ⟨y, i, rfl⟩, exact ⟨i, (f i y).2⟩ },
{ rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy,
exact ⟨y, i, congr_arg subtype.val hy⟩ }
end
lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) :
(⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) :=
begin
ext x,
rw [mem_union_eq, mem_Inter],
split; finish
end
lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) :
t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) :=
begin
rw [union_comm, union_distrib_Inter_right],
simp [union_comm]
end
lemma union_distrib_bInter_left {ι : Type*} (s : ι → set α) (u : set ι) (t : set α) :
t ∪ (⋂ i ∈ u, s i) = ⋂ i ∈ u, t ∪ s i :=
by rw [bInter_eq_Inter, bInter_eq_Inter, union_distrib_Inter_left]
lemma union_distrib_bInter_right {ι : Type*} (s : ι → set α) (u : set ι) (t : set α) :
(⋂ i ∈ u, s i) ∪ t = ⋂ i ∈ u, s i ∪ t :=
by rw [bInter_eq_Inter, bInter_eq_Inter, union_distrib_Inter_right]
section function
/-! ### `maps_to` -/
lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) :
maps_to f (⋃₀ S) t :=
λ x ⟨s, hs, hx⟩, H s hs hx
lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) :
maps_to f (⋃ i, s i) t :=
maps_to_sUnion $ forall_range_iff.2 H
lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β}
(H : ∀ i hi, maps_to f (s i hi) t) :
maps_to f (⋃ i hi, s i hi) t :=
maps_to_Union $ λ i, maps_to_Union (H i)
lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋃ i, s i) (⋃ i, t i) :=
maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i)
lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β}
{f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) :
maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) :=
maps_to_Union_Union $ λ i, maps_to_Union_Union (H i)
lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) :
maps_to f s (⋂₀ T) :=
λ x hx t ht, H t ht hx
lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) :
maps_to f s (⋂ i, t i) :=
λ x hx, mem_Inter.2 $ λ i, H i hx
lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β}
(H : ∀ i hi, maps_to f s (t i hi)) :
maps_to f s (⋂ i hi, t i hi) :=
maps_to_Inter $ λ i, maps_to_Inter (H i)
lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋂ i, s i) (⋂ i, t i) :=
maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _)
lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α}
{t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) :
maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) :=
maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i)
lemma image_Inter_subset (s : ι → set α) (f : α → β) :
f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) :=
(maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset
lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) :
f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) :=
(maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset
lemma image_sInter_subset (S : set (set α)) (f : α → β) :
f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s :=
by { rw sInter_eq_bInter, apply image_bInter_subset }
/-! ### `inj_on` -/
lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) :
f '' (⋂ i, s i) = ⋂ i, f '' (s i) :=
begin
inhabit ι,
refine subset.antisymm (image_Inter_subset s f) (λ y hy, _),
simp only [mem_Inter, mem_image_iff_bex] at hy,
choose x hx hy using hy,
refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩,
suffices : x (default ι) = x i,
{ rw this, apply hx },
replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i),
apply h (hx _) (hx _),
simp only [hy]
end
lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β}
(h : inj_on f (⋃ i hi, s i hi)) :
f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) :=
begin
simp only [Inter, infi_subtype'],
haveI : nonempty {i // p i} := nonempty_subtype.2 hp,
apply inj_on.image_Inter_eq,
simpa only [Union, supr_subtype'] using h
end
lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s)
{f : α → β} (hf : ∀ i, inj_on f (s i)) :
inj_on f (⋃ i, s i) :=
begin
intros x hx y hy hxy,
rcases mem_Union.1 hx with ⟨i, hx⟩,
rcases mem_Union.1 hy with ⟨j, hy⟩,
rcases hs i j with ⟨k, hi, hj⟩,
exact hf k (hi hx) (hj hy) hxy
end
/-! ### `surj_on` -/
lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) :
surj_on f s (⋃₀ T) :=
λ x ⟨t, ht, hx⟩, H t ht hx
lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) :
surj_on f s (⋃ i, t i) :=
surj_on_sUnion $ forall_range_iff.2 H
lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) :
surj_on f (⋃ i, s i) (⋃ i, t i) :=
surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _)
lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β}
(H : ∀ i hi, surj_on f s (t i hi)) :
surj_on f s (⋃ i hi, t i hi) :=
surj_on_Union $ λ i, surj_on_Union (H i)
lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β}
{f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) :
surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) :=
surj_on_Union_Union $ λ i, surj_on_Union_Union (H i)
lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β}
(H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) t :=
begin
intros y hy,
rw [Hinj.image_Inter_eq, mem_Inter],
exact λ i, H i hy
end
lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) (⋂ i, t i) :=
surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj
/-! ### `bij_on` -/
lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i))
(Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩
lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _),
surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩
lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β}
{f : α → β} (H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
end function
/-! ### `image`, `preimage` -/
section image
lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃ i, f '' s i) :=
begin
apply set.ext, intro x,
simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right],
exact exists_swap
end
lemma image_bUnion {f : α → β} {s : ι → set α} {p : ι → Prop} :
f '' (⋃ i (hi : p i), s i) = (⋃ i (hi : p i), f '' s i) :=
by simp only [image_Union]
lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃ x (h : p x), {⟨x, h⟩}) :=
set.ext $ λ ⟨x, h⟩, by simp [h]
lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃ i, {f i}) :=
set.ext $ λ a, by simp [@eq_comm α a]
lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃ i ∈ s, {f i}) :=
set.ext $ λ b, by simp [@eq_comm β b]
lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃ x ∈ range f, g x) = (⋃ y, g (f y)) :=
supr_range
@[simp] lemma Union_Union_eq' {f : ι → α} {g : α → set β} :
(⋃ x y (h : f y = x), g x) = ⋃ y, g (f y) :=
by simpa using bUnion_range
lemma bInter_range {f : ι → α} {g : α → set β} : (⋂ x ∈ range f, g x) = (⋂ y, g (f y)) :=
infi_range
@[simp] lemma Inter_Inter_eq' {f : ι → α} {g : α → set β} :
(⋂ x y (h : f y = x), g x) = ⋂ y, g (f y) :=
by simpa using bInter_range
variables {s : set γ} {f : γ → α} {g : α → set β}
lemma bUnion_image : (⋃ x ∈ f '' s, g x) = (⋃ y ∈ s, g (f y)) :=
supr_image
lemma bInter_image : (⋂ x ∈ f '' s, g x) = (⋂ y ∈ s, g (f y)) :=
infi_image
end image
section preimage
theorem monotone_preimage {f : α → β} : monotone (preimage f) := λ a b h, preimage_mono h
@[simp] theorem preimage_Union {ι : Sort*} {f : α → β} {s : ι → set β} :
f ⁻¹' (⋃ i, s i) = (⋃ i, f ⁻¹' s i) :=
set.ext $ by simp [preimage]
theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} :
f ⁻¹' (⋃ i ∈ s, t i) = (⋃ i ∈ s, f ⁻¹' (t i)) :=
by simp
@[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} :
f ⁻¹' (⋃₀ s) = (⋃ t ∈ s, f ⁻¹' t) :=
set.ext $ by simp [preimage]
lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} :
f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) :=
by ext; simp
lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} :
f ⁻¹' (⋂ i ∈ t, s i) = (⋂ i ∈ t, f ⁻¹' s i) :=
by ext; simp
@[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s :=
by rw [← preimage_bUnion, bUnion_of_singleton]
lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ :=
by rw [bUnion_preimage_singleton, preimage_range]
end preimage
section prod
theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λ x, (f x).prod (g x)) :=
λ a b h, prod_mono (hf h) (hg h)
alias monotone_prod ← monotone.set_prod
lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) :=
by { ext, simp }
lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} :
s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) :=
by simp_rw [prod_Union]
lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) :=
by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] }
lemma Union_prod_const {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t :=
by { ext, simp }
lemma bUnion_prod_const {ι} {u : set ι} {s : ι → set α} {t : set β} :
(⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t :=
by simp_rw [Union_prod_const]
lemma sUnion_prod_const {C : set (set α)} {t : set β} :
(⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) :=
by { simp only [sUnion_eq_bUnion, bUnion_prod_const, bUnion_image] }
lemma Union_prod {ι α β} (s : ι → set α) (t : ι → set β) :
(⋃ (x : ι × ι), (s x.1).prod (t x.2)) = (⋃ (i : ι), s i).prod (⋃ (i : ι), t i) :=
by { ext, simp }
lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ}
(hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) :=
begin
ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split,
{ intros x hz hw, exact ⟨⟨x, hz⟩, x, hw⟩ },
{ intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ }
end
end prod
section image2
variables (f : α → β → γ) {s : set α} {t : set β}
lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintro ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ }
lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintro ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩,
exact ⟨b, d, a, c, e⟩ }
lemma image2_Union_left (s : ι → set α) (t : set β) :
image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t :=
by simp only [← image_prod, Union_prod_const, image_Union]
lemma image2_Union_right (s : set α) (t : ι → set β) :
image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) :=
by simp only [← image_prod, prod_Union, image_Union]
end image2
section seq
/-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over
all `f ∈ s`. -/
def seq (s : set (α → β)) (t : set α) : set β := {b | ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b}
lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃ f ∈ s, f '' t :=
set.ext $ by simp [seq]
@[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} :
b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b :=
iff.rfl
lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} :
seq s t ⊆ u ↔ (∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u) :=
iff.intro
(λ h f hf a ha, h ⟨f, hf, a, ha, rfl⟩)
(λ h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha)
lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) :
seq s₀ t₀ ⊆ seq s₁ t₁ :=
λ b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩
lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t :=
set.ext $ by simp
lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λ f : α → β, f a) '' s :=
set.ext $ by simp
lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} :
seq s (seq t u) = seq (seq ((∘) '' s) t) u :=
begin
refine set.ext (λ c, iff.intro _ _),
{ rintro ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩,
exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ },
{ rintro ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩,
exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ }
end
lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} :
f '' seq s t = seq ((∘) f '' s) t :=
by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton]
lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t :=
begin
ext ⟨a, b⟩,
split,
{ rintro ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ },
{ rintro ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ }
end
lemma prod_image_seq_comm (s : set α) (t : set β) :
(prod.mk '' s).seq t = seq ((λ b a, (a, b)) '' t) s :=
by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap]
lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t :=
by { ext, simp }
end seq
/-! ### `set` as a monad -/
instance : monad set :=
{ pure := λ (α : Type u) a, {a},
bind := λ (α β : Type u) s f, ⋃ i ∈ s, f i,
seq := λ (α β : Type u), set.seq,
map := λ (α β : Type u), set.image }
section monad
variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')}
@[simp] lemma bind_def : s >>= f = ⋃ i ∈ s, f i := rfl
@[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl
@[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl
@[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl
end monad
instance : is_lawful_monad set :=
{ pure_bind := λ α β x f, by simp,
bind_assoc := λ α β γ s f g, set.ext $ λ a,
by simp [exists_and_distrib_right.symm, -exists_and_distrib_right,
exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc];
exact exists_swap,
id_map := λ α, id_map,
bind_pure_comp_eq_map := λ α β f s, set.ext $ by simp [set.image, eq_comm],
bind_map_eq_seq := λ α β s t, by simp [seq_def] }
instance : is_comm_applicative (set : Type u → Type u) :=
⟨ λ α β s t, prod_image_seq_comm s t ⟩
section pi
variables {π : α → Type*}
lemma pi_def (i : set α) (s : Π a, set (π a)) :
pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) :=
by { ext, simp }
lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i :=
by simp only [pi_def, Inter_true, mem_univ]
lemma pi_diff_pi_subset (i : set α) (s t : Π a, set (π a)) :
pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) :=
begin
refine diff_subset_comm.2 (λ x hx a ha, _),
simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply]
at hx,
exact hx.2 _ ha (hx.1 _ ha)
end
lemma Union_univ_pi (t : Π i, ι → set (π i)) :
(⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) :=
by { ext, simp [classical.skolem] }
end pi
end set
namespace function
namespace surjective
lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) :
(⋃ x, g (f x)) = ⋃ y, g y :=
hf.supr_comp g
lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) :
(⋂ x, g (f x)) = ⋂ y, g y :=
hf.infi_comp g
end surjective
end function
/-!
### Disjoint sets
We define some lemmas in the `disjoint` namespace to be able to use projection notation.
-/
section disjoint
variables {s t u : set α}
namespace disjoint
theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u :=
hs.sup_left ht
theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) :=
ht.sup_right hu
lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t :=
inf_left _ h
lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t :=
inf_left' _ h
lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) :=
inf_right _ h
lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) :=
inf_right' _ h
lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, h hx
end disjoint
namespace set
protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl
theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t :=
not_forall.trans $ exists_congr $ λ x, not_not
lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩
theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
d.mono_left h
theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
d.mono_right h
theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) :
disjoint s t :=
d.mono h1 h2
@[simp] theorem disjoint_union_left :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
disjoint_sup_left
@[simp] theorem disjoint_union_right :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_sup_right
@[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} :
disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t :=
supr_disjoint_iff
@[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} :
disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) :=
disjoint_supr_iff
theorem disjoint_diff {a b : set α} : disjoint a (b \ a) :=
disjoint_iff.2 (inter_diff_self _ _)
@[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left
@[simp] lemma univ_disjoint {s : set α} : disjoint univ s ↔ s = ∅ :=
top_disjoint
@[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ :=
disjoint_top
@[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s :=
by simp [set.disjoint_iff, subset_def]; exact iff.rfl
@[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s :=
by rw [disjoint.comm]; exact disjoint_singleton_left
theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ}
(h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : disjoint (f '' s) (g '' t) :=
by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq
theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) :
pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) :=
λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂)
lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) :
f ⁻¹' s = ∅ :=
by simpa using h.preimage f
lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ :=
⟨preimage_eq_empty,
λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩
end set
end disjoint
namespace set
/-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection
are disjoint. -/
def pairwise_disjoint (s : set (set α)) : Prop :=
pairwise_on s disjoint
lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t)
(ht : pairwise_disjoint t) : pairwise_disjoint s :=
pairwise_on.mono h ht
lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀ (x : s), f x ⊆ x.1)
(ht : pairwise_disjoint s) : pairwise_disjoint (range f) :=
begin
rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y),
intro h, apply hxy, apply congr_arg f, exact subtype.eq h
end
-- classical
lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α}
(hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y :=
not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩
end set
namespace set
variables (t : α → set β)
lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u :=
⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩,
λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩
/-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i`
sending `⟨i, x⟩` to `x`. -/
def sigma_to_Union (x : Σ i, t i) : (⋃ i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩
lemma sigma_to_Union_surjective : surjective (sigma_to_Union t)
| ⟨b, hb⟩ := have ∃ a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, b, hb⟩, rfl⟩
lemma sigma_to_Union_injective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) :
injective (sigma_to_Union t)
| ⟨a₁, b₁, h₁⟩ ⟨a₂, b₂, h₂⟩ eq :=
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ λ ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩,
h _ _ ne this,
sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq
lemma sigma_to_Union_bijective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) :
bijective (sigma_to_Union t) :=
⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩
/-- Equivalence between a disjoint union and a dependent sum. -/
noncomputable def Union_eq_sigma_of_disjoint {t : α → set β}
(h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : (⋃ i, t i) ≃ (Σ i, t i) :=
(equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm
/-- Equivalence between a disjoint bounded union and a dependent sum. -/
noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β}
(h : pairwise_on s (disjoint on t)) : (⋃ i ∈ s, t i) ≃ (Σ i : s, t i.val) :=
equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $
λ ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ λ eq, ne $ subtype.eq eq
end set
|
e46c48f344a044966679d98c620f01bf4d1a8ddb | c8b4b578b2fe61d500fbca7480e506f6603ea698 | /src/unused/tactic/may_assume.lean | 0d72420fae0e25097a0f7f5c08192720f88d8203 | [] | no_license | leanprover-community/flt-regular | aa7e564f2679dfd2e86015a5a9674a6e1197f7cc | 67fb3e176584bbc03616c221a7be6fa28c5ccd32 | refs/heads/master | 1,692,188,905,751 | 1,691,766,312,000 | 1,691,766,312,000 | 421,021,216 | 19 | 4 | null | 1,694,532,115,000 | 1,635,166,136,000 | Lean | UTF-8 | Lean | false | false | 5,557 | lean | import tactic
import data.nat.basic
import tactic.slim_check
/-
Example:
lemma ex (a b c : ℕ) (hab : a^2 + b^2 < c) : a + b < c :=
begin
may_assume h : a ≤ b,
{
-- state here is
-- (a b c : ℕ) (hab : a^2 + b^2 < c)
-- (this : ∀ (a b c : ℕ) (hab : a^2 + b^2 < c) (h : a ≤ b), a + b < c)
-- ⊢ a + b < c
},
-- state here is
-- (a b c : ℕ) (hab : a^2 + b^2 < c) (h : a ≤ b)
-- ⊢ a + b < c
end
-/
/- lemma ex (a b c : ℕ) (hab : a^2 + b^2 < c) : a + b < c :=
begin
have : ∀ (a b c : ℕ) (hab : a^2 + b^2 < c) (this : ∀ (a' b' c' : ℕ) (hab : a'^2 + b'^2 < c') (h : a' ≤ b'), a' + b' < c'),
a + b < c,
{ clear_except this,
intros,
-- state here is
-- (a b c : ℕ) (hab : a^2 + b^2 < c)
-- (this : ∀ (a b c : ℕ) (hab : a^2 + b^2 < c) (h : a ≤ b), a + b < c)
-- ⊢ a + b < c
cases le_total a b; specialize this _ _ c _ h,
assumption,
assumption,
rw add_comm,
assumption,
rw add_comm,
assumption, },
apply this a b c hab,
clear_except,
intros a b c hab h,
-- state here is
-- (a b c : ℕ) (hab : a^2 + b^2 < c) (h : a ≤ b)
-- ⊢ a + b < c
admit,
end -/
namespace tactic.interactive
open tactic expr
setup_tactic_parser
/-- auxiliary function for `apply_under_n_pis` -/
private meta def insert_under_n_pis_aux (na : name) (ty : expr) : ℕ → ℕ → expr → expr
| n 0 bd := expr.pi na binder_info.default ty (bd.lift_vars 0 1)
| n (k+1) (expr.pi nm bi tp bd) :=
expr.pi nm binder_info.default tp (insert_under_n_pis_aux (n+1) k bd)
| n (k+1) t := insert_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def insert_under_n_pis (na : name) (ty : expr) (pi_expr : expr) (n : ℕ) : expr :=
insert_under_n_pis_aux na ty 0 n (pi_expr)
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def insert_under_pis (na : name) (ty : expr) (pi_expr : expr) : expr :=
insert_under_n_pis na ty pi_expr pi_expr.pi_arity
meta def may_assume (h : parse ident?) (q₁ : parse (tk ":" *> texpr))
(wi : parse (tk "with" *> ident)?) (ot : parse (tk "else")?)
: tactic unit :=
let h := h.get_or_else `this,
wi := wi.get_or_else `h_red in
focus1 $ do
ls ← local_context,
q₂ ← to_expr q₁,
g ← get_goal,
⟨n,g⟩ ← goal_of_mvar g,
assert `h_red (insert_under_pis h (q₂.abstract_locals (ls.map local_uniq_name)) g),
-- s ← get_local wi,
-- let t : ident := wi,
focus1 `[clear_except h_red, introsI],
swap,
if ot.is_some then focus1 `[contrapose! h_red] else skip
end tactic.interactive
/- lemma ex' (a b c : ℕ) (hab : a^2 + b^2 < c) : a + b < c :=
begin
may_assume h : a ≤ b,
{ cases le_total a b; specialize h_red _ _ c _ h,
assumption,
assumption,
rw add_comm,
assumption,
rw add_comm,
assumption, },
admit
end -/
namespace tactic
namespace interactive
setup_tactic_parser
meta def doneif (h : parse ident?) (t : parse (tk ":" *> texpr))
(revert : parse (
(tk "generalizing" *> ((none <$ tk "*") <|> some <$> ident*)) <|> pure (some []))) :
tactic unit := do
let h := h.get_or_else `this,
t ← i_to_expr ``(%%t : Sort*),
(num_generalized, goal) ← retrieve (do
assert_core h t, swap,
num_generalized ← match revert with
| none := revert_all
| some revert := revert.mmap tactic.get_local >>= revert_lst
end,
goal ← target,
return (num_generalized, goal)),
tactic.assert h goal,
goal ← target,
(take_pi_args num_generalized goal).reverse.mmap' $ λ h,
try (tactic.get_local h >>= tactic.clear),
intron (num_generalized + 1)
meta def wlog' (h : parse ident?) (t : parse (tk ":" *> texpr)) : tactic unit :=
doneif h t none >> swap
end interactive
end tactic
lemma div_pow''' {a b : ℕ} (n : ℕ) (h : b ∣ a) : (a / b) ^ n = a ^ n / b ^ n :=
begin
by_cases hb : b = 0,
{ simp only [hb, zero_dvd_iff, eq_self_iff_true, nat.div_zero] at *,
rw h,
by_cases hn : n = 0,
simp only [hn, nat.lt_one_iff, nat.div_self, pow_zero],
rw zero_pow (pos_iff_ne_zero.mpr hn),
simp },
have hb : 0 < b := pos_iff_ne_zero.mpr hb,
-- have : 0 < b := by library_search,
rcases h with ⟨h_w, rfl⟩,
rw [mul_comm, mul_pow, nat.mul_div_cancel h_w hb, nat.mul_div_cancel (h_w ^ n) (pow_pos hb n)],
end
/-
lemma fermat (a b c n : ℕ) (hab : a^n + b^n = c^n) : a * b * c = 0 :=
begin
may_assume h : a.coprime b with h_red else,
{ use [a / a.gcd b, b / a.gcd b, c / a.gcd b, n],
simp,
push_neg,
split,
rw div_pow''',
rw div_pow''',
rw div_pow''',
admit,
admit,
exact nat.gcd_dvd_right a b,
exact nat.gcd_dvd_left a b,
split,
refine nat.coprime_div_gcd_div_gcd _,
contrapose h_red,
simp at h_red,
simp [h_red],
split,
split,
simp,
rw [nat.div_eq_zero_iff],
simp,
refine nat.le_of_dvd _ _,
admit,
exact nat.gcd_dvd_left a b,
admit,
admit,
admit, },
{ admit },
end -/
/- lemma test (a b : ℕ) : (a - b) * (b - a) = 0 :=
begin
may_assume h : a ≤ b with h_red else,
{ simp,
admit, },
{ admit },
end
lemma fermat' (a b c d n : ℕ) (hab : a^n + b^n = c^n) (hd : d^2 = 4) : a * b * c = 0 :=
begin
wlog' h : a.coprime b,
{ admit, },
{ admit },
end -/
|
a59e9004c0880f21aa616815dbb1e397ca2977d5 | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/algebra/algebra/subalgebra.lean | 9f116dca50f81f237b9211134c288c007af28637 | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,581 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.operations
/-!
# Subalgebras over Commutative Semiring
In this file we define `subalgebra`s and the usual operations on them (`map`, `comap'`).
More lemmas about `adjoin` can be found in `ring_theory.adjoin`.
-/
universes u v w
open_locale tensor_product big_operators
set_option old_structure_cmd true
/-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v :=
(algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier)
(zero_mem' := (algebra_map R A).map_zero ▸ algebra_map_mem' 0)
(one_mem' := (algebra_map R A).map_one ▸ algebra_map_mem' 1)
/-- Reinterpret a `subalgebra` as a `subsemiring`. -/
add_decl_doc subalgebra.to_subsemiring
namespace subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
include R
instance : set_like (subalgebra R A) A :=
⟨subalgebra.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
@[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x ∈ S.to_subsemiring ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (↑S.to_subsemiring : set A) = S := rfl
/-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : subalgebra R A :=
{ carrier := s,
add_mem' := hs.symm ▸ S.add_mem',
mul_mem' := hs.symm ▸ S.mul_mem',
algebra_map_mem' := hs.symm ▸ S.algebra_map_mem' }
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange ≤ S.to_subsemiring :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) ⊆ S :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) ≤ S :=
S.range_subset
theorem one_mem : (1 : A) ∈ S :=
S.to_subsemiring.one_mem
theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S :=
S.to_subsemiring.mul_mem hx hy
theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S :=
(algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx
theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
S.to_subsemiring.pow_mem hx n
theorem zero_mem : (0 : A) ∈ S :=
S.to_subsemiring.zero_mem
theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S :=
S.to_subsemiring.add_mem hx hy
theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S :=
neg_one_smul R x ▸ S.smul_mem hx _
theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S :=
by simpa only [sub_eq_add_neg] using S.add_mem hx (S.neg_mem hy)
theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S :=
S.to_subsemiring.nsmul_mem hx n
theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : ∀ (n : ℤ), n • x ∈ S
| (n : ℕ) := by { rw [gsmul_coe_nat], exact S.nsmul_mem hx n }
| -[1+ n] := by { rw [gsmul_neg_succ_of_nat], exact S.neg_mem (S.nsmul_mem hx _) }
theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S :=
S.to_subsemiring.coe_nat_mem n
theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S :=
int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1)
theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S :=
S.to_subsemiring.list_prod_mem h
theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S :=
S.to_subsemiring.list_sum_mem h
theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S :=
S.to_subsemiring.multiset_prod_mem m h
theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S :=
S.to_subsemiring.multiset_sum_mem m h
theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S :=
S.to_subsemiring.prod_mem h
theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S :=
S.to_subsemiring.sum_mem h
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_add_submonoid (S : set A) :=
{ zero_mem := S.zero_mem,
add_mem := λ _ _, S.add_mem }
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_submonoid (S : set A) :=
{ one_mem := S.one_mem,
mul_mem := λ _ _, S.mul_mem }
/-- A subalgebra over a ring is also a `subring`. -/
def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
subring A :=
{ neg_mem' := λ _, S.neg_mem,
.. S.to_subsemiring }
@[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} {x} : x ∈ S.to_subring ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : (↑S.to_subring : set A) = S := rfl
instance {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
is_subring (S : set A) :=
{ neg_mem := λ _, S.neg_mem }
instance : inhabited S := ⟨(0 : S.to_subsemiring)⟩
section
/-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/
instance to_semiring {R A}
[comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) :
semiring S := S.to_subsemiring.to_semiring
instance to_comm_semiring {R A}
[comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) :
comm_semiring S := S.to_subsemiring.to_comm_semiring
instance to_ring {R A}
[comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
ring S := S.to_subring.to_ring
instance to_comm_ring {R A}
[comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) :
comm_ring S := S.to_subring.to_comm_ring
instance to_ordered_semiring {R A}
[comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_semiring S := S.to_subsemiring.to_ordered_semiring
instance to_ordered_comm_semiring {R A}
[comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring
instance to_ordered_ring {R A}
[comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) :
ordered_ring S := S.to_subring.to_ordered_ring
instance to_ordered_comm_ring {R A}
[comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_ring S := S.to_subring.to_ordered_comm_ring
instance to_linear_ordered_semiring {R A}
[comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring
/-! There is no `linear_ordered_comm_semiring`. -/
instance to_linear_ordered_ring {R A}
[comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_ring S := S.to_subring.to_linear_ordered_ring
instance to_linear_ordered_comm_ring {R A}
[comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring
end
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1, S.smul_mem x.2 c⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_srestrict S.to_subsemiring $ λ x, S.range_le ⟨x, rfl⟩ }
instance to_algebra {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B]
[algebra R A] [algebra A B] (A₀ : subalgebra R A) : algebra A₀ B :=
algebra.of_subsemiring A₀.to_subsemiring
instance nontrivial [nontrivial A] : nontrivial S :=
S.to_subsemiring.nontrivial
instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S :=
⟨λ c x h,
have c = 0 ∨ (x : A) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩
@[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : S) : A) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : S) : A) = 1 := rfl
@[simp, norm_cast] lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl
@[simp, norm_cast] lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl
@[simp, norm_cast] lemma coe_smul (r : R) (x : S) : (↑(r • x) : A) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_algebra_map (r : R) : ↑(algebra_map R S r) = algebra_map R A r :=
rfl
@[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x^n) : A) = (↑x)^n :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
@[simp, norm_cast] lemma coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 :=
(subtype.ext_iff.symm : (x : A) = (0 : S) ↔ x = 0)
@[simp, norm_cast] lemma coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 :=
(subtype.ext_iff.symm : (x : A) = (1 : S) ↔ x = 1)
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := (coe : S → A) }; intros; refl
@[simp] lemma coe_val : (S.val : S → A) = coe := rfl
lemma val_apply (x : S) : S.val x = (x : A) := rfl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸
(⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance to_submodule.is_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : is_subring (S.to_submodule : set A) := S.is_subring
@[simp] lemma mem_to_submodule {x} : x ∈ S.to_submodule ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_submodule (S : subalgebra R A) : (↑S.to_submodule : set A) = S := rfl
theorem to_submodule_injective :
function.injective (to_submodule : subalgebra R A → submodule R A) :=
λ S T h, ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule ↔ S = U :=
to_submodule_injective.eq_iff
/-- As submodules, subalgebras are idempotent. -/
@[simp] theorem mul_self : S.to_submodule * S.to_submodule = S.to_submodule :=
begin
apply le_antisymm,
{ rw submodule.mul_le,
intros y hy z hz,
exact mul_mem S hy hz },
{ intros x hx1,
rw ← mul_one x,
exact submodule.mul_mem_mul hx1 (one_mem S) }
end
/-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal,
we define it as a `linear_equiv` to avoid type equalities. -/
def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ≃ₗ[R] S :=
linear_equiv.of_eq _ _ rfl
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ algebra_map_mem' := λ r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩,
.. T }
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r),
.. S.to_subsemiring.map (f : A →+* B) }
lemma map_mono {S₁ S₂ : subalgebra R A} {f : A →ₐ[R] B} :
S₁ ≤ S₂ → S₁.map f ≤ S₂.map f :=
set.image_subset f
lemma map_injective {S₁ S₂ : subalgebra R A} (f : A →ₐ[R] B)
(hf : function.injective f) (ih : S₁.map f = S₂.map f) : S₁ = S₂ :=
ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih
lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} :
y ∈ map S f ↔ ∃ x ∈ S, f x = y :=
subsemiring.mem_map
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A :=
{ algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S,
from (f.commutes r).symm ▸ S.algebra_map_mem r,
.. S.to_subsemiring.comap (f : A →+* B) }
theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} :
map S f ≤ U ↔ S ≤ comap' U f :=
set.image_subset_iff
@[simp] lemma mem_comap (S : subalgebra R B) (f : A →ₐ[R] B) (x : A) :
x ∈ S.comap' f ↔ f x ∈ S :=
iff.rfl
@[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A →ₐ[R] B) :
(S.comap' f : set A) = f ⁻¹' (S : set B) :=
by { ext, simp, }
instance no_zero_divisors {R A : Type*} [comm_ring R] [semiring A] [no_zero_divisors A]
[algebra R A] (S : subalgebra R A) : no_zero_divisors S :=
S.to_subsemiring.no_zero_divisors
instance no_zero_smul_divisors_top {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A]
[no_zero_divisors A] (S : subalgebra R A) : no_zero_smul_divisors S A :=
⟨λ c x h,
have (c : A) = 0 ∨ x = 0,
from eq_zero_or_eq_zero_of_mul_eq_zero h,
this.imp_left (@subtype.ext_iff _ _ c 0).mpr⟩
instance integral_domain {R A : Type*} [comm_ring R] [integral_domain A] [algebra R A]
(S : subalgebra R A) : integral_domain S :=
@subring.domain A _ S _
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩,
.. φ.to_ring_hom.srange }
@[simp] lemma mem_range (φ : A →ₐ[R] B) {y : B} :
y ∈ φ.range ↔ ∃ x, φ x = y := ring_hom.mem_srange
theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (φ : A →ₐ[R] B) : (φ.range : set B) = set.range φ :=
by { ext, rw [set_like.mem_coe, mem_range], refl }
/-- Restrict the codomain of an algebra homomorphism. -/
def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S :=
{ commutes' := λ r, subtype.eq $ f.commutes r,
.. ring_hom.cod_srestrict (f : A →+* B) S.to_subsemiring hf }
@[simp] lemma val_comp_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
S.val.comp (f.cod_restrict S hf) = f :=
alg_hom.ext $ λ _, rfl
@[simp] lemma coe_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) :
↑(f.cod_restrict S hf x) = f x := rfl
theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
function.injective (f.cod_restrict S hf) ↔ function.injective f :=
⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩
/-- Restrict the codomain of a alg_hom `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : A →ₐ[R] B) : A →ₐ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The equalizer of two R-algebra homomorphisms -/
def equalizer (ϕ ψ : A →ₐ[R] B) : subalgebra R A :=
{ carrier := {a | ϕ a = ψ a},
add_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x + y) = ψ (x + y),
rw [alg_hom.map_add, alg_hom.map_add, hx, hy] },
mul_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x * y) = ψ (x * y),
rw [alg_hom.map_mul, alg_hom.map_mul, hx, hy] },
algebra_map_mem' := λ x, by
{ change ϕ (algebra_map R A x) = ψ (algebra_map R A x),
rw [alg_hom.commutes, alg_hom.commutes] } }
@[simp] lemma mem_equalizer (ϕ ψ : A →ₐ[R] B) (x : A) :
x ∈ ϕ.equalizer ψ ↔ ϕ x = ψ x := iff.rfl
/-- The range of a morphism of algebras is a fintype, if the domain is a fintype.
Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/
instance fintype_range [fintype A] [decidable_eq B] (φ : A →ₐ[R] B) : fintype φ.range :=
set.fintype_range φ
end alg_hom
namespace alg_equiv
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
/-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range.
This is a computable alternative to `alg_equiv.of_injective`. -/
def of_left_inverse
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) :
A ≃ₐ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.val,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := f.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 : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : A) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Restrict an injective algebra homomorphism to an algebra isomorphism -/
noncomputable def of_injective (f : A →ₐ[R] B) (hf : function.injective f) :
A ≃ₐ[R] f.range :=
of_left_inverse (classical.some_spec hf.has_left_inverse)
@[simp] lemma of_injective_apply (f : A →ₐ[R] B) (hf : function.injective f) (x : A) :
↑(of_injective f hf x) = f x := rfl
/-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/
noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F]
[nontrivial F] [algebra R E] [algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range :=
of_injective f f.to_ring_hom.injective
end alg_equiv
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩,
.. subsemiring.closure (set.range (algebra_map R A) ∪ s) }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
λ H, show subsemiring.closure (set.range (algebra_map R A) ∪ s) ≤ S.to_subsemiring,
from subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, set_like.coe_injective $ by { generalize_proofs h, exact h } }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
@[simp]
lemma coe_top : (↑(⊤ : subalgebra R A) : set A) = set.univ := rfl
@[simp] lemma mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
set.mem_univ x
@[simp] lemma top_to_submodule : (⊤ : subalgebra R A).to_submodule = ⊤ := rfl
@[simp] lemma top_to_subsemiring : (⊤ : subalgebra R A).to_subsemiring = ⊤ := rfl
@[simp, norm_cast]
lemma coe_inf (S T : subalgebra R A) : (↑(S ⊓ T) : set A) = S ∩ T := rfl
@[simp]
lemma mem_inf {S T : subalgebra R A} {x : A} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
@[simp] lemma inf_to_submodule (S T : subalgebra R A) :
(S ⊓ T).to_submodule = S.to_submodule ⊓ T.to_submodule := rfl
@[simp] lemma inf_to_subsemiring (S T : subalgebra R A) :
(S ⊓ T).to_subsemiring = S.to_subsemiring ⊓ T.to_subsemiring := rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (subalgebra R A)) : (↑(Inf S) : set A) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) :
(Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) :=
set_like.coe_injective $ by simp
@[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) :
(Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) :=
set_like.coe_injective $ by simp
@[simp, norm_cast]
lemma coe_infi {ι : Sort*} {S : ι → subalgebra R A} : (↑(⨅ i, S i) : set A) = ⋂ i, S i :=
set.bInter_range
lemma mem_infi {ι : Sort*} {S : ι → subalgebra R A} {x : A} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp] lemma infi_to_submodule {ι : Sort*} (S : ι → subalgebra R A) :
(⨅ i, S i).to_submodule = ⨅ i, (S i).to_submodule :=
set_like.coe_injective $ by simp
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) :=
suffices (of_id R A).range = (⊥ : subalgebra R A),
by { rw [← this, ←set_like.mem_coe, alg_hom.coe_range], refl },
le_bot_iff.mp (λ x hx, subalgebra.range_le _ ((of_id R A).coe_range ▸ hx))
theorem to_submodule_bot : (⊥ : subalgebra R A).to_submodule = R ∙ 1 :=
by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] }
@[simp] theorem coe_bot : ((⊥ : subalgebra R A) : set A) = set.range (algebra_map R A) :=
by simp [set.ext_iff, algebra.mem_bot]
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
@[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range :=
subalgebra.ext $ λ x,
⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩
@[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ :=
eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _
⟨r, by rwa [← f.commutes, hr]⟩
@[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ :=
eq_top_iff.2 $ λ x, mem_top
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
theorem surjective_algebra_map_iff :
function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _,
λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩
theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A]
[algebra R A] :
function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, surjective_algebra_map_iff.1 h.2,
λ h, ⟨(algebra_map R A).injective, surjective_algebra_map_iff.2 h⟩⟩
/-- The bottom subalgebra is isomorphic to the base ring. -/
noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) :
(⊥ : subalgebra R A) ≃ₐ[R] R :=
alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _)
⟨λ x y hxy, h (congr_arg subtype.val hxy : _),
λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩
/-- The bottom subalgebra is isomorphic to the field. -/
noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] :
(⊥ : subalgebra F R) ≃ₐ[F] F :=
bot_equiv_of_injective (ring_hom.injective _)
/-- The top subalgebra is isomorphic to the field. -/
noncomputable def top_equiv : (⊤ : subalgebra R A) ≃ₐ[R] A :=
(alg_equiv.of_bijective to_top ⟨λ _ _, subtype.mk.inj,
λ x, ⟨x.val, by { ext, refl }⟩⟩ : A ≃ₐ[R] (⊤ : subalgebra R A)).symm
end algebra
namespace subalgebra
open algebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
variables (S : subalgebra R A)
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) :=
⟨λ B C, ext (λ x, by { simp only [subsingleton.elim x 0, zero_mem] })⟩
/--
For performance reasons this is not an instance. If you need this instance, add
```
local attribute [instance] alg_hom.subsingleton subalgebra.subsingleton_of_subsingleton
```
in the section that needs it.
-/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A →ₐ[R] B) :=
⟨λ f g, alg_hom.ext $ λ a,
have a ∈ (⊥ : subalgebra R A) := subsingleton.elim (⊤ : subalgebra R A) ⊥ ▸ mem_top,
let ⟨x, hx⟩ := set.mem_range.mp (mem_bot.mp this) in
hx ▸ (f.commutes _).trans (g.commutes _).symm⟩
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] :
subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (A →ₐ[R] B) := alg_hom.subsingleton,
exact ⟨λ f g, alg_equiv.ext
(λ x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)⟩,
end
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] :
subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (B ≃ₐ[R] A) := alg_equiv.subsingleton_left,
exact ⟨λ f g, eq.trans (alg_equiv.symm_symm _).symm
(by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])⟩
end
lemma range_val : S.val.range = S :=
ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val
instance : unique (subalgebra R R) :=
{ uniq :=
begin
intro S,
refine le_antisymm (λ r hr, _) bot_le,
simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default],
end
.. algebra.subalgebra.inhabited }
/-- Two subalgebras that are equal are also equivalent as algebras.
This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/
@[simps apply]
def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ≃ₐ[R] T :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
map_mul' := λ _ _, rfl,
commutes' := λ _, rfl,
.. linear_equiv.of_eq _ _ (congr_arg to_submodule h) }
@[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) :
(equiv_of_eq S T h).symm = equiv_of_eq T S h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) :
equiv_of_eq S S rfl = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) :
(equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) :=
rfl
section prod
variables (S₁ : subalgebra R B)
/-- The product of two subalgebras is a subalgebra. -/
def prod : subalgebra R (A × B) :=
{ carrier := set.prod S S₁,
algebra_map_mem' := λ r, ⟨algebra_map_mem _ _, algebra_map_mem _ _⟩,
.. S.to_subsemiring.prod S₁.to_subsemiring }
@[simp] lemma coe_prod :
(prod S S₁ : set (A × B)) = set.prod S S₁ := rfl
lemma prod_to_submodule :
(S.prod S₁).to_submodule = S.to_submodule.prod S₁.to_submodule := rfl
@[simp] lemma mem_prod {S : subalgebra R A} {S₁ : subalgebra R B} {x : A × B} :
x ∈ prod S S₁ ↔ x.1 ∈ S ∧ x.2 ∈ S₁ := set.mem_prod
@[simp] lemma prod_top : (prod ⊤ ⊤ : subalgebra R (A × B)) = ⊤ :=
by ext; simp
lemma prod_mono {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} :
S ≤ T → S₁ ≤ T₁ → prod S S₁ ≤ prod T T₁ := set.prod_mono
@[simp] lemma prod_inf_prod {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} :
S.prod S₁ ⊓ T.prod T₁ = (S ⊓ T).prod (S₁ ⊓ T₁) :=
set_like.coe_injective set.prod_inter_prod
end prod
end subalgebra
section nat
variables {R : Type*} [semiring R]
/-- A subsemiring is a `ℕ`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R :=
{ algebra_map_mem' := λ i, S.coe_nat_mem i,
.. S }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x ∈ subalgebra_of_subsemiring S ↔ x ∈ S :=
iff.rfl
end nat
section int
variables {R : Type*} [ring R]
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : subring R) : subalgebra ℤ R :=
{ algebra_map_mem' := λ i, int.induction_on i S.zero_mem
(λ i ih, S.add_mem ih S.one_mem)
(λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one],
exact S.sub_mem ih S.one_mem }),
.. S }
/-- A subset closed under the ring operations is a `ℤ`-subalgebra. -/
def subalgebra_of_is_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
subalgebra_of_subring S.to_subring
variables {S : Type*} [semiring S]
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_subalgebra_of_is_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_is_subring S ↔ x ∈ S :=
iff.rfl
end int
|
a840bf473d8c8a39202072e1bfae7389805b4700 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/data/complex/basic.lean | fa241583bda65096d12c954cc501ba10a8fad198 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 27,712 | 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
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 : 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 -/
instance : comm_ring ℂ :=
by refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, sub := has_sub.sub, one := 1,
mul := (*), nsmul := @nsmul_rec _ ⟨(0)⟩ ⟨(+)⟩, npow := @npow_rec _ ⟨(1)⟩ ⟨(*)⟩,
gsmul := @gsmul_rec _ ⟨(0)⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ };
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 -/
/-- The complex conjugate. -/
def conj : ℂ →+* ℂ :=
begin
refine_struct { to_fun := λ z : ℂ, (⟨z.re, -z.im⟩ : ℂ), .. };
{ intros, ext; simp [add_comm], },
end
@[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
@[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z :=
ext_iff.2 $ by simp
lemma conj_involutive : function.involutive conj := conj_conj
lemma conj_bijective : function.bijective conj := conj_involutive.bijective
lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w :=
conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 :=
by simpa using @conj_inj z 0
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 conj_sub (z z': ℂ) : conj (z - z') = conj z - conj z' := conj.map_sub z z'
lemma conj_one : conj 1 = 1 := by rw conj.map_one
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))⟩
instance : star_ring ℂ :=
{ star := λ z, conj z,
star_involutive := λ z, by simp,
star_mul := λ r s, by { ext; simp [mul_comm], },
star_add := by simp, }
/-! ### 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 [-mul_re, add_comm, add_left_comm, sub_eq_add_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'` := _root_.abs
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = abs' 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 : ℂ) : abs' 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 : ℂ) : abs' 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' (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' (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 ≤ abs' z.re + abs' z.im :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
lemma abs_re_div_abs_le_one (z : ℂ) : abs' (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 : ℂ) : abs' (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 : ℤ) : ↑(abs' 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.
-/
def complex_order : partial_order ℂ :=
{ le := λ z w, ∃ x : ℝ, 0 ≤ x ∧ w = z + x,
le_refl := λ x, ⟨0, by simp⟩,
le_trans := λ x y z h₁ h₂,
begin
obtain ⟨w₁, l₁, rfl⟩ := h₁,
obtain ⟨w₂, l₂, rfl⟩ := h₂,
refine ⟨w₁ + w₂, _, _⟩,
{ linarith, },
{ simp [add_assoc], },
end,
le_antisymm := λ z w h₁ h₂,
begin
obtain ⟨w₁, l₁, rfl⟩ := h₁,
obtain ⟨w₂, l₂, e⟩ := h₂,
have h₃ : w₁ + w₂ = 0,
{ symmetry,
rw add_assoc at e,
apply of_real_inj.mp,
apply add_left_cancel,
convert e; simp, },
have h₄ : w₁ = 0, linarith,
simp [h₄],
end, }
localized "attribute [instance] complex_order" in complex_order
section complex_order
open_locale complex_order
lemma le_def {z w : ℂ} : z ≤ w ↔ ∃ x : ℝ, 0 ≤ x ∧ w = z + x := iff.refl _
lemma lt_def {z w : ℂ} : z < w ↔ ∃ x : ℝ, 0 < x ∧ w = z + x :=
begin
rw [lt_iff_le_not_le],
fsplit,
{ rintro ⟨⟨x, l, rfl⟩, h⟩,
by_cases hx : x = 0,
{ simpa [hx] using h },
{ replace l : 0 < x := l.lt_of_ne (ne.symm hx),
exact ⟨x, l, rfl⟩, } },
{ rintro ⟨x, l, rfl⟩,
fsplit,
{ exact ⟨x, l.le, rfl⟩, },
{ rintro ⟨x', l', e⟩,
rw [add_assoc] at e,
replace e := add_left_cancel (by { convert e, simp }),
norm_cast at e,
linarith, } }
end
@[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y :=
begin
rw [le_def],
fsplit,
{ rintro ⟨r, l, e⟩,
norm_cast at e,
subst e,
exact le_add_of_nonneg_right l, },
{ intro h,
exact ⟨y - x, sub_nonneg.mpr h, (by simp)⟩, },
end
@[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y :=
begin
rw [lt_def],
fsplit,
{ rintro ⟨r, l, e⟩,
norm_cast at e,
subst e,
exact lt_add_of_pos_right x l, },
{ intro h,
exact ⟨y - x, sub_pos.mpr h, (by simp)⟩, },
end
@[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
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring.
-/
def complex_ordered_comm_ring : ordered_comm_ring ℂ :=
{ zero_le_one := ⟨1, zero_le_one, by simp⟩,
add_le_add_left := λ w z h y,
begin
obtain ⟨x, l, rfl⟩ := h,
exact ⟨x, l, by simp [add_assoc]⟩,
end,
mul_pos := λ z w hz hw,
begin
obtain ⟨zx, lz, rfl⟩ := lt_def.mp hz,
obtain ⟨wx, lw, rfl⟩ := lt_def.mp hw,
norm_cast,
simp only [mul_pos, lz, lw, zero_add],
end,
le_of_add_le_add_left := λ u v z h,
begin
obtain ⟨x, l, e⟩ := h,
rw add_assoc at e,
exact ⟨x, l, add_left_cancel e⟩,
end,
mul_lt_mul_of_pos_left := λ u v z h₁ h₂,
begin
obtain ⟨x₁, l₁, rfl⟩ := lt_def.mp h₁,
obtain ⟨x₂, l₂, rfl⟩ := lt_def.mp h₂,
simp only [mul_add, zero_add],
exact lt_def.mpr ⟨x₂ * x₁, mul_pos l₂ l₁, (by norm_cast)⟩,
end,
mul_lt_mul_of_pos_right := λ u v z h₁ h₂,
begin
obtain ⟨x₁, l₁, rfl⟩ := lt_def.mp h₁,
obtain ⟨x₂, l₂, rfl⟩ := lt_def.mp h₂,
simp only [add_mul, zero_add],
exact lt_def.mpr ⟨x₁ * x₂, mul_pos l₁ l₂, (by norm_cast)⟩,
end,
-- we need more instances here because comm_ring doesn't have zero_add et al as fields,
-- they are derived as lemmas
..(by apply_instance : partial_order ℂ),
..(by apply_instance : comm_ring ℂ),
..(by apply_instance : comm_semiring ℂ),
..(by apply_instance : add_cancel_monoid ℂ) }
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.
-/
def complex_star_ordered_ring : star_ordered_ring ℂ :=
{ star_mul_self_nonneg := λ z,
begin
refine ⟨z.abs^2, pow_nonneg (abs_nonneg z) 2, _⟩,
simp only [has_star.star, of_real_pow, zero_add],
norm_cast,
rw [←norm_sq_eq_abs, norm_sq_eq_conj_mul_self],
end, }
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 [← conj.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
|
6503b7ce34f7cccad7d6680ff609cfc9b49f7cb0 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/pp_unit.lean | 7da0045fbd277fad2198d3167ce859e8cb39689a | [
"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 | 57 | lean | check unit.star
check ()
set_option pp.all true
check ()
|
e935c0c75da7b1190de57e16c68af9bc3b4fd9c2 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/instances/ennreal.lean | e9ad2a2e5ff23ad13633d59225614acf5e6c1216 | [
"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 | 64,183 | 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 topology.instances.nnreal
import order.liminf_limsup
import topology.metric_space.lipschitz
import topology.algebra.order.monotone_continuity
/-!
# Extended non-negative reals
-/
noncomputable theory
open classical set filter metric
open_locale classical topological_space ennreal nnreal big_operators filter
variables {α : Type*} {β : Type*} {γ : Type*}
namespace ennreal
variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0}
variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞}
section topological_space
open topological_space
/-- Topology on `ℝ≥0∞`.
Note: this is different from the `emetric_space` topology. The `emetric_space` topology has
`is_open {⊤}`, while this topology doesn't have singleton elements. -/
instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞
instance : order_topology ℝ≥0∞ := ⟨rfl⟩
instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference
instance : normal_space ℝ≥0∞ := normal_of_compact_t2
instance : second_countable_topology ℝ≥0∞ :=
order_iso_unit_interval_birational.to_homeomorph.embedding.second_countable_topology
lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) :=
⟨⟨begin
refine le_antisymm _ _,
{ rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _,
← coinduced_le_iff_le_induced],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
show is_open {b : ℝ≥0 | a < ↑b},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] },
show is_open {b : ℝ≥0 | ↑b < a},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } },
{ rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩,
exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ }
end⟩,
assume a b, coe_eq_coe.1⟩
lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne
lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio}
lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) :=
⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩
lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) :=
is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _
@[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} :
tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) :=
embedding_coe.tendsto_nhds_iff.symm
lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) :=
embedding_coe.continuous
lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} :
continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f :=
embedding_coe.continuous_iff.symm
lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe :=
(open_embedding_coe.map_nhds_eq r).symm
lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} :
tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l :=
show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map]
lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} :
continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x :=
tendsto_nhds_coe_iff
lemma nhds_coe_coe {r p : ℝ≥0} :
𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) :=
((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm
lemma continuous_of_real : continuous ennreal.of_real :=
(continuous_coe_iff.2 continuous_id).comp continuous_real_to_nnreal
lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) :
tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) :=
tendsto.comp (continuous.tendsto continuous_of_real _) h
lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) :
tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) :=
begin
lift a to ℝ≥0 using ha,
rw [nhds_coe, tendsto_map'_iff],
exact tendsto_id
end
lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞}
(hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞)
(hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) :
f =ᶠ[l] g :=
begin
filter_upwards [hfi, hgi, hfg] with _ hfx hgx _,
rwa ← ennreal.to_real_eq_to_real hfx hgx,
end
lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} :=
λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha)
lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) :=
nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha
/-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/
def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 :=
{ continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal,
continuous_inv_fun := continuous_subtype_mk _ continuous_coe,
.. ne_top_equiv_nnreal }
/-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/
def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 :=
by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal;
simp only [mem_set_of_eq, lt_top_iff_ne_top]
lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) :=
nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi]
lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) :=
nhds_top.trans $ infi_ne_top _
lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis
lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a :=
by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi]
lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a :=
tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n,
λ h x, let ⟨n, hn⟩ := exists_nat_gt x in
(h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩
lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α}
(h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) :=
tendsto_nhds_top_iff_nat.2 h
lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) :=
tendsto_nhds_top $ λ n, mem_at_top_sets.2
⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩
@[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} :
tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top :=
by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff];
[simp, apply_instance, apply_instance]
lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) :=
nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio]
lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis
lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic
@[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[>] (r : ℝ≥0∞)).ne_bot :=
nhds_within_Ioi_self_ne_bot' ⟨⊤, ennreal.coe_lt_top⟩
@[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[>] (0 : ℝ≥0∞)).ne_bot :=
nhds_within_Ioi_coe_ne_bot
-- using Icc because
-- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0
-- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not
lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x :=
begin
rw _root_.mem_nhds_iff,
by_cases x0 : x = 0,
{ use Iio (x + ε),
have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt,
use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ },
{ use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self,
exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ }
end
lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) :=
begin
refine le_antisymm _ _,
-- first direction
simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne',
-- second direction
rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _),
rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩,
{ rcases exists_between xs with ⟨b, ab, bx⟩,
have xb_pos : 0 < x - b := tsub_pos_iff_lt.2 bx,
have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le,
refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _),
simp only [mem_principal, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ },
{ rcases exists_between xs with ⟨b, xb, ba⟩,
have bx_pos : 0 < b - x := tsub_pos_iff_lt.2 xb,
have xbx : x + (b - x) = b := add_tsub_cancel_of_le xb.le,
refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _),
simp only [mem_principal, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba },
end
/-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order`
for a version with strict inequalities. -/
protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) :=
by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc]
protected lemma tendsto_nhds_zero {f : filter α} {u : α → ℝ≥0∞} :
tendsto u f (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in f, u x ≤ ε :=
begin
rw ennreal.tendsto_nhds zero_ne_top,
simp only [true_and, zero_tsub, zero_le, zero_add, set.mem_Icc],
end
protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞}
(ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) :=
by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually]
instance : has_continuous_add ℝ≥0∞ :=
begin
refine ⟨continuous_iff_continuous_at.2 _⟩,
rintro ⟨(_|a), b⟩,
{ exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) },
rcases b with (_|b),
{ exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) },
simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘),
tendsto_coe, tendsto_add]
end
protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} :
filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε :=
begin
rw ennreal.tendsto_at_top zero_ne_top,
{ simp_rw [set.mem_Icc, zero_add, zero_tsub, zero_le _, true_and], },
{ exact hβ, },
end
lemma tendsto_sub {a b : ℝ≥0∞} (h : a ≠ ∞ ∨ b ≠ ∞) :
tendsto (λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) (𝓝 (a, b)) (𝓝 (a - b)) :=
begin
cases a; cases b,
{ simp only [eq_self_iff_true, not_true, ne.def, none_eq_top, or_self] at h, contradiction },
{ simp only [some_eq_coe, with_top.top_sub_coe, none_eq_top],
apply tendsto_nhds_top_iff_nnreal.2 (λ n, _),
rw [nhds_prod_eq, eventually_prod_iff],
refine ⟨λ z, ((n + (b + 1)) : ℝ≥0∞) < z,
Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]),
λ z, z < b + 1, Iio_mem_nhds ((ennreal.lt_add_right coe_ne_top one_ne_zero)),
λ x hx y hy, _⟩,
dsimp,
rw lt_tsub_iff_right,
have : ((n : ℝ≥0∞) + y) + (b + 1) < x + (b + 1) := calc
((n : ℝ≥0∞) + y) + (b + 1) = ((n : ℝ≥0∞) + (b + 1)) + y : by abel
... < x + (b + 1) : ennreal.add_lt_add hx hy,
exact lt_of_add_lt_add_right this },
{ simp only [some_eq_coe, with_top.sub_top, none_eq_top],
suffices H : ∀ᶠ (p : ℝ≥0∞ × ℝ≥0∞) in 𝓝 (a, ∞), 0 = p.1 - p.2,
from tendsto_const_nhds.congr' H,
rw [nhds_prod_eq, eventually_prod_iff],
refine ⟨λ z, z < a + 1, Iio_mem_nhds (ennreal.lt_add_right coe_ne_top one_ne_zero),
λ z, (a : ℝ≥0∞) + 1 < z,
Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]),
λ x hx y hy, _⟩,
rw eq_comm,
simp only [tsub_eq_zero_iff_le, (has_lt.lt.trans hx hy).le], },
{ simp only [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, function.comp, ← ennreal.coe_sub,
tendsto_coe],
exact continuous.tendsto (by continuity) _ }
end
protected lemma tendsto.sub {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hma : tendsto ma f (𝓝 a)) (hmb : tendsto mb f (𝓝 b)) (h : a ≠ ∞ ∨ b ≠ ∞) :
tendsto (λ a, ma a - mb a) f (𝓝 (a - b)) :=
show tendsto ((λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a - b)), from
tendsto.comp (ennreal.tendsto_sub h) (hma.prod_mk_nhds hmb)
protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) :=
have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤),
begin
refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _,
rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩,
have : ∀ᶠ c : ℝ≥0∞ × ℝ≥0∞ in 𝓝 (∞, b), ↑n / ↑ε < c.1 ∧ ↑ε < c.2,
from (lt_mem_nhds $ div_lt_top coe_ne_top hε.ne').prod_nhds (lt_mem_nhds hεb),
refine this.mono (λ c hc, _),
exact (div_mul_cancel hε.ne' coe_ne_top).symm.trans_lt (mul_lt_mul hc.1 hc.2)
end,
begin
cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] },
cases b,
{ simp [none_eq_top] at ha,
simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘),
mul_comm] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_mul.symm, tendsto_coe, tendsto_mul]
end
protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λa, ma a * mb a) f (𝓝 (a * b)) :=
show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from
tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb)
protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) :=
by_cases
(assume : a = 0, by simp [this, tendsto_const_nhds])
(assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb)
protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) :=
by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha
lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞}
(s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞):
tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) :=
begin
induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] },
simp only [finset.prod_insert has],
apply tendsto.mul (h _ (finset.mem_insert_self _ _)),
{ right,
exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne },
{ exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi))
(λ i hi, h' _ (finset.mem_insert_of_mem hi)) },
{ exact or.inr (h' _ (finset.mem_insert_self _ _)) }
end
protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at ((*) a) b :=
tendsto.const_mul tendsto_id h.symm
protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at (λ x, x * a) b :=
tendsto.mul_const tendsto_id h.symm
protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha)
protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha)
protected lemma continuous_div_const (c : ℝ≥0∞) (c_ne_zero : c ≠ 0) :
continuous (λ (x : ℝ≥0∞), x / c) :=
begin
simp_rw [div_eq_mul_inv, continuous_iff_continuous_at],
intro x,
exact ennreal.continuous_at_mul_const (or.intro_left _ (inv_ne_top.mpr c_ne_zero)),
end
@[continuity]
lemma continuous_pow (n : ℕ) : continuous (λ a : ℝ≥0∞, a ^ n) :=
begin
induction n with n IH,
{ simp [continuous_const] },
simp_rw [nat.succ_eq_add_one, pow_add, pow_one, continuous_iff_continuous_at],
assume x,
refine ennreal.tendsto.mul (IH.tendsto _) _ tendsto_id _;
by_cases H : x = 0,
{ simp only [H, zero_ne_top, ne.def, or_true, not_false_iff]},
{ exact or.inl (λ h, H (pow_eq_zero h)) },
{ simp only [H, pow_eq_top_iff, zero_ne_top, false_or, eq_self_iff_true,
not_true, ne.def, not_false_iff, false_and], },
{ simp only [H, true_or, ne.def, not_false_iff] }
end
lemma continuous_on_sub :
continuous_on (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) { p : ℝ≥0∞ × ℝ≥0∞ | p ≠ ⟨∞, ∞⟩ } :=
begin
rw continuous_on,
rintros ⟨x, y⟩ hp,
simp only [ne.def, set.mem_set_of_eq, prod.mk.inj_iff] at hp,
refine tendsto_nhds_within_of_tendsto_nhds (tendsto_sub (not_and_distrib.mp hp)),
end
lemma continuous_sub_left {a : ℝ≥0∞} (a_ne_top : a ≠ ⊤) :
continuous (λ x, a - x) :=
begin
rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl),
apply continuous_on.comp_continuous continuous_on_sub (continuous.prod.mk a),
intro x,
simp only [a_ne_top, ne.def, mem_set_of_eq, prod.mk.inj_iff, false_and, not_false_iff],
end
lemma continuous_nnreal_sub {a : ℝ≥0} :
continuous (λ (x : ℝ≥0∞), (a : ℝ≥0∞) - x) :=
continuous_sub_left coe_ne_top
lemma continuous_on_sub_left (a : ℝ≥0∞) :
continuous_on (λ x, a - x) {x : ℝ≥0∞ | x ≠ ∞} :=
begin
rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl),
apply continuous_on.comp continuous_on_sub (continuous.continuous_on (continuous.prod.mk a)),
rintros _ h (_|_),
exact h none_eq_top,
end
lemma continuous_sub_right (a : ℝ≥0∞) :
continuous (λ x : ℝ≥0∞, x - a) :=
begin
by_cases a_infty : a = ∞,
{ simp [a_infty, continuous_const], },
{ rw (show (λ x, x - a) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨x, a⟩), by refl),
apply continuous_on.comp_continuous
continuous_on_sub (continuous_id'.prod_mk continuous_const),
intro x,
simp only [a_infty, ne.def, mem_set_of_eq, prod.mk.inj_iff, and_false, not_false_iff], },
end
protected lemma tendsto.pow {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} {n : ℕ}
(hm : tendsto m f (𝓝 a)) :
tendsto (λ x, (m x) ^ n) f (𝓝 (a ^ n)) :=
((continuous_pow n).tendsto a).comp hm
lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y :=
begin
have : tendsto (* x) (𝓝[<] 1) (𝓝 (1 * x)) :=
(ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left,
rw one_mul at this,
haveI : (𝓝[<] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ⟨0, ennreal.zero_lt_one⟩,
exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h)
end
lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) :
(⨅ i, a * f i) = a * ⨅ i, f i :=
begin
by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0,
{ rcases h H.1 H.2 with ⟨i, hi⟩,
rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot],
exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ },
{ rw not_and_distrib at H,
casesI is_empty_or_nonempty ι,
{ rw [infi_of_empty, infi_of_empty, mul_top, if_neg],
exact mt h0 (not_nonempty_iff.2 ‹_›) },
{ exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H)
ennreal.mul_left_mono).symm } }
end
lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, a * f i) = a * ⨅ i, f i :=
infi_mul_left' h (λ _, ‹nonempty ι›)
lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) :
(⨅ i, f i * a) = (⨅ i, f i) * a :=
by simpa only [mul_comm a] using infi_mul_left' h h0
lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, f i * a) = (⨅ i, f i) * a :=
infi_mul_right' h (λ _, ‹nonempty ι›)
lemma inv_map_infi {ι : Sort*} {x : ι → ℝ≥0∞} :
(infi x)⁻¹ = (⨆ i, (x i)⁻¹) :=
order_iso.inv_ennreal.map_infi x
lemma inv_map_supr {ι : Sort*} {x : ι → ℝ≥0∞} :
(supr x)⁻¹ = (⨅ i, (x i)⁻¹) :=
order_iso.inv_ennreal.map_supr x
lemma inv_limsup {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} :
(l.limsup x)⁻¹ = l.liminf (λ i, (x i)⁻¹) :=
by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi]
lemma inv_liminf {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} :
(l.liminf x)⁻¹ = l.limsup (λ i, (x i)⁻¹) :=
by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi]
instance : has_continuous_inv ℝ≥0∞ := ⟨order_iso.inv_ennreal.continuous⟩
@[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} :
tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) :=
⟨λ h, by simpa only [inv_inv] using tendsto.inv h, tendsto.inv⟩
protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) :
tendsto (λa, ma a / mb a) f (𝓝 (a / b)) :=
by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] }
protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) :=
by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] }
protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) :=
by { apply tendsto.mul_const hm, simp [ha] }
protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) :=
ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top
lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a :=
map_supr_of_continuous_at_of_monotone' (continuous_at_id.add continuous_at_const) $
monotone_id.add monotone_const
lemma bsupr_add' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} :
(⨆ i (hi : p i), f i) + a = ⨆ i (hi : p i), f i + a :=
by { haveI : nonempty {i // p i} := nonempty_subtype.2 h, simp only [supr_subtype', supr_add] }
lemma add_bsupr' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} :
a + (⨆ i (hi : p i), f i) = ⨆ i (hi : p i), a + f i :=
by simp only [add_comm a, bsupr_add' h]
lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} :
(⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a :=
bsupr_add' hs
lemma add_bsupr {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} :
a + (⨆ i ∈ s, f i) = ⨆ i ∈ s, a + f i :=
add_bsupr' hs
lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a :=
by rw [Sup_eq_supr, bsupr_add hs]
lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [nonempty ι] : a + supr s = ⨆b, a + s b :=
by rw [add_comm, supr_add]; simp [add_comm]
lemma supr_add_supr_le {ι ι' : Sort*} [nonempty ι] [nonempty ι']
{f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i j, f i + g j ≤ a) :
supr f + supr g ≤ a :=
by simpa only [add_supr, supr_add] using supr₂_le h
lemma bsupr_add_bsupr_le' {ι ι'} {p : ι → Prop} {q : ι' → Prop} (hp : ∃ i, p i) (hq : ∃ j, q j)
{f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i (hi : p i) j (hj : q j), f i + g j ≤ a) :
(⨆ i (hi : p i), f i) + (⨆ j (hj : q j), g j) ≤ a :=
by { simp_rw [bsupr_add' hp, add_bsupr' hq], exact supr₂_le (λ i hi, supr₂_le (h i hi)) }
lemma bsupr_add_bsupr_le {ι ι'} {s : set ι} {t : set ι'} (hs : s.nonempty) (ht : t.nonempty)
{f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ (i ∈ s) (j ∈ t), f i + g j ≤ a) :
(⨆ i ∈ s, f i) + (⨆ j ∈ t, g j) ≤ a :=
bsupr_add_bsupr_le' hs ht h
lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) :
supr f + supr g = (⨆ a, f a + g a) :=
begin
casesI is_empty_or_nonempty ι,
{ simp only [supr_of_empty, bot_eq_zero, zero_add] },
{ refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)),
refine supr_add_supr_le (λ i j, _),
rcases h i j with ⟨k, hk⟩,
exact le_supr_of_le k hk }
end
lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι]
{f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) :
supr f + supr g = (⨆ a, f a + g a) :=
supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩
lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞}
(hf : ∀a, monotone (f a)) :
∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) :=
begin
refine finset.induction_on s _ _,
{ simp, },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [ih, supr_add_supr_of_monotone (hf a)],
assume i j h,
exact (finset.sum_le_sum $ assume a ha, hf a h) }
end
lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i :=
begin
by_cases hf : ∀ i, f i = 0,
{ obtain rfl : f = (λ _, 0), from funext hf,
simp only [supr_zero_eq_zero, mul_zero] },
{ refine map_supr_of_continuous_at_of_monotone _ (monotone_id.const_mul' _) (mul_zero a),
refine ennreal.tendsto.const_mul tendsto_id (or.inl _),
exact mt supr_eq_zero.1 hf }
end
lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i :=
by simp only [Sup_eq_supr, mul_supr]
lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a :=
by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm]
lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a :=
supr_mul
protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) :=
begin
refine forall_ennreal.2 ⟨λ a, _, _⟩,
{ simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, ← with_top.coe_sub],
exact tendsto_const_nhds.sub tendsto_id },
simp,
exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $
by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds
end
lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) :
a - (⨆i, b i) = (⨅i, a - b i) :=
let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in
have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i),
from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto
(assume x _ y _, tsub_le_tsub (le_refl (r : ℝ≥0∞)))
(range_nonempty _)
(ennreal.tendsto_coe_sub.comp (tendsto_id'.2 inf_le_left)),
by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_rfl
lemma exists_countable_dense_no_zero_top :
∃ (s : set ℝ≥0∞), s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s :=
begin
obtain ⟨s, s_count, s_dense, hs⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧
(∀ x, is_bot x → x ∉ s) ∧ (∀ x, is_top x → x ∉ s) := exists_countable_dense_no_bot_top ℝ≥0∞,
exact ⟨s, s_count, s_dense, λ h, hs.1 0 (by simp) h, λ h, hs.2 ∞ (by simp) h⟩,
end
lemma exists_lt_add_of_lt_add {x y z : ℝ≥0∞} (h : x < y + z) (hy : y ≠ 0) (hz : z ≠ 0) :
∃ y' z', y' < y ∧ z' < z ∧ x < y' + z' :=
begin
haveI : ne_bot (𝓝[<] y) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hy⟩,
haveI : ne_bot (𝓝[<] z) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hz⟩,
have A : tendsto (λ (p : ℝ≥0∞ × ℝ≥0∞), p.1 + p.2) ((𝓝[<] y).prod (𝓝[<] z)) (𝓝 (y + z)),
{ apply tendsto.mono_left _ (filter.prod_mono nhds_within_le_nhds nhds_within_le_nhds),
rw ← nhds_prod_eq,
exact tendsto_add },
rcases (((tendsto_order.1 A).1 x h).and
(filter.prod_mem_prod self_mem_nhds_within self_mem_nhds_within)).exists
with ⟨⟨y', z'⟩, hx, hy', hz'⟩,
exact ⟨y', z', hy', hz', hx⟩,
end
end topological_space
section tsum
variables {f g : α → ℝ≥0∞}
@[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} :
has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r :=
have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a),
from funext $ assume s, ennreal.coe_finset_sum.symm,
by unfold has_sum; rw [this, tendsto_coe]
protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r :=
(ennreal.has_sum_coe.2 h).tsum_eq
protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞)
| ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr]
protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) :=
tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset
@[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩
lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} :
∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f :=
begin
refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩,
lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha,
refine ⟨a, ennreal.has_sum_coe.1 _⟩,
rw ha,
exact ennreal.summable.has_sum
end
protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) :=
ennreal.has_sum.tsum_eq
protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) :
∑' a, f a = ⨆ i, ∑ a in s i, f a :=
begin
rw [ennreal.tsum_eq_supr_sum],
symmetry,
change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a,
exact (finset.sum_mono_set f).supr_comp_eq hs
end
protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) :
∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) :
∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b :=
tsum_prod' ennreal.summable $ λ _, ennreal.summable
protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b :=
tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable)
protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) :=
tsum_add ennreal.summable ennreal.summable
protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a :=
tsum_le_tsum h ennreal.summable ennreal.summable
protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x :=
sum_le_tsum s (λ x hx, zero_le _) ennreal.summable
protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) :
∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) :=
ennreal.tsum_eq_supr_sum' _ $ λ t,
let ⟨n, hn⟩ := t.exists_nat_subset_range,
⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in
⟨k, finset.subset.trans hn (finset.range_mono hk)⟩
protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} :
∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) :=
ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range
protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} :
∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) :=
begin
rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat],
congr,
refine funext (λ n, le_antisymm _ _),
{ refine le_infi₂ (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)),
simpa only [finset.range_subset, add_le_add_iff_right] using hi, },
{ refine le_trans (infi_le _ n) _,
simp [le_refl n, le_refl ((finset.range n).sum f)], },
end
protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a :=
le_tsum' ennreal.summable a
@[simp] protected lemma tsum_eq_zero : ∑' i, f i = 0 ↔ ∀ i, f i = 0 :=
⟨λ h i, nonpos_iff_eq_zero.1 $ h ▸ ennreal.le_tsum i, λ h, by simp [h]⟩
protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞
| ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a
@[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ :=
let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩
lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) :
(∑' (a : α), c) = ∞ :=
begin
have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)),
{ apply ennreal.tendsto.mul_const tendsto_nat_nhds_top,
simp only [true_or, top_ne_zero, ne.def, not_false_iff] },
have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c),
{ assume n,
rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩,
simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s },
simpa [hc] using le_of_tendsto' A B,
end
protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ :=
λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩
protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i :=
if h : ∀i, f i = 0 then by simp [h] else
let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in
have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $
calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm
... ≤ ∑'i, f i : ennreal.le_tsum _,
have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)),
by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j,
from funext $ λ s, finset.mul_sum];
exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0),
has_sum.tsum_eq this
protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a :=
by simp [mul_comm, ennreal.tsum_mul_left]
@[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} :
∑'b:α, (⨆ (h : a = b), f b) = f a :=
le_antisymm
(by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s,
calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b :
finset.sum_le_sum_of_ne_zero $ assume b _ hb,
suffices a = b, by simpa using this.symm,
classical.by_contradiction $ assume h,
by simpa [h] using hb
... = f a : by simp))
(calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl
... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _)
lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩,
rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat],
{ exact ennreal.summable.has_sum },
{ exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) }
end
lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) :
tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) :=
by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum }
lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) :
(((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x :=
coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _
lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) :
summable (ennreal.to_nnreal ∘ f) :=
by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf
lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) :
tendsto f cofinite (𝓝 0) :=
begin
have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf,
have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal),
from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm),
rw [h_f_coe, ←@coe_zero, tendsto_coe],
exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf),
end
lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) :
tendsto f at_top (𝓝 0) :=
by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf }
/-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole
space. This does not need a summability assumption, as otherwise all sums are zero. -/
lemma tendsto_tsum_compl_at_top_zero {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) :
tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) :=
begin
lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf,
convert ennreal.tendsto_coe.2 (nnreal.tendsto_tsum_compl_at_top_zero f),
ext1 s,
rw ennreal.coe_tsum,
exact nnreal.summable_comp_injective (tsum_coe_ne_top_iff_summable.1 hf) subtype.coe_injective
end
protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} :
(∑' i, f i) x = ∑' i, f i x :=
tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable
lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) :
∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) :=
begin
have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i,
{ rw [ennreal.tsum_add, ennreal.add_sub_cancel_right h₁]},
have h₄:(λ i, (f i - g i) + (g i)) = f,
{ ext n, rw tsub_add_cancel_of_le (h₂ n)},
rw h₄ at h₃, apply h₃,
end
lemma tsum_mono_subtype (f : α → ℝ≥0∞) {s t : set α} (h : s ⊆ t) :
∑' (x : s), f x ≤ ∑' (x : t), f x :=
begin
simp only [tsum_subtype],
apply ennreal.tsum_le_tsum,
exact indicator_le_indicator_of_subset h (λ _, zero_le _),
end
lemma tsum_union_le (f : α → ℝ≥0∞) (s t : set α) :
∑' (x : s ∪ t), f x ≤ ∑' (x : s), f x + ∑' (x : t), f x :=
calc ∑' (x : s ∪ t), f x = ∑' (x : s ∪ (t \ s)), f x :
by { apply tsum_congr_subtype, rw union_diff_self }
... = ∑' (x : s), f x + ∑' (x : t \ s), f x :
tsum_union_disjoint disjoint_diff ennreal.summable ennreal.summable
... ≤ ∑' (x : s), f x + ∑' (x : t), f x :
add_le_add le_rfl (tsum_mono_subtype _ (diff_subset _ _))
lemma tsum_bUnion_le {ι : Type*} (f : α → ℝ≥0∞) (s : finset ι) (t : ι → set α) :
∑' (x : ⋃ (i ∈ s), t i), f x ≤ ∑ i in s, ∑' (x : t i), f x :=
begin
classical,
induction s using finset.induction_on with i s hi ihs h, { simp },
have : (⋃ (j ∈ insert i s), t j) = t i ∪ (⋃ (j ∈ s), t j), by simp,
rw tsum_congr_subtype f this,
calc ∑' (x : (t i ∪ (⋃ (j ∈ s), t j))), f x ≤
∑' (x : t i), f x + ∑' (x : ⋃ (j ∈ s), t j), f x : tsum_union_le _ _ _
... ≤ ∑' (x : t i), f x + ∑ i in s, ∑' (x : t i), f x : add_le_add le_rfl ihs
... = ∑ j in insert i s, ∑' (x : t j), f x : (finset.sum_insert hi).symm
end
lemma tsum_Union_le {ι : Type*} [fintype ι] (f : α → ℝ≥0∞) (t : ι → set α) :
∑' (x : ⋃ i, t i), f x ≤ ∑ i, ∑' (x : t i), f x :=
begin
classical,
have : (⋃ i, t i) = (⋃ (i ∈ (finset.univ : finset ι)), t i), by simp,
rw tsum_congr_subtype f this,
exact tsum_bUnion_le _ _ _
end
end tsum
lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞}
(hx : x ≠ ∞) :
fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) :=
begin
refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩,
have h_eq : f = (λ n, ennreal.of_real (f n).to_real),
by { ext1 n, rw ennreal.of_real_to_real (hf n), },
rw [h_eq, ← ennreal.of_real_to_real hx],
exact ennreal.tendsto_of_real h,
end
lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} :
∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) :=
begin
rw nnreal.summable_coe,
exact tsum_coe_ne_top_iff_summable,
end
lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} :
∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) :=
begin
rw [← @not_not (∑' a, ↑(f a) = ⊤)],
exact not_congr tsum_coe_ne_top_iff_summable_coe
end
lemma has_sum_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) :
has_sum (λ x, (f x).to_real) (∑' x, (f x).to_real) :=
begin
lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum,
simp only [coe_to_real, ← nnreal.coe_tsum, nnreal.has_sum_coe],
exact (tsum_coe_ne_top_iff_summable.1 hsum).has_sum
end
lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) :
summable (λ x, (f x).to_real) :=
(has_sum_to_real hsum).summable
end ennreal
namespace nnreal
open_locale nnreal
lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} :
(∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal :=
begin
by_cases h : summable f,
{ rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] },
{ have A := tsum_eq_zero_of_not_summable h,
simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h,
simp only [h, ennreal.top_to_nnreal, A] }
end
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0}
(hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p :=
have ∑'b, (g b : ℝ≥0∞) ≤ r,
begin
refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr),
exact ennreal.coe_le_coe.2 (hgf _)
end,
let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in
⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g
| ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat],
simp only [ennreal.coe_finset_sum.symm],
exact ennreal.tendsto_coe
end
lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
split,
{ intros h,
refine ((tendsto_of_monotone _).resolve_right h).comp _,
exacts [finset.sum_mono_set _, tendsto_finset_range] },
{ rintros hnat ⟨r, hr⟩,
exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) }
end
lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top]
lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c :=
le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f)
{i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x :=
tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_rfl) (summable_comp_injective hf hi) hf
lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
begin
split,
{ simp only [← nnreal.summable_coe, nnreal.coe_tsum],
exact λ h, ⟨h.sigma_factor, h.sigma⟩ },
{ rintro ⟨h₁, h₂⟩,
simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁]
using h₂ }
end
lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) :
summable (s.indicator f) :=
begin
refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf,
split_ifs,
exact le_refl (f a),
exact zero_le_coe,
end
lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) :
∑' x, (s.indicator f) x ≠ 0 :=
λ h', let ⟨a, ha, hap⟩ := h in
hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm
(((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a))
open finset
/-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
rw ← tendsto_coe,
convert tendsto_sum_nat_add (λ i, (f i : ℝ)),
norm_cast,
end
lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i)
(hf : has_sum f sf) (hg : has_sum g sg) : sf < sg :=
begin
have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a),
have : (sf : ℝ) < sg :=
has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg),
exact nnreal.coe_lt_coe.1 this
end
@[mono] lemma has_sum_strict_mono
{f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg
lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i)
(hg : summable g) : ∑' n, f n < ∑' n, g n :=
has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum
@[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) :
∑' n, f n < ∑' n, g n :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg
lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) :
0 < ∑' b, g b :=
by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg }
end nnreal
namespace ennreal
lemma tsum_to_real_eq
{f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) :
(∑' a, f a).to_real = ∑' a, (f a).to_real :=
begin
lift f to α → ℝ≥0 using hf,
have : (∑' (a : α), (f a : ℝ≥0∞)).to_real =
((∑' (a : α), (f a : ℝ≥0∞)).to_nnreal : ℝ≥0∞).to_real,
{ rw [ennreal.coe_to_real], refl },
rw [this, ← nnreal.tsum_eq_to_nnreal_tsum, ennreal.coe_to_real],
exact nnreal.coe_tsum
end
lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) :
tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf,
replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf,
simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero],
exact_mod_cast nnreal.tendsto_sum_nat_add f
end
end ennreal
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a)
{i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f :=
begin
lift f to α → ℝ≥0 using hn,
rw nnreal.summable_coe at hf,
simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi
end
/-- Comparison test of convergence of series of non-negative real numbers. -/
lemma summable_of_nonneg_of_le {f g : β → ℝ}
(hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g :=
begin
lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b),
lift g to β → ℝ≥0 using hg,
rw nnreal.summable_coe at hf ⊢,
exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf
end
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) :
has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
lift f to ℕ → ℝ≥0 using hf,
simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'],
exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat)
end
lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) :
ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) :=
by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq
(nnreal.has_sum_real_to_nnreal_of_nonneg hf_nonneg hf)]
lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
lift f to ℕ → ℝ≥0 using hf,
exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top
end
lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf]
lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma }
lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f)
(h : ∀ u : finset ι, ∑ x in u, f x ≤ c) :
summable f :=
⟨ ⨆ u : finset ι, ∑ x in u, f x,
tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩
lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c :=
le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1
(summable_of_sum_range_le hf h).has_sum) h
/-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable
series and at least one term of `f` is strictly smaller than the corresponding term in `g`,
then the series of `f` is strictly smaller than the series of `g`. -/
lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ}
(h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) :
∑' n, f n < ∑' n, g n :=
tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg
section
variables [emetric_space β]
open ennreal filter emetric
/-- In an emetric ball, the distance between points is everywhere finite -/
lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ :=
lt_top_iff_ne_top.1 $
calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a
... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2
... ≤ ⊤ : le_top
/-- Each ball in an extended metric space gives us a metric space, as the edist
is everywhere finite. -/
def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) :=
emetric_space.to_metric_space edist_ne_top_of_mem_ball
local attribute [instance] metric_space_emetric_ball
lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) :
𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) :=
(map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm
end
section
variable [pseudo_emetric_space α]
open emetric
lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} :
tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) :=
by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball,
@tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and]
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} :
cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N)
∧ (tendsto b at_top (𝓝 0))) :=
⟨begin
assume hs,
rw emetric.cauchy_seq_iff at hs,
/- `s` is Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/
let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}),
--Prove that it bounds the distances of points in the Cauchy sequence
have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
{ refine λm n N hm hn, le_Sup _,
use (prod.mk m n),
simp only [and_true, eq_self_iff_true, set.mem_set_of_eq],
exact ⟨hm, hn⟩ },
--Prove that it tends to `0`, by using the Cauchy property of `s`
have D : tendsto b at_top (𝓝 0),
{ refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩,
rcases exists_between εpos with ⟨δ, δpos, δlt⟩,
rcases hs δ δpos with ⟨N, hN⟩,
refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩,
have : b n ≤ δ := Sup_le begin
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists],
intros d p q hp hq hd,
rw ← hd,
exact le_of_lt (hN p (le_trans hn hp) q (le_trans hn hq))
end,
simpa using lt_of_le_of_lt this δlt },
-- Conclude
exact ⟨b, ⟨C, D⟩⟩
end,
begin
rintros ⟨b, ⟨b_bound, b_lim⟩⟩,
/-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
b_lim : tendsto b at_top (𝓝 0)-/
refine emetric.cauchy_seq_iff.2 (λε εpos, _),
have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos,
rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩,
exact ⟨N, λ m hm n hn, calc
edist (s m) (s n) ≤ b N : b_bound m n N hm hn
... < ε : (hN _ (le_refl N)) ⟩
end⟩
lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞)
(hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f :=
begin
rcases eq_or_ne C 0 with (rfl|C0),
{ simp only [zero_mul, add_zero] at h,
exact continuous_of_const (λ x y, le_antisymm (h _ _) (h _ _)) },
{ refine continuous_iff_continuous_at.2 (λ x, _),
by_cases hx : f x = ∞,
{ have : f =ᶠ[𝓝 x] (λ _, ∞),
{ filter_upwards [emetric.ball_mem_nhds x ennreal.coe_lt_top],
refine λ y (hy : edist y x < ⊤), _, rw edist_comm at hy,
simpa [hx, hC, hy.ne] using h x y },
exact this.continuous_at },
{ refine (ennreal.tendsto_nhds hx).2 (λ ε (ε0 : 0 < ε), _),
filter_upwards [emetric.closed_ball_mem_nhds x (ennreal.div_pos_iff.2 ⟨ε0.ne', hC⟩)],
have hεC : C * (ε / C) = ε := ennreal.mul_div_cancel' C0 hC,
refine λ y (hy : edist y x ≤ ε / C), ⟨tsub_le_iff_right.2 _, _⟩,
{ rw edist_comm at hy,
calc f x ≤ f y + C * edist x y : h x y
... ≤ f y + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f y)
... = f y + ε : by rw hεC },
{ calc f y ≤ f x + C * edist y x : h y x
... ≤ f x + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f x)
... = f x + ε : by rw hεC } } }
end
theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) :=
begin
apply continuous_of_le_add_edist 2 (by norm_num),
rintros ⟨x, y⟩ ⟨x', y'⟩,
calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _
... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc
... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) :
add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _
... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm]
end
@[continuity] theorem continuous.edist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) :=
continuous_edist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) :=
(continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) :
cauchy_seq f :=
begin
lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i),
rw ennreal.tsum_coe_ne_top_iff_summable at hd,
exact cauchy_seq_of_edist_le_of_summable d hf hd
end
lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) :=
is_closed_le (continuous_id.edist continuous_const) continuous_const
@[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s :=
begin
refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure),
have : edist x y ∈ closure (Iic (diam s)),
from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem),
rwa closure_Iic at this
end
@[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) :
metric.diam (closure s) = diam s :=
by simp only [metric.diam, emetric.diam_closure]
lemma is_closed_set_of_lipschitz_on_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β]
(K : ℝ≥0) (s : set α) :
is_closed {f : α → β | lipschitz_on_with K f s} :=
begin
simp only [lipschitz_on_with, set_of_forall],
refine is_closed_bInter (λ x hx, is_closed_bInter $ λ y hy, is_closed_le _ _),
exacts [continuous.edist (continuous_apply x) (continuous_apply y), continuous_const]
end
lemma is_closed_set_of_lipschitz_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β]
(K : ℝ≥0) :
is_closed {f : α → β | lipschitz_with K f} :=
by simp only [← lipschitz_on_univ, is_closed_set_of_lipschitz_on_with]
namespace real
/-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as
`ℝ≥0∞`. -/
lemma ediam_eq {s : set ℝ} (h : bounded s) :
emetric.diam s = ennreal.of_real (Sup s - Inf s) :=
begin
rcases eq_empty_or_nonempty s with rfl|hne, { simp },
refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _,
{ have := real.subset_Icc_Inf_Sup_of_bounded h,
exact real.dist_le_of_mem_Icc (this hx) (this hy) },
{ apply ennreal.of_real_le_of_le_to_real,
rw [← metric.diam, ← metric.diam_closure],
have h' := real.bounded_iff_bdd_below_bdd_above.1 h,
calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _
... ≤ diam (closure s) :
dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) }
end
/-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/
lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s :=
begin
rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real],
rw real.bounded_iff_bdd_below_bdd_above at h,
exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2)
end
@[simp] lemma ediam_Ioo (a b : ℝ) :
emetric.diam (Ioo a b) = ennreal.of_real (b - a) :=
begin
rcases le_or_lt b a with h|h,
{ simp [h] },
{ rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] },
end
@[simp] lemma ediam_Icc (a b : ℝ) :
emetric.diam (Icc a b) = ennreal.of_real (b - a) :=
begin
rcases le_or_lt a b with h|h,
{ rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] },
{ simp [h, h.le] }
end
@[simp] lemma ediam_Ico (a b : ℝ) :
emetric.diam (Ico a b) = ennreal.of_real (b - a) :=
le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self)
(ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self)
@[simp] lemma ediam_Ioc (a b : ℝ) :
emetric.diam (Ioc a b) = ennreal.of_real (b - a) :=
le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self)
(ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self)
end real
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`,
then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto (tendsto_const_nhds.edist ha)
(mem_at_top_sets.2 ⟨n, λ m hnm, _⟩),
refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _,
rw [finset.sum_Ico_eq_sum_range],
exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable
end
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`,
then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ ∑' m, d m :=
by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0
end --section
|
d4b6aa276d995dc9dfab03c34b8216bc80da3a52 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/nat/basic_auto.lean | d8a64d306786fb6deff28ebec383b7ed46024714 | [] | 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 | 59,661 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group_power.basic
import Mathlib.algebra.order_functions
import Mathlib.algebra.ordered_monoid
import Mathlib.PostPort
universes u_1 u
namespace Mathlib
/-!
# Basic operations on the natural numbers
This file contains:
- instances on the natural numbers
- some basic lemmas about natural numbers
- extra recursors:
* `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers
* `decreasing_induction`: recursion growing downwards
* `strong_rec'`: recursion based on strong inequalities
- decidability instances on predicates about the natural numbers
-/
/-! ### instances -/
protected instance nat.nontrivial : nontrivial ℕ :=
nontrivial.mk (Exists.intro 0 (Exists.intro 1 nat.zero_ne_one))
protected instance nat.comm_semiring : comm_semiring ℕ :=
comm_semiring.mk Nat.add nat.add_assoc 0 nat.zero_add nat.add_zero nat.add_comm Nat.mul
nat.mul_assoc 1 nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero nat.left_distrib
nat.right_distrib nat.mul_comm
protected instance nat.linear_ordered_semiring : linear_ordered_semiring ℕ :=
linear_ordered_semiring.mk comm_semiring.add comm_semiring.add_assoc comm_semiring.zero
comm_semiring.zero_add comm_semiring.add_zero comm_semiring.add_comm comm_semiring.mul
comm_semiring.mul_assoc comm_semiring.one comm_semiring.one_mul comm_semiring.mul_one
comm_semiring.zero_mul comm_semiring.mul_zero comm_semiring.left_distrib
comm_semiring.right_distrib nat.add_left_cancel nat.add_right_cancel linear_order.le nat.lt
linear_order.le_refl linear_order.le_trans linear_order.le_antisymm nat.add_le_add_left
nat.le_of_add_le_add_left sorry nat.mul_lt_mul_of_pos_left nat.mul_lt_mul_of_pos_right
linear_order.le_total linear_order.decidable_le nat.decidable_eq linear_order.decidable_lt sorry
-- all the fields are already included in the linear_ordered_semiring instance
protected instance nat.linear_ordered_cancel_add_comm_monoid :
linear_ordered_cancel_add_comm_monoid ℕ :=
linear_ordered_cancel_add_comm_monoid.mk linear_ordered_semiring.add
linear_ordered_semiring.add_assoc nat.add_left_cancel linear_ordered_semiring.zero
linear_ordered_semiring.zero_add linear_ordered_semiring.add_zero
linear_ordered_semiring.add_comm linear_ordered_semiring.add_right_cancel
linear_ordered_semiring.le linear_ordered_semiring.lt linear_ordered_semiring.le_refl
linear_ordered_semiring.le_trans linear_ordered_semiring.le_antisymm
linear_ordered_semiring.add_le_add_left linear_ordered_semiring.le_of_add_le_add_left
linear_ordered_semiring.le_total linear_ordered_semiring.decidable_le
linear_ordered_semiring.decidable_eq linear_ordered_semiring.decidable_lt
protected instance nat.linear_ordered_comm_monoid_with_zero :
linear_ordered_comm_monoid_with_zero ℕ :=
linear_ordered_comm_monoid_with_zero.mk linear_ordered_semiring.le linear_ordered_semiring.lt
linear_ordered_semiring.le_refl linear_ordered_semiring.le_trans
linear_ordered_semiring.le_antisymm linear_ordered_semiring.le_total
linear_ordered_semiring.decidable_le linear_ordered_semiring.decidable_eq
linear_ordered_semiring.decidable_lt linear_ordered_semiring.mul
linear_ordered_semiring.mul_assoc linear_ordered_semiring.one linear_ordered_semiring.one_mul
linear_ordered_semiring.mul_one sorry linear_ordered_semiring.zero
linear_ordered_semiring.zero_mul linear_ordered_semiring.mul_zero sorry sorry
linear_ordered_semiring.zero_le_one
/-! Extra instances to short-circuit type class resolution -/
protected instance nat.add_comm_monoid : add_comm_monoid ℕ :=
ordered_add_comm_monoid.to_add_comm_monoid ℕ
protected instance nat.add_monoid : add_monoid ℕ := add_right_cancel_monoid.to_add_monoid ℕ
protected instance nat.monoid : monoid ℕ := monoid_with_zero.to_monoid ℕ
protected instance nat.comm_monoid : comm_monoid ℕ := ordered_comm_monoid.to_comm_monoid ℕ
protected instance nat.comm_semigroup : comm_semigroup ℕ := comm_monoid.to_comm_semigroup ℕ
protected instance nat.semigroup : semigroup ℕ := monoid.to_semigroup ℕ
protected instance nat.add_comm_semigroup : add_comm_semigroup ℕ :=
add_comm_monoid.to_add_comm_semigroup ℕ
protected instance nat.add_semigroup : add_semigroup ℕ := add_monoid.to_add_semigroup ℕ
protected instance nat.distrib : distrib ℕ := semiring.to_distrib ℕ
protected instance nat.semiring : semiring ℕ := ordered_semiring.to_semiring ℕ
protected instance nat.ordered_semiring : ordered_semiring ℕ :=
linear_ordered_semiring.to_ordered_semiring ℕ
protected instance nat.canonically_ordered_comm_semiring : canonically_ordered_comm_semiring ℕ :=
canonically_ordered_comm_semiring.mk ordered_add_comm_monoid.add sorry
ordered_add_comm_monoid.zero sorry sorry sorry ordered_add_comm_monoid.le
ordered_add_comm_monoid.lt sorry sorry sorry sorry sorry 0 nat.zero_le sorry
linear_ordered_semiring.mul sorry linear_ordered_semiring.one sorry sorry sorry sorry sorry
sorry sorry sorry
protected instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s]
[h : Nonempty ↥s] : semilattice_sup_bot ↥s :=
semilattice_sup_bot.mk { val := nat.find sorry, property := sorry } linear_order.le
linear_order.lt sorry sorry sorry sorry lattice.sup sorry sorry sorry
theorem nat.eq_of_mul_eq_mul_right {n : ℕ} {m : ℕ} {k : ℕ} (Hm : 0 < m) (H : n * m = k * m) :
n = k :=
nat.eq_of_mul_eq_mul_left Hm
(eq.mp (Eq._oldrec (Eq.refl (m * n = k * m)) (mul_comm k m))
(eq.mp (Eq._oldrec (Eq.refl (n * m = k * m)) (mul_comm n m)) H))
protected instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ :=
comm_cancel_monoid_with_zero.mk comm_monoid_with_zero.mul sorry comm_monoid_with_zero.one sorry
sorry sorry comm_monoid_with_zero.zero sorry sorry sorry sorry
/-!
Inject some simple facts into the type class system.
This `fact` should not be confused with the factorial function `nat.fact`!
-/
protected instance succ_pos'' (n : ℕ) : fact (0 < Nat.succ n) := nat.succ_pos n
protected instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h
namespace nat
/-!
### Recursion and `set.range`
-/
theorem zero_union_range_succ : singleton 0 ∪ set.range Nat.succ = set.univ := sorry
theorem range_of_succ {α : Type u_1} (f : ℕ → α) :
singleton (f 0) ∪ set.range (f ∘ Nat.succ) = set.range f :=
sorry
theorem range_rec {α : Type u_1} (x : α) (f : ℕ → α → α) :
(set.range fun (n : ℕ) => Nat.rec x f n) =
singleton x ∪ set.range fun (n : ℕ) => Nat.rec (f 0 x) (f ∘ Nat.succ) n :=
sorry
theorem range_cases_on {α : Type u_1} (x : α) (f : ℕ → α) :
(set.range fun (n : ℕ) => nat.cases_on n x f) = singleton x ∪ set.range f :=
Eq.symm (range_of_succ fun (n : ℕ) => nat.cases_on n x f)
/-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/
theorem units_eq_one (u : units ℕ) : u = 1 :=
units.ext (eq_one_of_dvd_one (Exists.intro (units.inv u) (Eq.symm (units.val_inv u))))
theorem add_units_eq_zero (u : add_units ℕ) : u = 0 :=
add_units.ext (and.left (eq_zero_of_add_eq_zero (add_units.val_neg u)))
@[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := sorry
/-! ### Equalities and inequalities involving zero and one -/
theorem one_lt_iff_ne_zero_and_ne_one {n : ℕ} : 1 < n ↔ n ≠ 0 ∧ n ≠ 1 := sorry
protected theorem mul_ne_zero {n : ℕ} {m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 :=
fun (ᾰ : n * m = 0) => idRhs False (or.elim (eq_zero_of_mul_eq_zero ᾰ) n0 m0)
@[simp] protected theorem mul_eq_zero {a : ℕ} {b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := sorry
@[simp] protected theorem zero_eq_mul {a : ℕ} {b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * b ↔ a = 0 ∨ b = 0)) (propext eq_comm)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a * b = 0 ↔ a = 0 ∨ b = 0)) (propext nat.mul_eq_zero)))
(iff.refl (a = 0 ∨ b = 0)))
theorem eq_zero_of_double_le {a : ℕ} (h : bit0 1 * a ≤ a) : a = 0 := sorry
theorem eq_zero_of_mul_le {a : ℕ} {b : ℕ} (hb : bit0 1 ≤ b) (h : b * a ≤ a) : a = 0 :=
eq_zero_of_double_le (le_trans (mul_le_mul_right a hb) h)
theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 :=
{ mp := eq_zero_of_le_zero, mpr := fun (h : i = 0) => h ▸ le_refl i }
theorem zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le m)
theorem one_le_of_lt {n : ℕ} {m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (zero_le n) h
theorem eq_one_of_mul_eq_one_right {m : ℕ} {n : ℕ} (H : m * n = 1) : m = 1 :=
eq_one_of_dvd_one (Exists.intro n (Eq.symm H))
theorem eq_one_of_mul_eq_one_left {m : ℕ} {n : ℕ} (H : m * n = 1) : n = 1 :=
eq_one_of_mul_eq_one_right (eq.mpr (id (Eq._oldrec (Eq.refl (n * m = 1)) (mul_comm n m))) H)
/-! ### `succ` -/
theorem eq_of_lt_succ_of_not_lt {a : ℕ} {b : ℕ} (h1 : a < b + 1) (h2 : ¬a < b) : a = b :=
(fun (h3 : a ≤ b) =>
or.elim (eq_or_lt_of_not_lt h2) (fun (h : a = b) => h)
fun (h : b < a) => absurd h (not_lt_of_ge h3))
(le_of_lt_succ h1)
theorem one_add (n : ℕ) : 1 + n = Nat.succ n := sorry
@[simp] theorem succ_pos' {n : ℕ} : 0 < Nat.succ n := succ_pos n
theorem succ_inj' {n : ℕ} {m : ℕ} : Nat.succ n = Nat.succ m ↔ n = m :=
{ mp := succ.inj, mpr := congr_arg fun {n : ℕ} => Nat.succ n }
theorem succ_injective : function.injective Nat.succ := fun (x y : ℕ) => succ.inj
theorem succ_le_succ_iff {m : ℕ} {n : ℕ} : Nat.succ m ≤ Nat.succ n ↔ m ≤ n :=
{ mp := le_of_succ_le_succ, mpr := succ_le_succ }
theorem max_succ_succ {m : ℕ} {n : ℕ} : max (Nat.succ m) (Nat.succ n) = Nat.succ (max m n) := sorry
theorem not_succ_lt_self {n : ℕ} : ¬Nat.succ n < n := not_lt_of_ge (le_succ n)
theorem lt_succ_iff {m : ℕ} {n : ℕ} : m < Nat.succ n ↔ m ≤ n := succ_le_succ_iff
theorem succ_le_iff {m : ℕ} {n : ℕ} : Nat.succ m ≤ n ↔ m < n :=
{ mp := lt_of_succ_le, mpr := succ_le_of_lt }
theorem lt_iff_add_one_le {m : ℕ} {n : ℕ} : m < n ↔ m + 1 ≤ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (m < n ↔ m + 1 ≤ n)) (propext succ_le_iff))) (iff.refl (m < n))
-- Just a restatement of `nat.lt_succ_iff` using `+1`.
theorem lt_add_one_iff {a : ℕ} {b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff
-- A flipped version of `lt_add_one_iff`.
theorem lt_one_add_iff {a : ℕ} {b : ℕ} : a < 1 + b ↔ a ≤ b := sorry
-- This is true reflexively, by the definition of `≤` on ℕ,
-- but it's still useful to have, to convince Lean to change the syntactic type.
theorem add_one_le_iff {a : ℕ} {b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl (a + 1 ≤ b)
theorem one_add_le_iff {a : ℕ} {b : ℕ} : 1 + a ≤ b ↔ a < b := sorry
theorem of_le_succ {n : ℕ} {m : ℕ} (H : n ≤ Nat.succ m) : n ≤ m ∨ n = Nat.succ m :=
or.imp le_of_lt_succ id (lt_or_eq_of_le H)
theorem succ_lt_succ_iff {m : ℕ} {n : ℕ} : Nat.succ m < Nat.succ n ↔ m < n :=
{ mp := lt_of_succ_lt_succ, mpr := succ_lt_succ }
/-! ### `add` -/
-- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding
-- during pattern matching. These lemmas package them back up as typeclass
-- mediated operations.
@[simp] theorem add_def {a : ℕ} {b : ℕ} : Nat.add a b = a + b := rfl
@[simp] theorem mul_def {a : ℕ} {b : ℕ} : Nat.mul a b = a * b := rfl
theorem exists_eq_add_of_le {m : ℕ} {n : ℕ} : m ≤ n → ∃ (k : ℕ), n = m + k := sorry
theorem exists_eq_add_of_lt {m : ℕ} {n : ℕ} : m < n → ∃ (k : ℕ), n = m + k + 1 := sorry
theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n :=
gt_of_gt_of_ge (trans_rel_left gt (nat.add_lt_add_right h n) (nat.zero_add n)) (zero_le n)
theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 < m + n)) (add_comm m n))) (add_pos_left h m)
theorem add_pos_iff_pos_or_pos (m : ℕ) (n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := sorry
theorem add_eq_one_iff {a : ℕ} {b : ℕ} : a + b = 1 ↔ a = 0 ∧ b = 1 ∨ a = 1 ∧ b = 0 := sorry
theorem le_add_one_iff {i : ℕ} {j : ℕ} : i ≤ j + 1 ↔ i ≤ j ∨ i = j + 1 := sorry
theorem add_succ_lt_add {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (hab : a < b) (hcd : c < d) :
a + c + 1 < b + d :=
eq.mpr (id (Eq._oldrec (Eq.refl (a + c + 1 < b + d)) (add_assoc a c 1)))
(add_lt_add_of_lt_of_le hab (iff.mpr succ_le_iff hcd))
/-! ### `pred` -/
@[simp] theorem add_succ_sub_one (n : ℕ) (m : ℕ) : n + Nat.succ m - 1 = n + m :=
eq.mpr (id (Eq._oldrec (Eq.refl (n + Nat.succ m - 1 = n + m)) (add_succ n m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ (n + m) - 1 = n + m)) (succ_sub_one (n + m))))
(Eq.refl (n + m)))
@[simp] theorem succ_add_sub_one (n : ℕ) (m : ℕ) : Nat.succ n + m - 1 = n + m :=
eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ n + m - 1 = n + m)) (succ_add n m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ (n + m) - 1 = n + m)) (succ_sub_one (n + m))))
(Eq.refl (n + m)))
theorem pred_eq_sub_one (n : ℕ) : Nat.pred n = n - 1 := rfl
theorem pred_eq_of_eq_succ {m : ℕ} {n : ℕ} (H : m = Nat.succ n) : Nat.pred m = n := sorry
@[simp] theorem pred_eq_succ_iff {n : ℕ} {m : ℕ} : Nat.pred n = Nat.succ m ↔ n = m + bit0 1 := sorry
theorem pred_sub (n : ℕ) (m : ℕ) : Nat.pred n - m = Nat.pred (n - m) :=
eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred n - m = Nat.pred (n - m))) (Eq.symm (sub_one n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (n - 1 - m = Nat.pred (n - m))) (nat.sub_sub n 1 m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (n - (1 + m) = Nat.pred (n - m))) (one_add m)))
(Eq.refl (n - Nat.succ m))))
theorem le_pred_of_lt {n : ℕ} {m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1
theorem le_of_pred_lt {m : ℕ} {n : ℕ} : Nat.pred m < n → m ≤ n := sorry
/-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/
@[simp] theorem pred_one_add (n : ℕ) : Nat.pred (1 + n) = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (1 + n) = n)) (add_comm 1 n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (n + 1) = n)) (add_one n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (Nat.succ n) = n)) (pred_succ n))) (Eq.refl n)))
/-! ### `sub` -/
protected theorem le_sub_add (n : ℕ) (m : ℕ) : n ≤ n - m + m := sorry
theorem sub_add_eq_max (n : ℕ) (m : ℕ) : n - m + m = max n m := sorry
theorem add_sub_eq_max (n : ℕ) (m : ℕ) : n + (m - n) = max n m :=
eq.mpr (id (Eq._oldrec (Eq.refl (n + (m - n) = max n m)) (add_comm n (m - n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (m - n + n = max n m)) (max_comm n m)))
(eq.mpr (id (Eq._oldrec (Eq.refl (m - n + n = max m n)) (sub_add_eq_max m n)))
(Eq.refl (max m n))))
theorem sub_add_min (n : ℕ) (m : ℕ) : n - m + min n m = n := sorry
protected theorem add_sub_cancel' {n : ℕ} {m : ℕ} (h : m ≤ n) : m + (n - m) = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (m + (n - m) = n)) (add_comm m (n - m))))
(eq.mpr (id (Eq._oldrec (Eq.refl (n - m + m = n)) (nat.sub_add_cancel h))) (Eq.refl n))
protected theorem sub_add_sub_cancel {a : ℕ} {b : ℕ} {c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) :
a - b + (b - c) = a - c :=
eq.mpr
(id (Eq._oldrec (Eq.refl (a - b + (b - c) = a - c)) (Eq.symm (nat.add_sub_assoc hbc (a - b)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - b + b - c = a - c)) (Eq.symm (nat.sub_add_comm hab))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + b - b - c = a - c)) (nat.add_sub_cancel a b)))
(Eq.refl (a - c))))
protected theorem sub_eq_of_eq_add {m : ℕ} {n : ℕ} {k : ℕ} (h : k = m + n) : k - m = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (k - m = n)) h))
(eq.mpr (id (Eq._oldrec (Eq.refl (m + n - m = n)) (nat.add_sub_cancel_left m n))) (Eq.refl n))
theorem sub_cancel {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c :=
eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (nat.sub_add_cancel h₁))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b - a + a = c)) (Eq.symm (nat.sub_add_cancel h₂))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b - a + a = c - a + a)) w)) (Eq.refl (c - a + a))))
theorem sub_sub_sub_cancel_right {a : ℕ} {b : ℕ} {c : ℕ} (h₂ : c ≤ b) : a - c - (b - c) = a - b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - c - (b - c) = a - b)) (nat.sub_sub a c (b - c))))
(eq.mpr
(id (Eq._oldrec (Eq.refl (a - (c + (b - c)) = a - b)) (Eq.symm (nat.add_sub_assoc h₂ c))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - (c + b - c) = a - b)) (nat.add_sub_cancel_left c b)))
(Eq.refl (a - b))))
theorem add_sub_cancel_right (n : ℕ) (m : ℕ) (k : ℕ) : n + (m + k) - k = n + m :=
eq.mpr
(id (Eq._oldrec (Eq.refl (n + (m + k) - k = n + m)) (nat.add_sub_assoc (le_add_left k m) n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (n + (m + k - k) = n + m)) (nat.add_sub_cancel m k)))
(Eq.refl (n + m)))
protected theorem sub_add_eq_add_sub {a : ℕ} {b : ℕ} {c : ℕ} (h : b ≤ a) : a - b + c = a + c - b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = a + c - b)) (add_comm a c)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = c + a - b)) (nat.add_sub_assoc h c)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = c + (a - b))) (add_comm (a - b) c)))
(Eq.refl (c + (a - b)))))
theorem sub_min (n : ℕ) (m : ℕ) : n - min n m = n - m :=
nat.sub_eq_of_eq_add
(eq.mpr (id (Eq._oldrec (Eq.refl (n = min n m + (n - m))) (add_comm (min n m) (n - m))))
(eq.mpr (id (Eq._oldrec (Eq.refl (n = n - m + min n m)) (sub_add_min n m))) (Eq.refl n)))
theorem sub_sub_assoc {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c :=
sorry
protected theorem lt_of_sub_pos {m : ℕ} {n : ℕ} (h : 0 < n - m) : m < n :=
lt_of_not_ge
fun (this : n ≤ m) =>
(fun (this : n - m = 0) => lt_irrefl 0 (eq.mp (Eq._oldrec (Eq.refl (0 < n - m)) this) h))
(sub_eq_zero_of_le this)
protected theorem lt_of_sub_lt_sub_right {m : ℕ} {n : ℕ} {k : ℕ} : m - k < n - k → m < n :=
lt_imp_lt_of_le_imp_le fun (h : n ≤ m) => nat.sub_le_sub_right h k
protected theorem lt_of_sub_lt_sub_left {m : ℕ} {n : ℕ} {k : ℕ} : m - n < m - k → k < n :=
lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left m)
protected theorem sub_lt_self {m : ℕ} {n : ℕ} (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := sorry
protected theorem le_sub_right_of_add_le {m : ℕ} {n : ℕ} {k : ℕ} (h : m + k ≤ n) : m ≤ n - k :=
eq.mpr (id (Eq._oldrec (Eq.refl (m ≤ n - k)) (Eq.symm (nat.add_sub_cancel m k))))
(nat.sub_le_sub_right h k)
protected theorem le_sub_left_of_add_le {m : ℕ} {n : ℕ} {k : ℕ} (h : k + m ≤ n) : m ≤ n - k :=
nat.le_sub_right_of_add_le (eq.mp (Eq._oldrec (Eq.refl (k + m ≤ n)) (add_comm k m)) h)
protected theorem lt_sub_right_of_add_lt {m : ℕ} {n : ℕ} {k : ℕ} (h : m + k < n) : m < n - k :=
lt_of_succ_le
(nat.le_sub_right_of_add_le
(eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ m + k ≤ n)) (succ_add m k))) (succ_le_of_lt h)))
protected theorem lt_sub_left_of_add_lt {m : ℕ} {n : ℕ} {k : ℕ} (h : k + m < n) : m < n - k :=
nat.lt_sub_right_of_add_lt (eq.mp (Eq._oldrec (Eq.refl (k + m < n)) (add_comm k m)) h)
protected theorem add_lt_of_lt_sub_right {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n - k) : m + k < n :=
nat.lt_of_sub_lt_sub_right
(eq.mpr (id (Eq._oldrec (Eq.refl (m + k - k < n - k)) (nat.add_sub_cancel m k))) h)
protected theorem add_lt_of_lt_sub_left {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n - k) : k + m < n :=
eq.mpr (id (Eq._oldrec (Eq.refl (k + m < n)) (add_comm k m))) (nat.add_lt_of_lt_sub_right h)
protected theorem le_add_of_sub_le_right {m : ℕ} {n : ℕ} {k : ℕ} : n - k ≤ m → n ≤ m + k :=
le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt
protected theorem le_add_of_sub_le_left {m : ℕ} {n : ℕ} {k : ℕ} : n - k ≤ m → n ≤ k + m :=
le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt
protected theorem lt_add_of_sub_lt_right {m : ℕ} {n : ℕ} {k : ℕ} : n - k < m → n < m + k :=
lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le
protected theorem lt_add_of_sub_lt_left {m : ℕ} {n : ℕ} {k : ℕ} : n - k < m → n < k + m :=
lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le
protected theorem sub_le_left_of_le_add {m : ℕ} {n : ℕ} {k : ℕ} : n ≤ k + m → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left
protected theorem sub_le_right_of_le_add {m : ℕ} {n : ℕ} {k : ℕ} : n ≤ m + k → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right
protected theorem sub_lt_left_iff_lt_add {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ k) :
k - n < m ↔ k < n + m :=
sorry
protected theorem le_sub_left_iff_add_le {m : ℕ} {n : ℕ} {k : ℕ} (H : m ≤ k) :
n ≤ k - m ↔ m + n ≤ k :=
iff.mpr le_iff_le_iff_lt_iff_lt (nat.sub_lt_left_iff_lt_add H)
protected theorem le_sub_right_iff_add_le {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ k) :
m ≤ k - n ↔ m + n ≤ k :=
eq.mpr
(id (Eq._oldrec (Eq.refl (m ≤ k - n ↔ m + n ≤ k)) (propext (nat.le_sub_left_iff_add_le H))))
(eq.mpr (id (Eq._oldrec (Eq.refl (n + m ≤ k ↔ m + n ≤ k)) (add_comm n m)))
(iff.refl (m + n ≤ k)))
protected theorem lt_sub_left_iff_add_lt {m : ℕ} {n : ℕ} {k : ℕ} : n < k - m ↔ m + n < k :=
{ mp := nat.add_lt_of_lt_sub_left, mpr := nat.lt_sub_left_of_add_lt }
protected theorem lt_sub_right_iff_add_lt {m : ℕ} {n : ℕ} {k : ℕ} : m < k - n ↔ m + n < k :=
eq.mpr (id (Eq._oldrec (Eq.refl (m < k - n ↔ m + n < k)) (propext nat.lt_sub_left_iff_add_lt)))
(eq.mpr (id (Eq._oldrec (Eq.refl (n + m < k ↔ m + n < k)) (add_comm n m)))
(iff.refl (m + n < k)))
theorem sub_le_left_iff_le_add {m : ℕ} {n : ℕ} {k : ℕ} : m - n ≤ k ↔ m ≤ n + k :=
iff.mpr le_iff_le_iff_lt_iff_lt nat.lt_sub_left_iff_add_lt
theorem sub_le_right_iff_le_add {m : ℕ} {n : ℕ} {k : ℕ} : m - k ≤ n ↔ m ≤ n + k :=
eq.mpr (id (Eq._oldrec (Eq.refl (m - k ≤ n ↔ m ≤ n + k)) (propext sub_le_left_iff_le_add)))
(eq.mpr (id (Eq._oldrec (Eq.refl (m ≤ k + n ↔ m ≤ n + k)) (add_comm k n)))
(iff.refl (m ≤ n + k)))
protected theorem sub_lt_right_iff_lt_add {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) :
m - k < n ↔ m < n + k :=
eq.mpr
(id (Eq._oldrec (Eq.refl (m - k < n ↔ m < n + k)) (propext (nat.sub_lt_left_iff_lt_add H))))
(eq.mpr (id (Eq._oldrec (Eq.refl (m < k + n ↔ m < n + k)) (add_comm k n)))
(iff.refl (m < n + k)))
protected theorem sub_le_sub_left_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n :=
sorry
protected theorem sub_lt_sub_right_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) :
m - k < n - k ↔ m < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff n m k H)
protected theorem sub_lt_sub_left_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ m) : m - n < m - k ↔ k < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H)
protected theorem sub_le_iff {m : ℕ} {n : ℕ} {k : ℕ} : m - n ≤ k ↔ m - k ≤ n :=
iff.trans sub_le_left_iff_le_add (iff.symm sub_le_right_iff_le_add)
protected theorem sub_le_self (n : ℕ) (m : ℕ) : n - m ≤ n :=
nat.sub_le_left_of_le_add (le_add_left n m)
protected theorem sub_lt_iff {m : ℕ} {n : ℕ} {k : ℕ} (h₁ : n ≤ m) (h₂ : k ≤ m) :
m - n < k ↔ m - k < n :=
iff.trans (nat.sub_lt_left_iff_lt_add h₁) (iff.symm (nat.sub_lt_right_iff_lt_add h₂))
theorem pred_le_iff {n : ℕ} {m : ℕ} : Nat.pred n ≤ m ↔ n ≤ Nat.succ m := sub_le_right_iff_le_add
theorem lt_pred_iff {n : ℕ} {m : ℕ} : n < Nat.pred m ↔ Nat.succ n < m := nat.lt_sub_right_iff_add_lt
theorem lt_of_lt_pred {a : ℕ} {b : ℕ} (h : a < b - 1) : a < b :=
lt_of_succ_lt (iff.mp lt_pred_iff h)
/-! ### `mul` -/
theorem mul_self_le_mul_self {n : ℕ} {m : ℕ} (h : n ≤ m) : n * n ≤ m * m :=
mul_le_mul h h (zero_le n) (zero_le m)
theorem mul_self_lt_mul_self {n : ℕ} {m : ℕ} : n < m → n * n < m * m := sorry
theorem mul_self_le_mul_self_iff {n : ℕ} {m : ℕ} : n ≤ m ↔ n * n ≤ m * m := sorry
theorem mul_self_lt_mul_self_iff {n : ℕ} {m : ℕ} : n < m ↔ n * n < m * m :=
iff.trans (lt_iff_not_ge n m)
(iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff)
(iff.symm (lt_iff_not_ge (n * n) (m * m))))
theorem le_mul_self (n : ℕ) : n ≤ n * n := sorry
theorem le_mul_of_pos_left {m : ℕ} {n : ℕ} (h : 0 < n) : m ≤ n * m := sorry
theorem le_mul_of_pos_right {m : ℕ} {n : ℕ} (h : 0 < n) : m ≤ m * n := sorry
theorem two_mul_ne_two_mul_add_one {n : ℕ} {m : ℕ} : bit0 1 * n ≠ bit0 1 * m + 1 := sorry
theorem mul_eq_one_iff {a : ℕ} {b : ℕ} : a * b = 1 ↔ a = 1 ∧ b = 1 := sorry
protected theorem mul_left_inj {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c :=
{ mp := eq_of_mul_eq_mul_right ha, mpr := fun (e : b = c) => e ▸ rfl }
protected theorem mul_right_inj {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c :=
{ mp := eq_of_mul_eq_mul_left ha, mpr := fun (e : b = c) => e ▸ rfl }
theorem mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective fun (x : ℕ) => x * a :=
fun (_x _x_1 : ℕ) => eq_of_mul_eq_mul_right ha
theorem mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective fun (x : ℕ) => a * x :=
fun (_x _x_1 : ℕ) => eq_of_mul_eq_mul_left ha
theorem mul_right_eq_self_iff {a : ℕ} {b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 :=
(fun (this : a * b = a * 1 ↔ b = 1) =>
eq.mp (Eq._oldrec (Eq.refl (a * b = a * 1 ↔ b = 1)) (mul_one a)) this)
(nat.mul_right_inj ha)
theorem mul_left_eq_self_iff {a : ℕ} {b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (a * b = b ↔ a = 1)) (mul_comm a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b ↔ a = 1)) (propext (mul_right_eq_self_iff hb))))
(iff.refl (a = 1)))
theorem lt_succ_iff_lt_or_eq {n : ℕ} {i : ℕ} : n < Nat.succ i ↔ n < i ∨ n = i :=
iff.trans lt_succ_iff le_iff_lt_or_eq
theorem mul_self_inj {n : ℕ} {m : ℕ} : n * n = m * m ↔ n = m :=
iff.trans le_antisymm_iff
(iff.symm
(iff.trans le_antisymm_iff (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)))
/-!
### Recursion and induction principles
This section is here due to dependencies -- the lemmas here require some of the lemmas
proved above, and some of the results in later sections depend on the definitions in this section.
-/
@[simp] theorem rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : (n : ℕ) → C n → C (n + 1)) :
Nat.rec h0 h 0 = h0 :=
rfl
@[simp] theorem rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : (n : ℕ) → C n → C (n + 1)) (n : ℕ) :
Nat.rec h0 h (n + 1) = h n (Nat.rec h0 h n) :=
rfl
/-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`,
there is a map from `C n` to each `C m`, `n ≤ m`. -/
def le_rec_on {C : ℕ → Sort u} {n : ℕ} {m : ℕ} : n ≤ m → ({k : ℕ} → C k → C (k + 1)) → C n → C m :=
sorry
theorem le_rec_on_self {C : ℕ → Sort u} {n : ℕ} {h : n ≤ n} {next : {k : ℕ} → C k → C (k + 1)}
(x : C n) : le_rec_on h next x = x :=
sorry
theorem le_rec_on_succ {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (h1 : n ≤ m) {h2 : n ≤ m + 1}
{next : {k : ℕ} → C k → C (k + 1)} (x : C n) :
le_rec_on h2 next x = next (le_rec_on h1 next x) :=
sorry
theorem le_rec_on_succ' {C : ℕ → Sort u} {n : ℕ} {h : n ≤ n + 1} {next : {k : ℕ} → C k → C (k + 1)}
(x : C n) : le_rec_on h next x = next x :=
eq.mpr (id (Eq._oldrec (Eq.refl (le_rec_on h next x = next x)) (le_rec_on_succ (le_refl n) x)))
(eq.mpr
(id (Eq._oldrec (Eq.refl (next (le_rec_on (le_refl n) next x) = next x)) (le_rec_on_self x)))
(Eq.refl (next x)))
theorem le_rec_on_trans {C : ℕ → Sort u} {n : ℕ} {m : ℕ} {k : ℕ} (hnm : n ≤ m) (hmk : m ≤ k)
{next : {k : ℕ} → C k → C (k + 1)} (x : C n) :
le_rec_on (le_trans hnm hmk) next x = le_rec_on hmk next (le_rec_on hnm next x) :=
sorry
theorem le_rec_on_succ_left {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (h1 : n ≤ m) (h2 : n + 1 ≤ m)
{next : {k : ℕ} → C k → C (k + 1)} (x : C n) :
le_rec_on h2 next (next x) = le_rec_on h1 next x :=
sorry
theorem le_rec_on_injective {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (hnm : n ≤ m)
(next : (n : ℕ) → C n → C (n + 1)) (Hnext : ∀ (n : ℕ), function.injective (next n)) :
function.injective (le_rec_on hnm next) :=
sorry
theorem le_rec_on_surjective {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (hnm : n ≤ m)
(next : (n : ℕ) → C n → C (n + 1)) (Hnext : ∀ (n : ℕ), function.surjective (next n)) :
function.surjective (le_rec_on hnm next) :=
sorry
/-- Recursion principle based on `<`. -/
protected def strong_rec' {p : ℕ → Sort u} (H : (n : ℕ) → ((m : ℕ) → m < n → p m) → p n) (n : ℕ) :
p n :=
sorry
/-- Recursion principle based on `<` applied to some natural number. -/
def strong_rec_on' {P : ℕ → Sort u_1} (n : ℕ) (h : (n : ℕ) → ((m : ℕ) → m < n → P m) → P n) : P n :=
nat.strong_rec' h n
theorem strong_rec_on_beta' {P : ℕ → Sort u_1} {h : (n : ℕ) → ((m : ℕ) → m < n → P m) → P n}
{n : ℕ} : strong_rec_on' n h = h n fun (m : ℕ) (hmn : m < n) => strong_rec_on' m h :=
sorry
/-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/
theorem le_induction {P : ℕ → Prop} {m : ℕ} (h0 : P m) (h1 : ∀ (n : ℕ), m ≤ n → P n → P (n + 1))
(n : ℕ) : m ≤ n → P n :=
less_than_or_equal._oldrec h0 h1
/-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`.
Also works for functions to `Sort*`. -/
def decreasing_induction {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ}
(mn : m ≤ n) (hP : P n) : P m :=
le_rec_on mn (fun (k : ℕ) (ih : P k → P m) (hsk : P (k + 1)) => ih (h k hsk)) (fun (h : P m) => h)
hP
@[simp] theorem decreasing_induction_self {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {n : ℕ}
(nn : n ≤ n) (hP : P n) : decreasing_induction h nn hP = hP :=
sorry
theorem decreasing_induction_succ {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ}
(mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n + 1)) :
decreasing_induction h msn hP = decreasing_induction h mn (h n hP) :=
sorry
@[simp] theorem decreasing_induction_succ' {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n)
{m : ℕ} (msm : m ≤ m + 1) (hP : P (m + 1)) : decreasing_induction h msm hP = h m hP :=
sorry
theorem decreasing_induction_trans {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ}
{n : ℕ} {k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) :
decreasing_induction h (le_trans mn nk) hP =
decreasing_induction h mn (decreasing_induction h nk hP) :=
sorry
theorem decreasing_induction_succ_left {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ}
{n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) :
decreasing_induction h mn hP = h m (decreasing_induction h smn hP) :=
sorry
/-! ### `div` -/
protected theorem div_le_of_le_mul' {m : ℕ} {n : ℕ} {k : ℕ} (h : m ≤ k * n) : m / k ≤ n := sorry
protected theorem div_le_self' (m : ℕ) (n : ℕ) : m / n ≤ m := sorry
/-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/
theorem div_lt_self' (n : ℕ) (b : ℕ) : (n + 1) / (b + bit0 1) < n + 1 :=
div_lt_self (succ_pos n) (succ_lt_succ (succ_pos b))
theorem le_div_iff_mul_le' {x : ℕ} {y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y :=
le_div_iff_mul_le x y k0
theorem div_lt_iff_lt_mul' {x : ℕ} {y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k :=
lt_iff_lt_of_le_iff_le (le_div_iff_mul_le' k0)
protected theorem div_le_div_right {n : ℕ} {m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := sorry
theorem lt_of_div_lt_div {m : ℕ} {n : ℕ} {k : ℕ} (h : m / k < n / k) : m < n :=
by_contradiction
fun (h₁ : ¬m < n) => absurd h (not_lt_of_ge (nat.div_le_div_right (iff.mp not_lt h₁)))
protected theorem div_pos {a : ℕ} {b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := sorry
protected theorem div_lt_of_lt_mul {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n * k) : m / n < k :=
lt_of_mul_lt_mul_left
(lt_of_le_of_lt (trans_rel_left LessEq (le_add_left (n * (m / n)) (m % n)) (mod_add_div m n)) h)
(zero_le n)
theorem lt_mul_of_div_lt {a : ℕ} {b : ℕ} {c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c :=
lt_of_not_ge (not_le_of_gt h ∘ iff.mpr (le_div_iff_mul_le b a w))
protected theorem div_eq_zero_iff {a : ℕ} {b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := sorry
protected theorem div_eq_zero {a : ℕ} {b : ℕ} (hb : a < b) : a / b = 0 :=
iff.mpr (nat.div_eq_zero_iff (has_le.le.trans_lt (zero_le a) hb)) hb
theorem eq_zero_of_le_div {a : ℕ} {b : ℕ} (hb : bit0 1 ≤ b) (h : a ≤ a / b) : a = 0 :=
eq_zero_of_mul_le hb
(eq.mpr (id (Eq._oldrec (Eq.refl (b * a ≤ a)) (mul_comm b a)))
(iff.mp (le_div_iff_mul_le' (lt_of_lt_of_le (of_as_true trivial) hb)) h))
theorem mul_div_le_mul_div_assoc (a : ℕ) (b : ℕ) (c : ℕ) : a * (b / c) ≤ a * b / c := sorry
theorem div_mul_div_le_div (a : ℕ) (b : ℕ) (c : ℕ) : a / c * b / a ≤ b / c := sorry
theorem eq_zero_of_le_half {a : ℕ} (h : a ≤ a / bit0 1) : a = 0 :=
eq_zero_of_le_div (le_refl (bit0 1)) h
protected theorem eq_mul_of_div_eq_right {a : ℕ} {b : ℕ} {c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (Eq.symm H2)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a = b * (a / b))) (nat.mul_div_cancel' H1))) (Eq.refl a))
protected theorem div_eq_iff_eq_mul_right {a : ℕ} {b : ℕ} {c : ℕ} (H : 0 < b) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
{ mp := nat.eq_mul_of_div_eq_right H', mpr := nat.div_eq_of_eq_mul_right H }
protected theorem div_eq_iff_eq_mul_left {a : ℕ} {b : ℕ} {c : ℕ} (H : 0 < b) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a / b = c ↔ a = c * b)) (mul_comm c b)))
(nat.div_eq_iff_eq_mul_right H H')
protected theorem eq_mul_of_div_eq_left {a : ℕ} {b : ℕ} {c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a = c * b)) (mul_comm c b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (nat.eq_mul_of_div_eq_right H1 H2)))
(Eq.refl (b * c)))
protected theorem mul_div_cancel_left' {a : ℕ} {b : ℕ} (Hd : a ∣ b) : a * (b / a) = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / a) = b)) (mul_comm a (b / a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b / a * a = b)) (nat.div_mul_cancel Hd))) (Eq.refl b))
/-! ### `mod`, `dvd` -/
protected theorem div_mod_unique {n : ℕ} {k : ℕ} {m : ℕ} {d : ℕ} (h : 0 < k) :
n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k :=
sorry
theorem two_mul_odd_div_two {n : ℕ} (hn : n % bit0 1 = 1) : bit0 1 * (n / bit0 1) = n - 1 := sorry
theorem div_dvd_of_dvd {a : ℕ} {b : ℕ} (h : b ∣ a) : a / b ∣ a :=
Exists.intro b (Eq.symm (nat.div_mul_cancel h))
protected theorem div_div_self {a : ℕ} {b : ℕ} : b ∣ a → 0 < a → a / (a / b) = b := sorry
theorem mod_mul_right_div_self (a : ℕ) (b : ℕ) (c : ℕ) : a % (b * c) / b = a / b % c := sorry
theorem mod_mul_left_div_self (a : ℕ) (b : ℕ) (c : ℕ) : a % (c * b) / b = a / b % c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a % (c * b) / b = a / b % c)) (mul_comm c b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a % (b * c) / b = a / b % c)) (mod_mul_right_div_self a b c)))
(Eq.refl (a / b % c)))
@[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 :=
{ mp := eq_one_of_dvd_one, mpr := fun (e : n = 1) => Eq.symm e ▸ dvd_refl 1 }
protected theorem dvd_add_left {k : ℕ} {m : ℕ} {n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m :=
iff.symm (nat.dvd_add_iff_left h)
protected theorem dvd_add_right {k : ℕ} {m : ℕ} {n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n :=
iff.symm (nat.dvd_add_iff_right h)
@[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬bit0 1 ∣ bit1 n :=
mt (iff.mp (nat.dvd_add_right two_dvd_bit0)) (of_as_true trivial)
/-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/
@[simp] protected theorem dvd_add_self_left {m : ℕ} {n : ℕ} : m ∣ m + n ↔ m ∣ n :=
nat.dvd_add_right (dvd_refl m)
/-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/
@[simp] protected theorem dvd_add_self_right {m : ℕ} {n : ℕ} : m ∣ n + m ↔ m ∣ n :=
nat.dvd_add_left (dvd_refl m)
theorem not_dvd_of_pos_of_lt {a : ℕ} {b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬a ∣ b := sorry
protected theorem mul_dvd_mul_iff_left {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) :
a * b ∣ a * c ↔ b ∣ c :=
sorry
protected theorem mul_dvd_mul_iff_right {a : ℕ} {b : ℕ} {c : ℕ} (hc : 0 < c) :
a * c ∣ b * c ↔ a ∣ b :=
sorry
theorem succ_div (a : ℕ) (b : ℕ) : (a + 1) / b = a / b + ite (b ∣ a + 1) 1 0 := sorry
theorem succ_div_of_dvd {a : ℕ} {b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl ((a + 1) / b = a / b + 1)) (succ_div a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a / b + ite (b ∣ a + 1) 1 0 = a / b + 1)) (if_pos hba)))
(Eq.refl (a / b + 1)))
theorem succ_div_of_not_dvd {a : ℕ} {b : ℕ} (hba : ¬b ∣ a + 1) : (a + 1) / b = a / b :=
eq.mpr (id (Eq._oldrec (Eq.refl ((a + 1) / b = a / b)) (succ_div a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a / b + ite (b ∣ a + 1) 1 0 = a / b)) (if_neg hba)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a / b + 0 = a / b)) (add_zero (a / b)))) (Eq.refl (a / b))))
@[simp] theorem mod_mod_of_dvd (n : ℕ) {m : ℕ} {k : ℕ} (h : m ∣ k) : n % k % m = n % m := sorry
@[simp] theorem mod_mod (a : ℕ) (n : ℕ) : a % n % n = a % n := sorry
/-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/
theorem sub_mod_eq_zero_of_mod_eq {a : ℕ} {b : ℕ} {c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 :=
sorry
@[simp] theorem one_mod (n : ℕ) : 1 % (n + bit0 1) = 1 :=
mod_eq_of_lt (add_lt_add_right (succ_pos n) 1)
theorem dvd_sub_mod {n : ℕ} (k : ℕ) : n ∣ k - k % n :=
Exists.intro (k / n) (nat.sub_eq_of_eq_add (Eq.symm (mod_add_div k n)))
@[simp] theorem mod_add_mod (m : ℕ) (n : ℕ) (k : ℕ) : (m % n + k) % n = (m + k) % n := sorry
@[simp] theorem add_mod_mod (m : ℕ) (n : ℕ) (k : ℕ) : (m + n % k) % k = (m + n) % k :=
eq.mpr (id (Eq._oldrec (Eq.refl ((m + n % k) % k = (m + n) % k)) (add_comm m (n % k))))
(eq.mpr (id (Eq._oldrec (Eq.refl ((n % k + m) % k = (m + n) % k)) (mod_add_mod n k m)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((n + m) % k = (m + n) % k)) (add_comm n m)))
(Eq.refl ((m + n) % k))))
theorem add_mod (a : ℕ) (b : ℕ) (n : ℕ) : (a + b) % n = (a % n + b % n) % n :=
eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b % n) % n)) (add_mod_mod (a % n) b n)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b) % n)) (mod_add_mod a n b)))
(Eq.refl ((a + b) % n)))
theorem add_mod_eq_add_mod_right {m : ℕ} {n : ℕ} {k : ℕ} (i : ℕ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod m n i))))
(eq.mpr
(id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod k n i))))
(eq.mpr (id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k % n + i) % n)) H))
(Eq.refl ((k % n + i) % n))))
theorem add_mod_eq_add_mod_left {m : ℕ} {n : ℕ} {k : ℕ} (i : ℕ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
eq.mpr (id (Eq._oldrec (Eq.refl ((i + m) % n = (i + k) % n)) (add_comm i m)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (i + k) % n)) (add_mod_eq_add_mod_right i H)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((k + i) % n = (i + k) % n)) (add_comm k i)))
(Eq.refl ((i + k) % n))))
theorem mul_mod (a : ℕ) (b : ℕ) (n : ℕ) : a * b % n = a % n * (b % n) % n := sorry
theorem dvd_div_of_mul_dvd {a : ℕ} {b : ℕ} {c : ℕ} (h : a * b ∣ c) : b ∣ c / a := sorry
theorem mul_dvd_of_dvd_div {a : ℕ} {b : ℕ} {c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b :=
sorry
theorem div_mul_div {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) :
a / b * (c / d) = a * c / (b * d) :=
sorry
@[simp] theorem div_div_div_eq_div {a : ℕ} {b : ℕ} {c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c) :
c / (a / b) / b = c / a :=
sorry
theorem eq_of_dvd_of_div_eq_one {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (nat.div_mul_cancel w))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a = b / a * a)) h))
(eq.mpr (id (Eq._oldrec (Eq.refl (a = 1 * a)) (one_mul a))) (Eq.refl a)))
theorem eq_zero_of_dvd_of_div_eq_zero {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (b = 0)) (Eq.symm (nat.div_mul_cancel w))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b / a * a = 0)) h))
(eq.mpr (id (Eq._oldrec (Eq.refl (0 * a = 0)) (zero_mul a))) (Eq.refl 0)))
/-- If a small natural number is divisible by a larger natural number,
the small number is zero. -/
theorem eq_zero_of_dvd_of_lt {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 :=
eq_zero_of_dvd_of_div_eq_zero w
(iff.elim_right (nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)) h)
theorem div_le_div_left {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c :=
iff.mpr (le_div_iff_mul_le (a / b) a h₂)
(le_trans (mul_le_mul_left (a / b) h₁) (div_mul_le_self a b))
theorem div_eq_self {a : ℕ} {b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := sorry
/-! ### `pow` -/
-- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`,
-- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long.
-- So, we leave a version in the `nat` namespace as well.
-- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.)
protected theorem pow_le_pow_of_le_left {x : ℕ} {y : ℕ} (H : x ≤ y) (i : ℕ) : x ^ i ≤ y ^ i :=
canonically_ordered_semiring.pow_le_pow_of_le_left H
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} {j : ℕ} : i ≤ j → x ^ i ≤ x ^ j := sorry
theorem pow_lt_pow_of_lt_left {x : ℕ} {y : ℕ} (H : x < y) {i : ℕ} (h : 0 < i) : x ^ i < y ^ i :=
sorry
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i : ℕ} {j : ℕ} (h : i < j) : x ^ i < x ^ j :=
sorry
-- TODO: Generalize?
theorem pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p ^ n < p ^ (n + 1) := sorry
theorem lt_pow_self {p : ℕ} (h : 1 < p) (n : ℕ) : n < p ^ n := sorry
theorem lt_two_pow (n : ℕ) : n < bit0 1 ^ n := lt_pow_self (of_as_true trivial) n
theorem one_le_pow (n : ℕ) (m : ℕ) (h : 0 < m) : 1 ≤ m ^ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (1 ≤ m ^ n)) (Eq.symm (one_pow n))))
(nat.pow_le_pow_of_le_left h n)
theorem one_le_pow' (n : ℕ) (m : ℕ) : 1 ≤ (m + 1) ^ n := one_le_pow n (m + 1) (succ_pos m)
theorem one_le_two_pow (n : ℕ) : 1 ≤ bit0 1 ^ n := one_le_pow n (bit0 1) (of_as_true trivial)
theorem one_lt_pow (n : ℕ) (m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m ^ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (1 < m ^ n)) (Eq.symm (one_pow n)))) (pow_lt_pow_of_lt_left h₁ h₀)
theorem one_lt_pow' (n : ℕ) (m : ℕ) : 1 < (m + bit0 1) ^ (n + 1) :=
one_lt_pow (n + 1) (m + bit0 1) (succ_pos n) (nat.lt_of_sub_eq_succ rfl)
theorem one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < bit0 1 ^ n :=
one_lt_pow n (bit0 1) h₀ (of_as_true trivial)
theorem one_lt_two_pow' (n : ℕ) : 1 < bit0 1 ^ (n + 1) :=
one_lt_pow (n + 1) (bit0 1) (succ_pos n) (of_as_true trivial)
theorem pow_right_strict_mono {x : ℕ} (k : bit0 1 ≤ x) : strict_mono fun (n : ℕ) => x ^ n :=
fun (_x _x_1 : ℕ) => pow_lt_pow_of_lt_right k
theorem pow_le_iff_le_right {x : ℕ} {m : ℕ} {n : ℕ} (k : bit0 1 ≤ x) : x ^ m ≤ x ^ n ↔ m ≤ n :=
strict_mono.le_iff_le (pow_right_strict_mono k)
theorem pow_lt_iff_lt_right {x : ℕ} {m : ℕ} {n : ℕ} (k : bit0 1 ≤ x) : x ^ m < x ^ n ↔ m < n :=
strict_mono.lt_iff_lt (pow_right_strict_mono k)
theorem pow_right_injective {x : ℕ} (k : bit0 1 ≤ x) : function.injective fun (n : ℕ) => x ^ n :=
strict_mono.injective (pow_right_strict_mono k)
theorem pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono fun (x : ℕ) => x ^ m :=
fun (_x _x_1 : ℕ) (h : _x < _x_1) => pow_lt_pow_of_lt_left h k
end nat
theorem strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) :
strict_mono fun (m : ℕ) => f m ^ n :=
strict_mono.comp (nat.pow_left_strict_mono hn) hf
namespace nat
theorem pow_le_iff_le_left {m : ℕ} {x : ℕ} {y : ℕ} (k : 1 ≤ m) : x ^ m ≤ y ^ m ↔ x ≤ y :=
strict_mono.le_iff_le (pow_left_strict_mono k)
theorem pow_lt_iff_lt_left {m : ℕ} {x : ℕ} {y : ℕ} (k : 1 ≤ m) : x ^ m < y ^ m ↔ x < y :=
strict_mono.lt_iff_lt (pow_left_strict_mono k)
theorem pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective fun (x : ℕ) => x ^ m :=
strict_mono.injective (pow_left_strict_mono k)
/-! ### `pow` and `mod` / `dvd` -/
theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w : ℕ) (m : ℕ) :
m % b ^ Nat.succ w = b * (m / b % b ^ w) + m % b :=
sorry
theorem pow_dvd_pow_iff_pow_le_pow {k : ℕ} {l : ℕ} {x : ℕ} (w : 0 < x) :
x ^ k ∣ x ^ l ↔ x ^ k ≤ x ^ l :=
sorry
/-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/
theorem pow_dvd_pow_iff_le_right {x : ℕ} {k : ℕ} {l : ℕ} (w : 1 < x) : x ^ k ∣ x ^ l ↔ k ≤ l :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (x ^ k ∣ x ^ l ↔ k ≤ l))
(propext (pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (x ^ k ≤ x ^ l ↔ k ≤ l)) (propext (pow_le_iff_le_right w))))
(iff.refl (k ≤ l)))
theorem pow_dvd_pow_iff_le_right' {b : ℕ} {k : ℕ} {l : ℕ} :
(b + bit0 1) ^ k ∣ (b + bit0 1) ^ l ↔ k ≤ l :=
pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl)
theorem not_pos_pow_dvd {p : ℕ} {k : ℕ} (hp : 1 < p) (hk : 1 < k) : ¬p ^ k ∣ p := sorry
theorem pow_dvd_of_le_of_pow_dvd {p : ℕ} {m : ℕ} {n : ℕ} {k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) :
p ^ m ∣ k :=
(fun (this : p ^ m ∣ p ^ n) => dvd_trans this hdiv) (pow_dvd_pow p hmn)
theorem dvd_of_pow_dvd {p : ℕ} {k : ℕ} {m : ℕ} (hk : 1 ≤ k) (hpk : p ^ k ∣ m) : p ∣ m :=
eq.mpr (id (Eq._oldrec (Eq.refl (p ∣ m)) (Eq.symm (pow_one p)))) (pow_dvd_of_le_of_pow_dvd hk hpk)
/-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/
theorem exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) :
(∃ (k : ℕ), n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m :=
sorry
/-! ### `find` -/
theorem find_eq_iff {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) {m : ℕ} :
nat.find h = m ↔ p m ∧ ∀ (n : ℕ), n < m → ¬p n :=
sorry
@[simp] theorem find_eq_zero {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) :
nat.find h = 0 ↔ p 0 :=
sorry
@[simp] theorem find_pos {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) :
0 < nat.find h ↔ ¬p 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 < nat.find h ↔ ¬p 0)) (propext pos_iff_ne_zero)))
(eq.mpr (id (Eq._oldrec (Eq.refl (nat.find h ≠ 0 ↔ ¬p 0)) (propext not_iff_not)))
(eq.mpr (id (Eq._oldrec (Eq.refl (nat.find h = 0 ↔ p 0)) (propext (find_eq_zero h))))
(iff.refl (p 0))))
/-! ### `find_greatest` -/
/-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i`
exists -/
protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ := sorry
@[simp] theorem find_greatest_zero {P : ℕ → Prop} [decidable_pred P] : nat.find_greatest P 0 = 0 :=
rfl
@[simp] theorem find_greatest_eq {P : ℕ → Prop} [decidable_pred P] {b : ℕ} :
P b → nat.find_greatest P b = b :=
sorry
@[simp] theorem find_greatest_of_not {P : ℕ → Prop} [decidable_pred P] {b : ℕ} (h : ¬P (b + 1)) :
nat.find_greatest P (b + 1) = nat.find_greatest P b :=
sorry
theorem find_greatest_eq_iff {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ} :
nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ ∀ {n : ℕ}, m < n → n ≤ b → ¬P n :=
sorry
theorem find_greatest_eq_zero_iff {P : ℕ → Prop} [decidable_pred P] {b : ℕ} :
nat.find_greatest P b = 0 ↔ ∀ {n : ℕ}, 0 < n → n ≤ b → ¬P n :=
sorry
theorem find_greatest_spec {P : ℕ → Prop} [decidable_pred P] {b : ℕ} (h : ∃ (m : ℕ), m ≤ b ∧ P m) :
P (nat.find_greatest P b) :=
sorry
theorem find_greatest_le {P : ℕ → Prop} [decidable_pred P] {b : ℕ} : nat.find_greatest P b ≤ b :=
and.left (iff.mp find_greatest_eq_iff rfl)
theorem le_find_greatest {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ} (hmb : m ≤ b)
(hm : P m) : m ≤ nat.find_greatest P b :=
le_of_not_lt
fun (hlt : nat.find_greatest P b < m) =>
and.right (and.right (iff.mp find_greatest_eq_iff rfl)) m hlt hmb hm
theorem find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {k : ℕ}
(hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬P k :=
and.right (and.right (iff.mp find_greatest_eq_iff rfl)) k hk hkb
theorem find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ}
(h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m :=
and.left (and.right (iff.mp find_greatest_eq_iff h)) h0
/-! ### `bodd_div2` and `bodd` -/
@[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := sorry
@[simp] theorem bodd_bit0 (n : ℕ) : bodd (bit0 n) = false := bodd_bit false n
@[simp] theorem bodd_bit1 (n : ℕ) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] theorem div2_bit0 (n : ℕ) : div2 (bit0 n) = n := div2_bit false n
@[simp] theorem div2_bit1 (n : ℕ) : div2 (bit1 n) = n := div2_bit tt n
/-! ### `bit0` and `bit1` -/
protected theorem bit0_le {n : ℕ} {m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h
protected theorem bit1_le {n : ℕ} {m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m :=
succ_le_succ (add_le_add h h)
theorem bit_le (b : Bool) {n : ℕ} {m : ℕ} : n ≤ m → bit b n ≤ bit b m :=
fun (ᾰ : n ≤ m) =>
bool.cases_on b (idRhs (bit0 n ≤ bit0 m) (nat.bit0_le ᾰ))
(idRhs (bit1 n ≤ bit1 m) (nat.bit1_le ᾰ))
theorem bit_ne_zero (b : Bool) {n : ℕ} (h : n ≠ 0) : bit b n ≠ 0 :=
bool.cases_on b (nat.bit0_ne_zero h) (nat.bit1_ne_zero n)
theorem bit0_le_bit (b : Bool) {m : ℕ} {n : ℕ} : m ≤ n → bit0 m ≤ bit b n :=
fun (ᾰ : m ≤ n) =>
bool.cases_on b (idRhs (bit0 m ≤ bit0 n) (nat.bit0_le ᾰ))
(idRhs (bit0 m ≤ bit tt n) (le_of_lt (nat.bit0_lt_bit1 ᾰ)))
theorem bit_le_bit1 (b : Bool) {m : ℕ} {n : ℕ} : m ≤ n → bit b m ≤ bit1 n :=
fun (ᾰ : m ≤ n) =>
bool.cases_on b (idRhs (bit false m ≤ bit1 n) (le_of_lt (nat.bit0_lt_bit1 ᾰ)))
(idRhs (bit1 m ≤ bit1 n) (nat.bit1_le ᾰ))
theorem bit_lt_bit0 (b : Bool) {n : ℕ} {m : ℕ} : n < m → bit b n < bit0 m :=
fun (ᾰ : n < m) =>
bool.cases_on b (idRhs (bit0 n < bit0 m) (nat.bit0_lt ᾰ))
(idRhs (bit1 n < bit0 m) (nat.bit1_lt_bit0 ᾰ))
theorem bit_lt_bit (a : Bool) (b : Bool) {n : ℕ} {m : ℕ} (h : n < m) : bit a n < bit b m :=
lt_of_lt_of_le (bit_lt_bit0 a h) (bit0_le_bit b (le_refl m))
@[simp] theorem bit0_le_bit1_iff {n : ℕ} {k : ℕ} : bit0 k ≤ bit1 n ↔ k ≤ n := sorry
@[simp] theorem bit0_lt_bit1_iff {n : ℕ} {k : ℕ} : bit0 k < bit1 n ↔ k ≤ n :=
{ mp := fun (h : bit0 k < bit1 n) => iff.mp bit0_le_bit1_iff (le_of_lt h),
mpr := nat.bit0_lt_bit1 }
@[simp] theorem bit1_le_bit0_iff {n : ℕ} {k : ℕ} : bit1 k ≤ bit0 n ↔ k < n := sorry
@[simp] theorem bit1_lt_bit0_iff {n : ℕ} {k : ℕ} : bit1 k < bit0 n ↔ k < n :=
{ mp := fun (h : bit1 k < bit0 n) => iff.mp bit1_le_bit0_iff (le_of_lt h),
mpr := nat.bit1_lt_bit0 }
@[simp] theorem one_le_bit0_iff {n : ℕ} : 1 ≤ bit0 n ↔ 0 < n := sorry
@[simp] theorem one_lt_bit0_iff {n : ℕ} : 1 < bit0 n ↔ 1 ≤ n := sorry
@[simp] theorem bit_le_bit_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k ≤ bit b n ↔ k ≤ n :=
bool.cases_on b (idRhs (bit0 k ≤ bit0 n ↔ k ≤ n) bit0_le_bit0)
(idRhs (bit1 k ≤ bit1 n ↔ k ≤ n) bit1_le_bit1)
@[simp] theorem bit_lt_bit_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k < bit b n ↔ k < n :=
bool.cases_on b (idRhs (bit0 k < bit0 n ↔ k < n) bit0_lt_bit0)
(idRhs (bit1 k < bit1 n ↔ k < n) bit1_lt_bit1)
@[simp] theorem bit_le_bit1_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k ≤ bit1 n ↔ k ≤ n :=
bool.cases_on b (idRhs (bit0 k ≤ bit1 n ↔ k ≤ n) bit0_le_bit1_iff)
(idRhs (bit1 k ≤ bit1 n ↔ k ≤ n) bit1_le_bit1)
@[simp] theorem bit0_mod_two {n : ℕ} : bit0 n % bit0 1 = 0 := sorry
@[simp] theorem bit1_mod_two {n : ℕ} : bit1 n % bit0 1 = 1 := sorry
theorem pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := sorry
/-- Define a function on `ℕ` depending on parity of the argument. -/
def bit_cases {C : ℕ → Sort u} (H : (b : Bool) → (n : ℕ) → C (bit b n)) (n : ℕ) : C n :=
eq.rec_on (bit_decomp n) (H (bodd n) (div2 n))
/-! ### `shiftl` and `shiftr` -/
theorem shiftl_eq_mul_pow (m : ℕ) (n : ℕ) : shiftl m n = m * bit0 1 ^ n := sorry
theorem shiftl'_tt_eq_mul_pow (m : ℕ) (n : ℕ) : shiftl' tt m n + 1 = (m + 1) * bit0 1 ^ n := sorry
theorem one_shiftl (n : ℕ) : shiftl 1 n = bit0 1 ^ n :=
Eq.trans (shiftl_eq_mul_pow 1 n) (nat.one_mul (bit0 1 ^ n))
@[simp] theorem zero_shiftl (n : ℕ) : shiftl 0 n = 0 :=
Eq.trans (shiftl_eq_mul_pow 0 n) (nat.zero_mul (bit0 1 ^ n))
theorem shiftr_eq_div_pow (m : ℕ) (n : ℕ) : shiftr m n = m / bit0 1 ^ n := sorry
@[simp] theorem zero_shiftr (n : ℕ) : shiftr 0 n = 0 :=
Eq.trans (shiftr_eq_div_pow 0 n) (nat.zero_div (bit0 1 ^ n))
theorem shiftl'_ne_zero_left (b : Bool) {m : ℕ} (h : m ≠ 0) (n : ℕ) : shiftl' b m n ≠ 0 := sorry
theorem shiftl'_tt_ne_zero (m : ℕ) {n : ℕ} (h : n ≠ 0) : shiftl' tt m n ≠ 0 :=
nat.cases_on n (fun (h : 0 ≠ 0) => idRhs (shiftl' tt m 0 ≠ 0) (absurd rfl h))
(fun (n : ℕ) (h : Nat.succ n ≠ 0) =>
idRhs (bit1 (shiftl' tt m n) ≠ 0) (nat.bit1_ne_zero (shiftl' tt m n)))
h
/-! ### `size` -/
@[simp] theorem size_zero : size 0 = 0 := rfl
@[simp] theorem size_bit {b : Bool} {n : ℕ} (h : bit b n ≠ 0) :
size (bit b n) = Nat.succ (size n) :=
sorry
@[simp] theorem size_bit0 {n : ℕ} (h : n ≠ 0) : size (bit0 n) = Nat.succ (size n) :=
size_bit (nat.bit0_ne_zero h)
@[simp] theorem size_bit1 (n : ℕ) : size (bit1 n) = Nat.succ (size n) :=
size_bit (nat.bit1_ne_zero n)
@[simp] theorem size_one : size 1 = 1 := size_bit1 0
@[simp] theorem size_shiftl' {b : Bool} {m : ℕ} {n : ℕ} (h : shiftl' b m n ≠ 0) :
size (shiftl' b m n) = size m + n :=
sorry
@[simp] theorem size_shiftl {m : ℕ} (h : m ≠ 0) (n : ℕ) : size (shiftl m n) = size m + n :=
size_shiftl' (shiftl'_ne_zero_left false h n)
theorem lt_size_self (n : ℕ) : n < bit0 1 ^ size n := sorry
theorem size_le {m : ℕ} {n : ℕ} : size m ≤ n ↔ m < bit0 1 ^ n := sorry
theorem lt_size {m : ℕ} {n : ℕ} : m < size n ↔ bit0 1 ^ m ≤ n := sorry
theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 < size n ↔ 0 < n)) (propext lt_size)))
(iff.refl (bit0 1 ^ 0 ≤ n))
theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := sorry
theorem size_pow {n : ℕ} : size (bit0 1 ^ n) = n + 1 :=
le_antisymm (iff.mpr size_le (pow_lt_pow_of_lt_right (of_as_true trivial) (lt_succ_self n)))
(iff.mpr lt_size (le_refl (bit0 1 ^ n)))
theorem size_le_size {m : ℕ} {n : ℕ} (h : m ≤ n) : size m ≤ size n :=
iff.mpr size_le (lt_of_le_of_lt h (lt_size_self n))
/-! ### decidability of predicates -/
protected instance decidable_ball_lt (n : ℕ) (P : (k : ℕ) → k < n → Prop)
[H : (n_1 : ℕ) → (h : n_1 < n) → Decidable (P n_1 h)] :
Decidable (∀ (n_1 : ℕ) (h : n_1 < n), P n_1 h) :=
Nat.rec
(fun (P : (k : ℕ) → k < 0 → Prop) (H : (n : ℕ) → (h : n < 0) → Decidable (P n h)) =>
is_true sorry)
(fun (n : ℕ)
(IH :
(P : (k : ℕ) → k < n → Prop) →
[H : (n_1 : ℕ) → (h : n_1 < n) → Decidable (P n_1 h)] →
Decidable (∀ (n_1 : ℕ) (h : n_1 < n), P n_1 h))
(P : (k : ℕ) → k < Nat.succ n → Prop)
(H : (n_1 : ℕ) → (h : n_1 < Nat.succ n) → Decidable (P n_1 h)) =>
decidable.cases_on (IH fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h))
(fun
(h :
¬∀ (n_1 : ℕ) (h : n_1 < n), (fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h)) n_1 h) =>
isFalse sorry)
fun
(h :
∀ (n_1 : ℕ) (h : n_1 < n), (fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h)) n_1 h) =>
dite (P n (lt_succ_self n)) (fun (p : P n (lt_succ_self n)) => is_true sorry)
fun (p : ¬P n (lt_succ_self n)) => isFalse sorry)
n P
protected instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] :
Decidable (∀ (i : fin n), P i) :=
decidable_of_iff (∀ (k : ℕ) (h : k < n), P { val := k, property := h }) sorry
protected instance decidable_ball_le (n : ℕ) (P : (k : ℕ) → k ≤ n → Prop)
[H : (n_1 : ℕ) → (h : n_1 ≤ n) → Decidable (P n_1 h)] :
Decidable (∀ (n_1 : ℕ) (h : n_1 ≤ n), P n_1 h) :=
decidable_of_iff (∀ (k : ℕ) (h : k < Nat.succ n), P k (le_of_lt_succ h)) sorry
protected instance decidable_lo_hi (lo : ℕ) (hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
Decidable (∀ (x : ℕ), lo ≤ x → x < hi → P x) :=
decidable_of_iff (∀ (x : ℕ), x < hi - lo → P (lo + x)) sorry
protected instance decidable_lo_hi_le (lo : ℕ) (hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
Decidable (∀ (x : ℕ), lo ≤ x → x ≤ hi → P x) :=
decidable_of_iff (∀ (x : ℕ), lo ≤ x → x < hi + 1 → P x) sorry
protected instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] :
decidable_pred fun (n : ℕ) => ∃ (m : ℕ), m < n ∧ P m :=
sorry
/-! ### find -/
theorem find_le {p : ℕ → Prop} {q : ℕ → Prop} [decidable_pred p] [decidable_pred q]
(h : ∀ (n : ℕ), q n → p n) (hp : ∃ (n : ℕ), p n) (hq : ∃ (n : ℕ), q n) :
nat.find hp ≤ nat.find hq :=
nat.find_min' hp (h (nat.find hq) (nat.find_spec hq))
end Mathlib |
54b84d858896fc2e85225af48562e20b012fb2a7 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Init/Data/Hashable.lean | b34c41c1654d2a514b3e96c61afabad1c7333009 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 787 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.UInt
import Init.Data.String
universes u
instance : Hashable Nat := {
hash := fun n => USize.ofNat n
}
instance {α β} [Hashable α] [Hashable β] : Hashable (α × β) := {
hash := fun (a, b) => mixHash (hash a) (hash b)
}
protected def Option.hash {α} [Hashable α] : Option α → USize
| none => 11
| some a => mixHash (hash a) 13
instance {α} [Hashable α] : Hashable (Option α) := {
hash := fun
| none => 11
| some a => mixHash (hash a) 13
}
instance {α} [Hashable α] : Hashable (List α) := {
hash := fun as => as.foldl (fun r a => mixHash r (hash a)) 7
}
|
2ec85ccaaac04eccc9e0f34a954286abccabe45c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/list/palindrome_auto.lean | e89bf1499fc482dd7a89191b6d9e38b4ca90b673 | [] | 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 | 1,884 | lean | /-
Copyright (c) 2020 Google LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Wong
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.list.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Palindromes
This module defines *palindromes*, lists which are equal to their reverse.
The main result is the `palindrome` inductive type, and its associated `palindrome.rec_on` induction
principle. Also provided are conversions to and from other equivalent definitions.
## References
* [Pierre Castéran, *On palindromes*][casteran]
[casteran]: https://www.labri.fr/perso/casteran/CoqArt/inductive-prop-chap/palindrome.html
## Tags
palindrome, reverse, induction
-/
/--
`palindrome l` asserts that `l` is a palindrome. This is defined inductively:
* The empty list is a palindrome;
* A list with one element is a palindrome;
* Adding the same element to both ends of a palindrome results in a bigger palindrome.
-/
inductive palindrome {α : Type u_1} : List α → Prop where
| nil : palindrome []
| singleton : ∀ (x : α), palindrome [x]
| cons_concat : ∀ (x : α) {l : List α}, palindrome l → palindrome (x :: (l ++ [x]))
namespace palindrome
theorem reverse_eq {α : Type u_1} {l : List α} (p : palindrome l) : list.reverse l = l := sorry
theorem of_reverse_eq {α : Type u_1} {l : List α} : list.reverse l = l → palindrome l := sorry
theorem iff_reverse_eq {α : Type u_1} {l : List α} : palindrome l ↔ list.reverse l = l :=
{ mp := reverse_eq, mpr := of_reverse_eq }
theorem append_reverse {α : Type u_1} (l : List α) : palindrome (l ++ list.reverse l) := sorry
protected instance decidable {α : Type u_1} [DecidableEq α] (l : List α) :
Decidable (palindrome l) :=
decidable_of_iff' (list.reverse l = l) iff_reverse_eq
end Mathlib |
30ab3e6ffc4b114aaeed541b5da971c7bceb5872 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/opposites.lean | d44a4cb43493a0aeeea996ab3a0836e976d7605a | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,695 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison
-/
import category_theory.types
import category_theory.equivalence
/-!
# Opposite categories
We provide a category instance on `Cᵒᵖ`.
The morphisms `X ⟶ Y` are defined to be the morphisms `unop Y ⟶ unop X` in `C`.
Here `Cᵒᵖ` is an irreducible typeclass synonym for `C`
(it is the same one used in the algebra library).
We also provide various mechanisms for constructing opposite morphisms, functors,
and natural transformations.
Unfortunately, because we do not have a definitional equality `op (op X) = X`,
there are quite a few variations that are needed in practice.
-/
universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].
open opposite
variables {C : Type u₁}
section quiver
variables [quiver.{v₁} C]
lemma quiver.hom.op_inj {X Y : C} :
function.injective (quiver.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) :=
λ _ _ H, congr_arg quiver.hom.unop H
lemma quiver.hom.unop_inj {X Y : Cᵒᵖ} :
function.injective (quiver.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) :=
λ _ _ H, congr_arg quiver.hom.op H
@[simp] lemma quiver.hom.unop_op {X Y : C} (f : X ⟶ Y) : f.op.unop = f := rfl
@[simp] lemma quiver.hom.op_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : f.unop.op = f := rfl
end quiver
namespace category_theory
variables [category.{v₁} C]
/--
The opposite category.
See https://stacks.math.columbia.edu/tag/001M.
-/
instance category.opposite : category.{v₁} Cᵒᵖ :=
{ comp := λ _ _ _ f g, (g.unop ≫ f.unop).op,
id := λ X, (𝟙 (unop X)).op }
@[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).op = g.op ≫ f.op := rfl
@[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl
@[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unop = g.unop ≫ f.unop := rfl
@[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl
@[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl
@[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl
section
variables (C)
/-- The functor from the double-opposite of a category to the underlying category. -/
@[simps]
def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C :=
{ obj := λ X, unop (unop X),
map := λ X Y f, f.unop.unop }
/-- The functor from a category to its double-opposite. -/
@[simps]
def unop_unop : C ⥤ Cᵒᵖᵒᵖ :=
{ obj := λ X, op (op X),
map := λ X Y f, f.op.op }
/-- The double opposite category is equivalent to the original. -/
@[simps]
def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C :=
{ functor := op_op C,
inverse := unop_unop C,
unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ),
counit_iso := iso.refl (unop_unop C ⋙ op_op C) }
end
/-- If `f` is an isomorphism, so is `f.op` -/
instance is_iso_op {X Y : C} (f : X ⟶ Y) [is_iso f] : is_iso f.op :=
⟨⟨(inv f).op,
⟨quiver.hom.unop_inj (by tidy), quiver.hom.unop_inj (by tidy)⟩⟩⟩
/--
If `f.op` is an isomorphism `f` must be too.
(This cannot be an instance as it would immediately loop!)
-/
lemma is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f :=
⟨⟨(inv (f.op)).unop,
⟨quiver.hom.op_inj (by simp), quiver.hom.op_inj (by simp)⟩⟩⟩
@[simp] lemma op_inv {X Y : C} (f : X ⟶ Y) [f_iso : is_iso f] : (inv f).op = inv f.op :=
by { ext, rw [← op_comp, is_iso.inv_hom_id, op_id] }
namespace functor
section
variables {D : Type u₂} [category.{v₂} D]
variables {C D}
/--
The opposite of a functor, i.e. considering a functor `F : C ⥤ D` as a functor `Cᵒᵖ ⥤ Dᵒᵖ`.
In informal mathematics no distinction is made between these.
-/
@[simps]
protected def op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).op }
/--
Given a functor `F : Cᵒᵖ ⥤ Dᵒᵖ` we can take the "unopposite" functor `F : C ⥤ D`.
In informal mathematics no distinction is made between these.
-/
@[simps]
protected def unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D :=
{ obj := λ X, unop (F.obj (op X)),
map := λ X Y f, (F.map f.op).unop }
/-- The isomorphism between `F.op.unop` and `F`. -/
@[simps] def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
/-- The isomorphism between `F.unop.op` and `F`. -/
@[simps] def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
variables (C D)
/--
Taking the opposite of a functor is functorial.
-/
@[simps]
def op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) :=
{ obj := λ F, (unop F).op,
map := λ F G α,
{ app := λ X, (α.unop.app (unop X)).op,
naturality' := λ X Y f, quiver.hom.unop_inj (α.unop.naturality f.unop).symm } }
/--
Take the "unopposite" of a functor is functorial.
-/
@[simps]
def op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ :=
{ obj := λ F, op F.unop,
map := λ F G α, quiver.hom.op
{ app := λ X, (α.app (op X)).unop,
naturality' := λ X Y f, quiver.hom.op_inj $ (α.naturality f.op).symm } }
variables {C D}
/--
Another variant of the opposite of functor, turning a functor `C ⥤ Dᵒᵖ` into a functor `Cᵒᵖ ⥤ D`.
In informal mathematics no distinction is made.
-/
@[simps]
protected def left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D :=
{ obj := λ X, unop (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).unop }
/--
Another variant of the opposite of functor, turning a functor `Cᵒᵖ ⥤ D` into a functor `C ⥤ Dᵒᵖ`.
In informal mathematics no distinction is made.
-/
@[simps]
protected def right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (op X)),
map := λ X Y f, (F.map f.op).op }
instance {F : C ⥤ D} [full F] : full F.op :=
{ preimage := λ X Y f, (F.preimage f.unop).op }
instance {F : C ⥤ D} [faithful F] : faithful F.op :=
{ map_injective' := λ X Y f g h,
quiver.hom.unop_inj $ by simpa using map_injective F (quiver.hom.op_inj h) }
/-- If F is faithful then the right_op of F is also faithful. -/
instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op :=
{ map_injective' := λ X Y f g h, quiver.hom.op_inj (map_injective F (quiver.hom.op_inj h)) }
/-- If F is faithful then the left_op of F is also faithful. -/
instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op :=
{ map_injective' := λ X Y f g h, quiver.hom.unop_inj (map_injective F (quiver.hom.unop_inj h)) }
/-- The isomorphism between `F.left_op.right_op` and `F`. -/
@[simps]
def left_op_right_op_iso (F : C ⥤ Dᵒᵖ) : F.left_op.right_op ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
/-- The isomorphism between `F.right_op.left_op` and `F`. -/
@[simps]
def right_op_left_op_iso (F : Cᵒᵖ ⥤ D) : F.right_op.left_op ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
end
end functor
namespace nat_trans
variables {D : Type u₂} [category.{v₂} D]
section
variables {F G : C ⥤ D}
/-- The opposite of a natural transformation. -/
@[simps] protected def op (α : F ⟶ G) : G.op ⟶ F.op :=
{ app := λ X, (α.app (unop X)).op,
naturality' := begin tidy, simp_rw [← op_comp, α.naturality] end }
@[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl
/-- The "unopposite" of a natural transformation. -/
@[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) : G.unop ⟶ F.unop :=
{ app := λ X, (α.app (op X)).unop,
naturality' := begin tidy, simp_rw [← unop_comp, α.naturality] end }
@[simp] lemma unop_id (F : Cᵒᵖ ⥤ Dᵒᵖ) : nat_trans.unop (𝟙 F) = 𝟙 (F.unop) := rfl
/--
Given a natural transformation `α : F.op ⟶ G.op`,
we can take the "unopposite" of each component obtaining a natural transformation `G ⟶ F`.
-/
@[simps] protected def remove_op (α : F.op ⟶ G.op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).unop,
naturality' :=
begin
intros X Y f,
have := congr_arg quiver.hom.unop (α.naturality f.op),
dsimp at this,
rw this,
end }
@[simp] lemma remove_op_id (F : C ⥤ D) : nat_trans.remove_op (𝟙 F.op) = 𝟙 F := rfl
end
section
variables {F G H : C ⥤ Dᵒᵖ}
/--
Given a natural transformation `α : F ⟶ G`, for `F G : C ⥤ Dᵒᵖ`,
taking `unop` of each component gives a natural transformation `G.left_op ⟶ F.left_op`.
-/
@[simps] protected def left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op :=
{ app := λ X, (α.app (unop X)).unop,
naturality' := begin
intros X Y f,
dsimp,
simp_rw [← unop_comp, α.naturality]
end }
@[simp] lemma left_op_id : (𝟙 F : F ⟶ F).left_op = 𝟙 F.left_op := rfl
@[simp] lemma left_op_comp (α : F ⟶ G) (β : G ⟶ H) :
(α ≫ β).left_op = β.left_op ≫ α.left_op := rfl
/--
Given a natural transformation `α : F.left_op ⟶ G.left_op`, for `F G : C ⥤ Dᵒᵖ`,
taking `op` of each component gives a natural transformation `G ⟶ F`.
-/
@[simps] protected def remove_left_op (α : F.left_op ⟶ G.left_op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).op,
naturality' :=
begin
intros X Y f,
have := congr_arg quiver.hom.op (α.naturality f.op),
dsimp at this,
erw this
end }
end
section
variables {F G H : Cᵒᵖ ⥤ D}
/--
Given a natural transformation `α : F ⟶ G`, for `F G : Cᵒᵖ ⥤ D`,
taking `op` of each component gives a natural transformation `G.right_op ⟶ F.right_op`.
-/
@[simps] protected def right_op (α : F ⟶ G) : G.right_op ⟶ F.right_op :=
{ app := λ X, (α.app _).op,
naturality' := begin
intros X Y f,
dsimp,
simp_rw [← op_comp, α.naturality]
end }
@[simp] lemma right_op_id : (𝟙 F : F ⟶ F).right_op = 𝟙 F.right_op := rfl
@[simp] lemma right_op_comp (α : F ⟶ G) (β : G ⟶ H) :
(α ≫ β).right_op = β.right_op ≫ α.right_op := rfl
/--
Given a natural transformation `α : F.right_op ⟶ G.right_op`, for `F G : Cᵒᵖ ⥤ D`,
taking `unop` of each component gives a natural transformation `G ⟶ F`.
-/
@[simps] protected def remove_right_op (α : F.right_op ⟶ G.right_op) : G ⟶ F :=
{ app := λ X, (α.app X.unop).unop,
naturality' := begin
intros X Y f,
have := congr_arg quiver.hom.unop (α.naturality f.unop),
dsimp at this,
erw this,
end }
end
end nat_trans
namespace iso
variables {X Y : C}
/--
The opposite isomorphism.
-/
@[simps]
protected def op (α : X ≅ Y) : op Y ≅ op X :=
{ hom := α.hom.op,
inv := α.inv.op,
hom_inv_id' := quiver.hom.unop_inj α.inv_hom_id,
inv_hom_id' := quiver.hom.unop_inj α.hom_inv_id }
/-- The isomorphism obtained from an isomorphism in the opposite category. -/
@[simps] def unop {X Y : Cᵒᵖ} (f : X ≅ Y) : Y.unop ≅ X.unop :=
{ hom := f.hom.unop,
inv := f.inv.unop,
hom_inv_id' := by simp only [← unop_comp, f.inv_hom_id, unop_id],
inv_hom_id' := by simp only [← unop_comp, f.hom_inv_id, unop_id] }
@[simp] lemma unop_op {X Y : Cᵒᵖ} (f : X ≅ Y) : f.unop.op = f :=
by ext; refl
@[simp] lemma op_unop {X Y : C} (f : X ≅ Y) : f.op.unop = f :=
by ext; refl
end iso
namespace nat_iso
variables {D : Type u₂} [category.{v₂} D]
variables {F G : C ⥤ D}
/-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural
isomorphism between the original functors `F ≅ G`. -/
@[simps] protected def op (α : F ≅ G) : G.op ≅ F.op :=
{ hom := nat_trans.op α.hom,
inv := nat_trans.op α.inv,
hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end }
/-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism
between the opposite functors `F.op ≅ G.op`. -/
@[simps] protected def remove_op (α : F.op ≅ G.op) : G ≅ F :=
{ hom := nat_trans.remove_op α.hom,
inv := nat_trans.remove_op α.inv,
hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end }
/-- The natural isomorphism between functors `G.unop ≅ F.unop` induced by a natural isomorphism
between the original functors `F ≅ G`. -/
@[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ≅ G) : G.unop ≅ F.unop :=
{ hom := nat_trans.unop α.hom,
inv := nat_trans.unop α.inv,
hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end }
end nat_iso
namespace equivalence
variables {D : Type u₂} [category.{v₂} D]
/--
An equivalence between categories gives an equivalence between the opposite categories.
-/
@[simps]
def op (e : C ≌ D) : Cᵒᵖ ≌ Dᵒᵖ :=
{ functor := e.functor.op,
inverse := e.inverse.op,
unit_iso := (nat_iso.op e.unit_iso).symm,
counit_iso := (nat_iso.op e.counit_iso).symm,
functor_unit_iso_comp' := λ X, by { apply quiver.hom.unop_inj, dsimp, simp, }, }
/--
An equivalence between opposite categories gives an equivalence between the original categories.
-/
@[simps]
def unop (e : Cᵒᵖ ≌ Dᵒᵖ) : C ≌ D :=
{ functor := e.functor.unop,
inverse := e.inverse.unop,
unit_iso := (nat_iso.unop e.unit_iso).symm,
counit_iso := (nat_iso.unop e.counit_iso).symm,
functor_unit_iso_comp' := λ X, by { apply quiver.hom.op_inj, dsimp, simp, }, }
end equivalence
/-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building
adjunctions.
Note that this (definitionally) gives variants
```
def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) :=
op_equiv _ _
def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) :=
op_equiv _ _
def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) :=
op_equiv _ _
```
-/
@[simps] def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) :=
{ to_fun := λ f, f.unop,
inv_fun := λ g, g.op,
left_inv := λ _, rfl,
right_inv := λ _, rfl }
instance subsingleton_of_unop (A B : Cᵒᵖ) [subsingleton (unop B ⟶ unop A)] : subsingleton (A ⟶ B) :=
(op_equiv A B).subsingleton
instance decidable_eq_of_unop (A B : Cᵒᵖ) [decidable_eq (unop B ⟶ unop A)] : decidable_eq (A ⟶ B) :=
(op_equiv A B).decidable_eq
namespace functor
variables (C)
variables (D : Type u₂) [category.{v₂} D]
/--
The equivalence of functor categories induced by `op` and `unop`.
-/
@[simps]
def op_unop_equiv : (C ⥤ D)ᵒᵖ ≌ Cᵒᵖ ⥤ Dᵒᵖ :=
{ functor := op_hom _ _,
inverse := op_inv _ _,
unit_iso := nat_iso.of_components (λ F, F.unop.op_unop_iso.op) begin
intros F G f,
dsimp [op_unop_iso],
rw [(show f = f.unop.op, by simp), ← op_comp, ← op_comp],
congr' 1,
tidy,
end,
counit_iso := nat_iso.of_components (λ F, F.unop_op_iso) (by tidy) }.
/--
The equivalence of functor categories induced by `left_op` and `right_op`.
-/
@[simps]
def left_op_right_op_equiv : (Cᵒᵖ ⥤ D)ᵒᵖ ≌ (C ⥤ Dᵒᵖ) :=
{ functor :=
{ obj := λ F, F.unop.right_op,
map := λ F G η, η.unop.right_op },
inverse :=
{ obj := λ F, op F.left_op,
map := λ F G η, η.left_op.op },
unit_iso := nat_iso.of_components (λ F, F.unop.right_op_left_op_iso.op) begin
intros F G η,
dsimp,
rw [(show η = η.unop.op, by simp), ← op_comp, ← op_comp],
congr' 1,
tidy,
end,
counit_iso := nat_iso.of_components (λ F, F.left_op_right_op_iso) (by tidy) }
end functor
end category_theory
|
a7b33bd0baf28fcc2f140bf22c410bc592aee368 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/polynomial/chebyshev.lean | 2c2439b7f5d151e56b2ab040deb1ae3d08d67d18 | [
"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 | 11,067 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Julian Kuelshammer, Heather Macbeth
-/
import data.polynomial.derivative
import tactic.ring
/-!
# Chebyshev polynomials
The Chebyshev polynomials are two families of polynomials indexed by `ℕ`,
with integral coefficients.
## Main definitions
* `polynomial.chebyshev.T`: the Chebyshev polynomials of the first kind.
* `polynomial.chebyshev.U`: the Chebyshev polynomials of the second kind.
## Main statements
* The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the
Chebyshev polynomials of the second kind.
* `polynomial.chebyshev.mul_T`, the product of the `m`-th and `(m + k)`-th Chebyshev polynomials of
the first kind is the sum of the `(2 * m + k)`-th and `k`-th Chebyshev polynomials of the first
kind.
* `polynomial.chebyshev.T_mul`, the `(m * n)`-th Chebyshev polynomial of the first kind is the
composition of the `m`-th and `n`-th Chebyshev polynomials of the first kind.
## Implementation details
Since Chebyshev polynomials have interesting behaviour over the complex numbers and modulo `p`,
we define them to have coefficients in an arbitrary commutative ring, even though
technically `ℤ` would suffice.
The benefit of allowing arbitrary coefficient rings, is that the statements afterwards are clean,
and do not have `map (int.cast_ring_hom R)` interfering all the time.
## References
[Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_]
[ponton2020chebyshev]
## TODO
* Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`.
* Add explicit formula involving square roots for Chebyshev polynomials
* Compute zeroes and extrema of Chebyshev polynomials.
* Prove that the roots of the Chebyshev polynomials (except 0) are irrational.
* Prove minimax properties of Chebyshev polynomials.
-/
noncomputable theory
namespace polynomial.chebyshev
open polynomial
variables (R S : Type*) [comm_ring R] [comm_ring S]
/-- `T n` is the `n`-th Chebyshev polynomial of the first kind -/
noncomputable def T : ℕ → polynomial R
| 0 := 1
| 1 := X
| (n + 2) := 2 * X * T (n + 1) - T n
@[simp] lemma T_zero : T R 0 = 1 := rfl
@[simp] lemma T_one : T R 1 = X := rfl
lemma T_two : T R 2 = 2 * X ^ 2 - 1 :=
by simp only [T, sub_left_inj, sq, mul_assoc]
@[simp] lemma T_add_two (n : ℕ) :
T R (n + 2) = 2 * X * T R (n + 1) - T R n :=
by rw T
lemma T_of_two_le (n : ℕ) (h : 2 ≤ n) :
T R n = 2 * X * T R (n - 1) - T R (n - 2) :=
begin
obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h,
rw add_comm,
exact T_add_two R n
end
variables {R S}
lemma map_T (f : R →+* S) :
∀ (n : ℕ), map f (T R n) = T S n
| 0 := by simp only [T_zero, map_one]
| 1 := by simp only [T_one, map_X]
| (n + 2) :=
begin
simp only [T_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one],
rw [map_T (n + 1), map_T n],
end
variables (R S)
/-- `U n` is the `n`-th Chebyshev polynomial of the second kind -/
noncomputable def U : ℕ → polynomial R
| 0 := 1
| 1 := 2 * X
| (n + 2) := 2 * X * U (n + 1) - U n
@[simp] lemma U_zero : U R 0 = 1 := rfl
@[simp] lemma U_one : U R 1 = 2 * X := rfl
lemma U_two : U R 2 = 4 * X ^ 2 - 1 :=
by { simp only [U], ring, }
@[simp] lemma U_add_two (n : ℕ) :
U R (n + 2) = 2 * X * U R (n + 1) - U R n :=
by rw U
lemma U_of_two_le (n : ℕ) (h : 2 ≤ n) :
U R n = 2 * X * U R (n - 1) - U R (n - 2) :=
begin
obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h,
rw add_comm,
exact U_add_two R n
end
lemma U_eq_X_mul_U_add_T :
∀ (n : ℕ), U R (n+1) = X * U R n + T R (n+1)
| 0 := by { simp only [U_zero, U_one, T_one], ring }
| 1 := by { simp only [U_one, T_two, U_two], ring }
| (n + 2) :=
calc U R (n + 2 + 1) = 2 * X * (X * U R (n + 1) + T R (n + 2)) - (X * U R n + T R (n + 1)) :
by simp only [U_add_two, U_eq_X_mul_U_add_T n, U_eq_X_mul_U_add_T (n + 1)]
... = X * (2 * X * U R (n + 1) - U R n) + (2 * X * T R (n + 2) - T R (n + 1)) : by ring
... = X * U R (n + 2) + T R (n + 2 + 1) : by simp only [U_add_two, T_add_two]
lemma T_eq_U_sub_X_mul_U (n : ℕ) :
T R (n+1) = U R (n+1) - X * U R n :=
by rw [U_eq_X_mul_U_add_T, add_comm (X * U R n), add_sub_cancel]
lemma T_eq_X_mul_T_sub_pol_U :
∀ (n : ℕ), T R (n+2) = X * T R (n+1) - (1 - X ^ 2) * U R n
| 0 := by { simp only [T_one, T_two, U_zero], ring }
| 1 := by { simp only [T_add_two, T_zero, T_add_two,
U_one, T_one], ring }
| (n + 2) :=
calc T R (n + 2 + 2)
= 2 * X * T R (n + 2 + 1) - T R (n + 2) : T_add_two _ _
... = 2 * X * (X * T R (n + 2) - (1 - X ^ 2) * U R (n + 1))
- (X * T R (n + 1) - (1 - X ^ 2) * U R n) : by simp only [T_eq_X_mul_T_sub_pol_U]
... = X * (2 * X * T R (n + 2) - T R (n + 1)) - (1 - X ^ 2) * (2 * X * U R (n + 1) - U R n) :
by ring
... = X * T R (n + 2 + 1) - (1 - X ^ 2) * U R (n + 2) : by rw [T_add_two _ (n + 1), U_add_two]
lemma one_sub_X_sq_mul_U_eq_pol_in_T (n : ℕ) :
(1 - X ^ 2) * U R n = X * T R (n + 1) - T R (n + 2) :=
by rw [T_eq_X_mul_T_sub_pol_U, ←sub_add, sub_self, zero_add]
variables {R S}
@[simp] lemma map_U (f : R →+* S) :
∀ (n : ℕ), map f (U R n) = U S n
| 0 := by simp only [U_zero, map_one]
| 1 :=
begin
simp only [U_one, map_X, map_mul, map_add, map_one],
change map f (1+1) * X = 2 * X,
simpa only [map_add, map_one]
end
| (n + 2) :=
begin
simp only [U_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one],
rw [map_U (n + 1), map_U n],
end
lemma T_derivative_eq_U :
∀ (n : ℕ), derivative (T R (n + 1)) = (n + 1) * U R n
| 0 := by simp only [T_one, U_zero, derivative_X, nat.cast_zero, zero_add, mul_one]
| 1 := by { simp only [T_two, U_one, derivative_sub, derivative_one, derivative_mul,
derivative_X_pow, nat.cast_one, nat.cast_two],
norm_num }
| (n + 2) :=
calc derivative (T R (n + 2 + 1))
= 2 * T R (n + 2) + 2 * X * derivative (T R (n + 1 + 1)) - derivative (T R (n + 1)) :
by simp only [T_add_two _ (n + 1), derivative_sub, derivative_mul, derivative_X,
derivative_bit0, derivative_one, bit0_zero, zero_mul, zero_add, mul_one]
... = 2 * (U R (n + 1 + 1) - X * U R (n + 1)) + 2 * X * ((n + 1 + 1) * U R (n + 1))
- (n + 1) * U R n : by rw_mod_cast [T_derivative_eq_U, T_derivative_eq_U,
T_eq_U_sub_X_mul_U]
... = (n + 1) * (2 * X * U R (n + 1) - U R n) + 2 * U R (n + 2) : by ring
... = (n + 1) * U R (n + 2) + 2 * U R (n + 2) : by rw U_add_two
... = (n + 2 + 1) * U R (n + 2) : by ring
... = (↑(n + 2) + 1) * U R (n + 2) : by norm_cast
lemma one_sub_X_sq_mul_derivative_T_eq_poly_in_T (n : ℕ) :
(1 - X ^ 2) * (derivative (T R (n+1))) =
(n + 1) * (T R n - X * T R (n+1)) :=
calc
(1 - X ^ 2) * (derivative (T R (n+1))) = (1 - X ^ 2 ) * ((n + 1) * U R n) :
by rw T_derivative_eq_U
... = (n + 1) * ((1 - X ^ 2) * U R n) : by ring
... = (n + 1) * (X * T R (n + 1) - (2 * X * T R (n + 1) - T R n)) :
by rw [one_sub_X_sq_mul_U_eq_pol_in_T, T_add_two]
... = (n + 1) * (T R n - X * T R (n+1)) : by ring
lemma add_one_mul_T_eq_poly_in_U (n : ℕ) :
((n : polynomial R) + 1) * T R (n+1) =
X * U R n - (1 - X ^ 2) * derivative ( U R n) :=
begin
have h : derivative (T R (n + 2)) = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1))
+ 2 * X * U R n - (1 - X ^ 2) * derivative (U R n),
{ conv_lhs { rw T_eq_X_mul_T_sub_pol_U },
simp only [derivative_sub, derivative_mul, derivative_X, derivative_one, derivative_X_pow,
one_mul, T_derivative_eq_U],
rw [T_eq_U_sub_X_mul_U, nat.cast_bit0, nat.cast_one],
ring },
calc ((n : polynomial R) + 1) * T R (n + 1)
= ((n : polynomial R) + 1 + 1) * (X * U R n + T R (n + 1))
- X * ((n + 1) * U R n) - (X * U R n + T R (n + 1)) : by ring
... = derivative (T R (n + 2)) - X * derivative (T R (n + 1)) - U R (n + 1) :
by rw [←U_eq_X_mul_U_add_T, ←T_derivative_eq_U, ←nat.cast_one, ←nat.cast_add,
nat.cast_one, ←T_derivative_eq_U (n + 1)]
... = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1))
+ 2 * X * U R n - (1 - X ^ 2) * derivative (U R n)
- X * derivative (T R (n + 1)) - U R (n + 1) : by rw h
... = X * U R n - (1 - X ^ 2) * derivative (U R n) : by ring,
end
variables (R)
/-- The product of two Chebyshev polynomials is the sum of two other Chebyshev polynomials. -/
lemma mul_T :
∀ m : ℕ, ∀ k,
2 * T R m * T R (m + k) = T R (2 * m + k) + T R k
| 0 := by simp [two_mul, add_mul]
| 1 := by simp [add_comm]
| (m + 2) := begin
intros k,
-- clean up the `T` nat indices in the goal
suffices : 2 * T R (m + 2) * T R (m + k + 2) = T R (2 * m + k + 4) + T R k,
{ have h_nat₁ : 2 * (m + 2) + k = 2 * m + k + 4 := by ring,
have h_nat₂ : m + 2 + k = m + k + 2 := by simp [add_comm, add_assoc],
simpa [h_nat₁, h_nat₂] using this },
-- clean up the `T` nat indices in the inductive hypothesis applied to `m + 1` and
-- `k + 1`
have H₁ : 2 * T R (m + 1) * T R (m + k + 2) = T R (2 * m + k + 3) + T R (k + 1),
{ have h_nat₁ : m + 1 + (k + 1) = m + k + 2 := by ring,
have h_nat₂ : 2 * (m + 1) + (k + 1) = 2 * m + k + 3 := by ring,
simpa [h_nat₁, h_nat₂] using mul_T (m + 1) (k + 1) },
-- clean up the `T` nat indices in the inductive hypothesis applied to `m` and `k + 2`
have H₂ : 2 * T R m * T R (m + k + 2) = T R (2 * m + k + 2) + T R (k + 2),
{ have h_nat₁ : 2 * m + (k + 2) = 2 * m + k + 2 := by simp [add_assoc],
have h_nat₂ : m + (k + 2) = m + k + 2 := by simp [add_assoc],
simpa [h_nat₁, h_nat₂] using mul_T m (k + 2) },
-- state the `T` recurrence relation for a few useful indices
have h₁ := T_add_two R m,
have h₂ := T_add_two R (2 * m + k + 2),
have h₃ := T_add_two R k,
-- the desired identity is an appropriate linear combination of H₁, H₂, h₁, h₂, h₃
-- it would be really nice here to have a linear algebra tactic!!
apply_fun (λ p, 2 * X * p) at H₁,
apply_fun (λ p, 2 * T R (m + k + 2) * p) at h₁,
have e₁ := congr (congr_arg has_add.add H₁) h₁,
have e₂ := congr (congr_arg has_sub.sub e₁) H₂,
have e₃ := congr (congr_arg has_sub.sub e₂) h₂,
have e₄ := congr (congr_arg has_sub.sub e₃) h₃,
rw ← sub_eq_zero at e₄ ⊢,
rw ← e₄,
ring,
end
/-- The `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th -/
lemma T_mul :
∀ m : ℕ, ∀ n : ℕ, T R (m * n) = (T R m).comp (T R n)
| 0 := by simp
| 1 := by simp
| (m + 2) := begin
intros n,
have : 2 * T R n * T R ((m + 1) * n) = T R ((m + 2) * n) + T R (m * n),
{ convert mul_T R n (m * n); ring },
simp [this, T_mul m, ← T_mul (m + 1)]
end
end polynomial.chebyshev
|
c36b246712972efc33732c3ffeb6fc0b2ad995f6 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Data/Json/Parser.lean | af895eef2d693ab14e6072523c66227222aaf7fe | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,691 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
namespace Lean
open Std (RBNode RBNode.singleton RBNode.leaf)
inductive Quickparse.Result (α : Type)
| success (pos : String.Iterator) (res : α) : Result α
| error (pos : String.Iterator) (err : String) : Result α
def Quickparse (α : Type) : Type := String.Iterator → Lean.Quickparse.Result α
instance (α : Type) : Inhabited (Quickparse α) :=
⟨fun it => Quickparse.Result.error it ""⟩
namespace Quickparse
open Result
partial def skipWs (it : String.Iterator) : String.Iterator :=
if it.hasNext then
let c := it.curr;
if c = '\u0009' ∨ c = '\u000a' ∨ c = '\u000d' ∨ c = '\u0020' then
skipWs it.next
else
it
else
it
@[inline]
protected def pure {α : Type} (a : α) : Quickparse α := fun it =>
success it a
@[inline]
protected def bind {α β : Type} (f : Quickparse α) (g : α → Quickparse β) : Quickparse β := fun it =>
match f it with
| success rem a => g a rem
| error pos msg => error pos msg
@[inline]
def fail {α : Type} (msg : String) : Quickparse α := fun it =>
error it msg
@[inline]
instance : Monad Quickparse :=
{ pure := @Quickparse.pure, bind := @Quickparse.bind }
def unexpectedEndOfInput := "unexpected end of input"
@[inline]
def peek? : Quickparse (Option Char) := fun it =>
if it.hasNext then
success it it.curr
else
success it none
@[inline]
def peek! : Quickparse Char := do
let some c ← peek? | fail unexpectedEndOfInput
pure c
@[inline]
def skip : Quickparse Unit := fun it =>
success it.next ()
@[inline]
def next : Quickparse Char := do
let c ← peek!
skip
pure c
def expect (s : String) : Quickparse Unit := fun it =>
if it.extract (it.forward s.length) = s then
success (it.forward s.length) ()
else
error it ("expected: " ++ s)
@[inline]
def ws : Quickparse Unit := fun it =>
success (skipWs it) ()
def expectedEndOfInput := "expected end of input"
@[inline]
def eoi : Quickparse Unit := fun it =>
if it.hasNext then
error it expectedEndOfInput
else
success it ()
end Quickparse
namespace Json.Parser
open Quickparse
@[inline]
def hexChar : Quickparse Nat := do
let c ← next
if '0' ≤ c ∧ c ≤ '9' then
pure $ c.val.toNat - '0'.val.toNat
else if 'a' ≤ c ∧ c ≤ 'f' then
pure $ c.val.toNat - 'a'.val.toNat
else if 'A' ≤ c ∧ c ≤ 'F' then
pure $ c.val.toNat - 'A'.val.toNat
else
fail "invalid hex character"
def escapedChar : Quickparse Char := do
let c ← next
match c with
| '\\' => pure '\\'
| '"' => pure '"'
| '/' => pure '/'
| 'b' => pure '\x08'
| 'f' => pure '\x0c'
| 'n' => pure '\n'
| 'r' => pure '\x0d'
| 't' => pure '\t'
| 'u' => do
let u1 ← hexChar; let u2 ← hexChar; let u3 ← hexChar; let u4 ← hexChar;
pure $ Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4
| _ => fail "illegal \\u escape"
partial def strCore (acc : String) : Quickparse String := do
let c ← peek!
if c = '"' then do -- "
skip;
pure acc
else do
let c ← next
let ec ←
if c = '\\' then
escapedChar
-- as to whether c.val > 0xffff should be split up and encoded with multiple \u,
-- the JSON standard is not definite: both directly printing the character
-- and encoding it with multiple \u is allowed. we choose the former.
else if 0x0020 ≤ c.val ∧ c.val ≤ 0x10ffff then
pure c
else
fail "unexpected character in string";
strCore (acc.push ec)
def str : Quickparse String := strCore ""
partial def natCore (acc digits : Nat) : Quickparse (Nat × Nat) := do
let some c ← peek? | pure (acc, digits);
if '0' ≤ c ∧ c ≤ '9' then do
skip;
let acc' := 10*acc + (c.val.toNat - '0'.val.toNat);
natCore acc' (digits+1)
else
pure (acc, digits)
@[inline]
def lookahead (p : Char → Prop) (desc : String) [DecidablePred p] : Quickparse Unit := do
let c ← peek!
if p c then
pure ()
else
fail $ "expected " ++ desc
@[inline]
def natNonZero : Quickparse Nat := do
lookahead (fun c => '1' ≤ c ∧ c ≤ '9') "1-9"
let (n, _) ← natCore 0 0
pure n
@[inline]
def natNumDigits : Quickparse (Nat × Nat) := do
lookahead (fun c => '0' ≤ c ∧ c ≤ '9') "digit"
natCore 0 0
@[inline]
def natMaybeZero : Quickparse Nat := do
let (n, _) ← natNumDigits
pure n
def num : Quickparse JsonNumber := do
let c ← peek!
let sign ←
if c = '-' then do
skip
pure (0 - 1 : Int)
else
pure 1
let c ← peek!
let res ←
if c = '0' then do
skip
pure 0
else
natNonZero
let res := JsonNumber.fromInt (sign * res)
let c? ← peek?
let res ←
if c? = some '.' then
skip
let (n, d) ← natNumDigits
if d > usizeSz then fail "too many decimals"
let mantissa' := res.mantissa * (10^d : Nat) + n
let exponent' := res.exponent + d
pure $ JsonNumber.mk mantissa' exponent'
else
pure res
let c? ← peek?
if c? = some 'e' ∨ c? = some 'E' then
skip
let c ← peek!
if c = '-' then
skip
let n ← natMaybeZero
pure (res.shiftr n)
else do
if c = '+' then skip
let n ← natMaybeZero
if n > usizeSz then fail "exp too large"
pure (res.shiftl n)
else
pure res
partial def arrayCore (anyCore : Unit → Quickparse Json) (acc : Array Json) : Quickparse (Array Json) := do
let hd ← anyCore ()
let acc' := acc.push hd
let c ← next
if c = ']' then
ws
pure acc'
else if c = ',' then
ws
arrayCore anyCore acc'
else
fail "unexpected character in array"
partial def objectCore (anyCore : Unit → Quickparse Json) : Quickparse (RBNode String (fun _ => Json)) := do
lookahead (fun c => c = '"') "\""; skip; -- "
let k ← strCore ""; ws
lookahead (fun c => c = ':') ":"; skip; ws
let v ← anyCore ()
let c ← next
if c = '}' then do
ws
pure (RBNode.singleton k v)
else if c = ',' then do
ws
let kvs ← objectCore anyCore
pure (kvs.insert strLt k v)
else
fail "unexpected character in object"
-- takes a unit parameter so that
-- we can use the equation compiler and recursion
partial def anyCore (u : Unit) : Quickparse Json := do
let c ← peek!
if c = '[' then
skip; ws
let c ← peek!
if c = ']' then
skip; ws
pure (Json.arr (Array.mkEmpty 0))
else
let a ← arrayCore anyCore (Array.mkEmpty 4)
pure (Json.arr a)
else if c = '{' then
skip; ws
let c ← peek!
if c = '}' then
skip; ws
pure (Json.obj (RBNode.leaf))
else
let kvs ← objectCore anyCore
pure (Json.obj kvs)
else if c = '\"' then
skip
let s ← strCore ""
ws
pure (Json.str s)
else if c = 'f' then
expect "false"; ws
pure (Json.bool false)
else if c = 't' then
expect "true"; ws
pure (Json.bool true)
else if c = 'n' then
expect "null"; ws
pure Json.null
else if c = '-' ∨ ('0' ≤ c ∧ c ≤ '9') then
let n ← num;
ws
pure (Json.num n)
else
fail "unexpected input"
def any : Quickparse Json := do
ws
let res ← anyCore ()
eoi
pure res
end Json.Parser
namespace Json
def parse (s : String) : Except String Lean.Json :=
match Json.Parser.any s.mkIterator with
| Quickparse.Result.success _ res => Except.ok res
| Quickparse.Result.error it err => Except.error ("offset " ++ it.i.repr ++ ": " ++ err)
end Json
end Lean
|
6e958f5b4631a01a4d0b90af681c2ab2bbda8f29 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/congr_lemma_bug.lean | 155a135fd5e15c9de9fb0ead908013bff19a0563 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 114 | lean | constant P : Type₁
constant P_sub : subsingleton P
attribute P_sub [instance]
constant q : P → Prop
#congr q
|
42c68edd918b9a988e9e29f20a26c14360498038 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/model_theory/elementary_maps.lean | ada6f2c3ce971ad64aca1ff58f934715df423f7b | [
"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 | 14,834 | 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 data.fintype.basic
import model_theory.substructures
/-!
# Elementary Maps Between First-Order Structures
## Main Definitions
* A `first_order.language.elementary_embedding` is an embedding that commutes with the
realizations of formulas.
* A `first_order.language.elementary_substructure` is a substructure where the realization of each
formula agrees with the realization in the larger model.
* The `first_order.language.elementary_diagram` of a structure is the set of all sentences with
parameters that the structure satisfies.
* `first_order.language.elementary_embedding.of_models_elementary_diagram` is the canonical
elementary embedding of any structure into a model of its elementary diagram.
## Main Results
* The Tarski-Vaught Test for embeddings: `first_order.language.embedding.is_elementary_of_exists`
gives a simple criterion for an embedding to be elementary.
* The Tarski-Vaught Test for substructures: `first_order.language.embedding.is_elementary_of_exists`
gives a simple criterion for a substructure to be elementary.
-/
open_locale first_order
namespace first_order
namespace language
open Structure
variables (L : language) (M : Type*) (N : Type*) {P : Type*} {Q : Type*}
variables [L.Structure M] [L.Structure N] [L.Structure P] [L.Structure Q]
/-- An elementary embedding of first-order structures is an embedding that commutes with the
realizations of formulas. -/
structure elementary_embedding :=
(to_fun : M → N)
(map_formula' : ∀ {{n}} (φ : L.formula (fin n)) (x : fin n → M),
φ.realize (to_fun ∘ x) ↔ φ.realize x . obviously)
localized "notation (name := elementary_embedding)
A ` ↪ₑ[`:25 L `] ` B := first_order.language.elementary_embedding L A B" in first_order
variables {L} {M} {N}
namespace elementary_embedding
instance fun_like : fun_like (M ↪ₑ[L] N) M (λ _, N) :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x end }
instance : has_coe_to_fun (M ↪ₑ[L] N) (λ _, M → N) := fun_like.has_coe_to_fun
@[simp] lemma map_bounded_formula (f : M ↪ₑ[L] N) {α : Type} {n : ℕ}
(φ : L.bounded_formula α n) (v : α → M) (xs : fin n → M) :
φ.realize (f ∘ v) (f ∘ xs) ↔ φ.realize v xs :=
begin
classical,
rw [← bounded_formula.realize_restrict_free_var set.subset.rfl, set.inclusion_eq_id, iff_eq_eq],
swap, { apply_instance },
have h := f.map_formula' ((φ.restrict_free_var id).to_formula.relabel (fintype.equiv_fin _))
((sum.elim (v ∘ coe) xs) ∘ (fintype.equiv_fin _).symm),
simp only [formula.realize_relabel, bounded_formula.realize_to_formula, iff_eq_eq] at h,
rw [← function.comp.assoc _ _ ((fintype.equiv_fin _).symm),
function.comp.assoc _ ((fintype.equiv_fin _).symm) (fintype.equiv_fin _),
equiv.symm_comp_self, function.comp.right_id, function.comp.assoc, sum.elim_comp_inl,
function.comp.assoc _ _ sum.inr, sum.elim_comp_inr,
← function.comp.assoc] at h,
refine h.trans _,
rw [function.comp.assoc _ _ (fintype.equiv_fin _), equiv.symm_comp_self,
function.comp.right_id, sum.elim_comp_inl, sum.elim_comp_inr, ← set.inclusion_eq_id,
bounded_formula.realize_restrict_free_var set.subset.rfl],
end
@[simp] lemma map_formula (f : M ↪ₑ[L] N) {α : Type} (φ : L.formula α) (x : α → M) :
φ.realize (f ∘ x) ↔ φ.realize x :=
by rw [formula.realize, formula.realize, ← f.map_bounded_formula, unique.eq_default (f ∘ default)]
lemma map_sentence (f : M ↪ₑ[L] N) (φ : L.sentence) :
M ⊨ φ ↔ N ⊨ φ :=
by rw [sentence.realize, sentence.realize, ← f.map_formula, unique.eq_default (f ∘ default)]
lemma Theory_model_iff (f : M ↪ₑ[L] N) (T : L.Theory) :
M ⊨ T ↔ N ⊨ T :=
by simp only [Theory.model_iff, f.map_sentence]
lemma elementarily_equivalent (f : M ↪ₑ[L] N) : M ≅[L] N :=
elementarily_equivalent_iff.2 f.map_sentence
@[simp] lemma injective (φ : M ↪ₑ[L] N) :
function.injective φ :=
begin
intros x y,
have h := φ.map_formula ((var 0).equal (var 1) : L.formula (fin 2)) (λ i, if i = 0 then x else y),
rw [formula.realize_equal, formula.realize_equal] at h,
simp only [nat.one_ne_zero, term.realize, fin.one_eq_zero_iff, if_true, eq_self_iff_true,
function.comp_app, if_false] at h,
exact h.1,
end
instance embedding_like : embedding_like (M ↪ₑ[L] N) M N :=
{ injective' := injective }
@[simp] lemma map_fun (φ : M ↪ₑ[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
begin
have h := φ.map_formula (formula.graph f) (fin.cons (fun_map f x) x),
rw [formula.realize_graph, fin.comp_cons, formula.realize_graph] at h,
rw [eq_comm, h]
end
@[simp] lemma map_rel (φ : M ↪ₑ[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (φ ∘ x) ↔ rel_map r x :=
begin
have h := φ.map_formula (r.formula var) x,
exact h
end
instance strong_hom_class : strong_hom_class L (M ↪ₑ[L] N) M N :=
{ map_fun := map_fun,
map_rel := map_rel }
@[simp] lemma map_constants (φ : M ↪ₑ[L] N) (c : L.constants) : φ c = c :=
hom_class.map_constants φ c
/-- An elementary embedding is also a first-order embedding. -/
def to_embedding (f : M ↪ₑ[L] N) : M ↪[L] N :=
{ to_fun := f,
inj' := f.injective, }
/-- An elementary embedding is also a first-order homomorphism. -/
def to_hom (f : M ↪ₑ[L] N) : M →[L] N :=
{ to_fun := f }
@[simp] lemma to_embedding_to_hom (f : M ↪ₑ[L] N) : f.to_embedding.to_hom = f.to_hom := rfl
@[simp]
lemma coe_to_hom {f : M ↪ₑ[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl
@[simp] lemma coe_to_embedding (f : M ↪ₑ[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl
lemma coe_injective : @function.injective (M ↪ₑ[L] N) (M → N) coe_fn :=
fun_like.coe_injective
@[ext]
lemma ext ⦃f g : M ↪ₑ[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
fun_like.ext f g h
lemma ext_iff {f g : M ↪ₑ[L] N} : f = g ↔ ∀ x, f x = g x :=
fun_like.ext_iff
variables (L) (M)
/-- The identity elementary embedding from a structure to itself -/
@[refl] def refl : M ↪ₑ[L] M :=
{ to_fun := id }
variables {L} {M}
instance : inhabited (M ↪ₑ[L] M) := ⟨refl L M⟩
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of elementary embeddings -/
@[trans] def comp (hnp : N ↪ₑ[L] P) (hmn : M ↪ₑ[L] N) : M ↪ₑ[L] P :=
{ to_fun := hnp ∘ hmn }
@[simp] lemma comp_apply (g : N ↪ₑ[L] P) (f : M ↪ₑ[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of elementary embeddings is associative. -/
lemma comp_assoc (f : M ↪ₑ[L] N) (g : N ↪ₑ[L] P) (h : P ↪ₑ[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end elementary_embedding
variables (L) (M)
/-- The elementary diagram of an `L`-structure is the set of all sentences with parameters it
satisfies. -/
abbreviation elementary_diagram : L[[M]].Theory := L[[M]].complete_theory M
/-- The canonical elementary embedding of an `L`-structure into any model of its elementary diagram
-/
@[simps] def elementary_embedding.of_models_elementary_diagram
(N : Type*) [L.Structure N] [L[[M]].Structure N]
[(Lhom_with_constants L M).is_expansion_on N] [N ⊨ L.elementary_diagram M] :
M ↪ₑ[L] N :=
⟨(coe : L[[M]].constants → N) ∘ sum.inr, λ n φ x, begin
refine trans _ ((realize_iff_of_model_complete_theory M N (((L.Lhom_with_constants
M).on_bounded_formula φ).subst (constants.term ∘ sum.inr ∘ x)).alls).trans _),
{ simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst,
Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff, realize_constants] },
{ simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst,
Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff],
refl }
end⟩
variables {L M}
namespace embedding
/-- The Tarski-Vaught test for elementarity of an embedding. -/
theorem is_elementary_of_exists (f : M ↪[L] N)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N),
φ.realize default (fin.snoc (f ∘ x) a : _ → N) →
∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) :
∀{n} (φ : L.formula (fin n)) (x : fin n → M), φ.realize (f ∘ x) ↔ φ.realize x :=
begin
suffices h : ∀ (n : ℕ) (φ : L.bounded_formula empty n) (xs : fin n → M),
φ.realize (f ∘ default) (f ∘ xs) ↔ φ.realize default xs,
{ intros n φ x,
refine φ.realize_relabel_sum_inr.symm.trans (trans (h n _ _) φ.realize_relabel_sum_inr), },
refine λ n φ, φ.rec_on _ _ _ _ _,
{ exact λ _ _, iff.rfl },
{ intros,
simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] },
{ intros,
simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] },
{ intros _ _ _ ih1 ih2 _,
simp [ih1, ih2] },
{ intros n φ ih xs,
simp only [bounded_formula.realize_all],
refine ⟨λ h a, _, _⟩,
{ rw [← ih, fin.comp_snoc],
exact h (f a) },
{ contrapose!,
rintro ⟨a, ha⟩,
obtain ⟨b, hb⟩ := htv n φ.not xs a _,
{ refine ⟨b, λ h, hb (eq.mp _ ((ih _).2 h))⟩,
rw [unique.eq_default (f ∘ default), fin.comp_snoc], },
{ rw [bounded_formula.realize_not, ← unique.eq_default (f ∘ default)],
exact ha } } },
end
/-- Bundles an embedding satisfying the Tarski-Vaught test as an elementary embedding. -/
@[simps] def to_elementary_embedding (f : M ↪[L] N)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N),
φ.realize default (fin.snoc (f ∘ x) a : _ → N) →
∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) :
M ↪ₑ[L] N :=
⟨f, λ _, f.is_elementary_of_exists htv⟩
end embedding
namespace equiv
/-- A first-order equivalence is also an elementary embedding. -/
def to_elementary_embedding (f : M ≃[L] N) : M ↪ₑ[L] N :=
{ to_fun := f }
@[simp] lemma to_elementary_embedding_to_embedding (f : M ≃[L] N) :
f.to_elementary_embedding.to_embedding = f.to_embedding := rfl
@[simp] lemma coe_to_elementary_embedding (f : M ≃[L] N) :
(f.to_elementary_embedding : M → N) = (f : M → N) := rfl
end equiv
@[simp] lemma realize_term_substructure {α : Type*} {S : L.substructure M} (v : α → S)
(t : L.term α) :
t.realize (coe ∘ v) = (↑(t.realize v) : M) :=
S.subtype.realize_term t
namespace substructure
@[simp] lemma realize_bounded_formula_top {α : Type*} {n : ℕ} {φ : L.bounded_formula α n}
{v : α → (⊤ : L.substructure M)} {xs : fin n → (⊤ : L.substructure M)} :
φ.realize v xs ↔ φ.realize ((coe : _ → M) ∘ v) (coe ∘ xs) :=
begin
rw ← substructure.top_equiv.realize_bounded_formula φ,
simp,
end
@[simp] lemma realize_formula_top {α : Type*} {φ : L.formula α} {v : α → (⊤ : L.substructure M)} :
φ.realize v ↔ φ.realize ((coe : (⊤ : L.substructure M) → M) ∘ v) :=
begin
rw ← substructure.top_equiv.realize_formula φ,
simp,
end
/-- A substructure is elementary when every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
def is_elementary (S : L.substructure M) : Prop :=
∀ {{n}} (φ : L.formula (fin n)) (x : fin n → S), φ.realize ((coe : _ → M) ∘ x) ↔ φ.realize x
end substructure
variables (L M)
/-- An elementary substructure is one in which every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
structure elementary_substructure :=
(to_substructure : L.substructure M)
(is_elementary' : to_substructure.is_elementary)
variables {L M}
namespace elementary_substructure
instance : has_coe (L.elementary_substructure M) (L.substructure M) :=
⟨elementary_substructure.to_substructure⟩
instance : set_like (L.elementary_substructure M) M :=
⟨λ x, x.to_substructure.carrier, λ ⟨⟨s, hs1⟩, hs2⟩ ⟨⟨t, ht1⟩, ht2⟩ h, begin
congr,
exact h,
end⟩
instance induced_Structure (S : L.elementary_substructure M) : L.Structure S :=
substructure.induced_Structure
@[simp] lemma is_elementary (S : L.elementary_substructure M) :
(S : L.substructure M).is_elementary := S.is_elementary'
/-- The natural embedding of an `L.substructure` of `M` into `M`. -/
def subtype (S : L.elementary_substructure M) : S ↪ₑ[L] M :=
{ to_fun := coe,
map_formula' := S.is_elementary }
@[simp] theorem coe_subtype {S : L.elementary_substructure M} : ⇑S.subtype = coe := rfl
/-- The substructure `M` of the structure `M` is elementary. -/
instance : has_top (L.elementary_substructure M) :=
⟨⟨⊤, λ n φ x, substructure.realize_formula_top.symm⟩⟩
instance : inhabited (L.elementary_substructure M) := ⟨⊤⟩
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : L.elementary_substructure M) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : L.elementary_substructure M) : set M) = set.univ := rfl
@[simp] lemma realize_sentence (S : L.elementary_substructure M) (φ : L.sentence) :
S ⊨ φ ↔ M ⊨ φ :=
S.subtype.map_sentence φ
@[simp] lemma Theory_model_iff (S : L.elementary_substructure M) (T : L.Theory) :
S ⊨ T ↔ M ⊨ T :=
by simp only [Theory.model_iff, realize_sentence]
instance Theory_model {T : L.Theory} [h : M ⊨ T] {S : L.elementary_substructure M} : S ⊨ T :=
(Theory_model_iff S T).2 h
instance [h : nonempty M] {S : L.elementary_substructure M} : nonempty S :=
(model_nonempty_theory_iff L).1 infer_instance
lemma elementarily_equivalent (S : L.elementary_substructure M) : S ≅[L] M :=
S.subtype.elementarily_equivalent
end elementary_substructure
namespace substructure
/-- The Tarski-Vaught test for elementarity of a substructure. -/
theorem is_elementary_of_exists (S : L.substructure M)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M),
φ.realize default (fin.snoc (coe ∘ x) a : _ → M) →
∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) :
S.is_elementary :=
λ n, S.subtype.is_elementary_of_exists htv
/-- Bundles a substructure satisfying the Tarski-Vaught test as an elementary substructure. -/
@[simps] def to_elementary_substructure (S : L.substructure M)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M),
φ.realize default (fin.snoc (coe ∘ x) a : _ → M) →
∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) :
L.elementary_substructure M :=
⟨S, S.is_elementary_of_exists htv⟩
end substructure
end language
end first_order
|
37e10811c5ee070b62b787ad59b5af90f6a90a16 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/tactic/core.lean | 19090ef48c81ecec419f5f34536d7bc5b99e8792 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 89,694 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import logic.function.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.binder_matching
import tactic.lean_core_docs
import tactic.interactive_expr
import system.io
universe variable u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e ← kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
/-- Format a list as a comma separated list, without any brackets. -/
meta def comma_separated {α : Type*} [has_to_format α] : list α → format
| [] := nil
| xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt)
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format :=
bracket "[" "]" (comma_separated l)
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of `type`. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of `fn`'s type. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/--
Auxiliary function for `get_app_fn_args_whnf`.
-/
private meta def get_app_fn_args_whnf_aux (md : transparency)
(unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) :=
λ args e, do
(expr.app t u) ← whnf e md unfold_ginductive | pure (e, args),
get_app_fn_args_whnf_aux (u :: args) t
/--
For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e`
is normalised as necessary; for example:
```
get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])
```
-/
meta def get_app_fn_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (expr × list expr) :=
get_app_fn_args_whnf_aux md unfold_ginductive [] e
/--
`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is
normalised as necessary (with transparency `md`). `unfold_ginductive` controls
whether constructors of generalised inductive types are unfolded.
-/
meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr
| e md unfold_ginductive := do
(expr.app f _) ← whnf e md unfold_ginductive | pure e,
get_app_fn_whnf f md
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- `get_decls_from` returns a dictionary mapping names to their
corresponding declarations. Covers all declarations the files listed
in `fs`, with the current file listed as `none`.
The path of the file names is expected to be relative to
the root of the project (i.e. the location of `leanpkg.toml` when it
is present); e.g. `"src/tactic/core.lean"`
Possible issue: `get_decls_from` uses `get_cwd`, the current working
directory, which may not always point at the root of the project.
It would work better if it searched for the root directory or,
better yet, if Lean exposed its path information.
-/
meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=
do root ← unsafe_run_io $ io.env.get_cwd,
let fs := fs.map (option.map $ λ path, root ++ "/" ++ path),
err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists,
guard (err = []) <|> fail format!"File not found: {err}",
e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s,
let source := e.decl_olean d.to_name in
if source ∈ fs ∧ (source = none → e.in_current_file d.to_name)
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Runs a tactic for a result, reverting the state after completion or error. -/
meta def retrieve' {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
(λ msg pos s', result.exception msg pos s)
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).
Returns the number of local constants that have been reverted. -/
meta def revert_target_deps : tactic ℕ :=
do tgt ← target,
ctx ← local_context,
l ← ctx.mfilter (kdepends_on tgt),
n ← revert_lst l,
if l = [] then return n
else do m ← revert_target_deps, return (m + n)
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro n) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : ℕ → tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ ← target,
intro pp_n,
intron_no_renames n
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`
(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.
whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes
them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition
running up to the first match. -/
private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α)
| [] acc := [acc.reverse]
| (l :: ls) acc :=
if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l]
else partition_local_deps_aux ls (l :: acc)
/-- `partition_local_deps vs`, with `vs` a list of local constants,
reorders `vs` in the order they appear in the local context together
with the variables that follow them. If local context is `[a,b,c,d,e,f]`,
and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.
The head of each list is one of the variables given as a parameter. -/
meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=
do ls ← local_context,
pure (partition_local_deps_aux vs ls []).tail.reverse
/-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular
hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not
matter as a permutation will be chosen so as to preserve type correctness.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (vs : list expr) : tactic unit := do
ls ← partition_local_deps vs,
ls.mmap' $ λ vs, do
{ revert_lst vs,
(expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.",
let e := expr.pi v binder_info.default t b,
type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.",
g ← mk_meta_var e,
h ← note `h none g,
tactic.exact $ h d,
gs ← get_goals,
set_goals $ g :: gs },
ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
c ← match env.constructors_of struct_n with
| [c] := pure c
| [] :=
if env.is_inductive struct_n
then fail format!"{struct_n} does not have constructors"
else fail format!"{struct_n} is not an inductive type"
| _ := fail "too many constructors"
end,
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`.
`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond → tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`.
The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since
it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do
f ← mk_meta_var cond,
e ← assertv `c cond f, swap,
reset_instance_cache,
inst ← mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Constructs a list of `tactic expr` given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.
We need to return a list of `tactic expr`, rather than just `expr`, because these expressions
will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
-/
meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr))
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n),
-- We reverse the list of lemmas marked with an attribute,
-- on the assumption that lemmas proved earlier are more often applicable
-- than lemmas proved later. This is a performance optimization.
build_list_expr_for_apply (m.reverse ++ t))
<|> return ((i_to_expr_for_apply h) :: tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=
do l ← lock_tactic_state $ build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr → tactic unit := (λ _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
when (repl_tp ≠ tp) $ change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/--
`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,
and fail otherwise.
-/
meta def sorry_if_contains_sorry : tactic unit :=
do
g ← target,
guard g.contains_sorry <|> fail "goal does not contain `sorrry`",
tactic.admit
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
old::other_goals ← get_goals,
t ← infer_type old,
new_goal ← mk_meta_var (t.pis lc),
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- Protect the declaration `n` -/
meta def mk_protected (n : name) : tactic unit :=
do env ← get_env, set_env (env.mk_protected n)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr
},
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings)
}
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= open_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← open_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← open_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Copies a definition into the `tactic.interactive` namespace to make it usable
in proof scripts. It allows one to write
```lean
@[interactive]
meta def my_tactic := ...
```
instead of
```lean
meta def my_tactic := ...
run_cmd add_interactive [``my_tactic]
```
-/
@[user_attribute]
meta def interactive_attr : user_attribute :=
{ name := `interactive,
descr :=
"Put a definition in the `tactic.interactive` namespace to make it usable
in proof scripts.",
after_set := some $ λ tac _ _, add_interactive [tac] }
add_tactic_doc
{ name := "interactive",
category := doc_category.attr,
decl_names := [``tactic.interactive_attr],
tags := ["environment"] }
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/
meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s'
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/--
Construct a `refine ...` or `exact ...` string which would construct `g`.
-/
meta def tactic_statement (g : expr) : tactic string :=
do g ← instantiate_mvars g,
g ← head_beta g,
r ← pp (replace_mvars g),
if g.has_meta_var
then return (sformat!"Try this: refine {r}")
else return (sformat!"Try this: exact {r}")
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `trace`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
/--
Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns
the name of the declaration that defines this attribute.
Fails if there is no user attribute with this name.
Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/
meta def get_user_attribute_name (attr_name : name) : tactic name := do
ns ← attribute.get_instances `user_attribute,
ns.mfirst (λ nm, do
d ← get_decl nm,
e ← mk_app `user_attribute.name [d.value],
attr_nm ← eval_expr name e,
guard $ attr_nm = attr_name,
return nm) <|> fail!"'{attr_name}' is not a user attribute."
/-- A tactic to set either a basic attribute or a user attribute, as long as the user attribute has
no parameter.
If a user attribute with a parameter (that is not `unit`) is set, this function will raise an
error. -/
-- possible enhancement if needed: use default value for a user attribute with parameter.
meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)
(prio : option nat := none) : tactic unit := do
get_decl c_name <|> fail!"unknown declaration {c_name}",
s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio),
sum.inr msg ← return s | skip,
if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string
then do
user_attr_nm ← get_user_attribute_name attr_name,
user_attr_const ← mk_const user_attr_nm,
tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name () %%persistent) <|>
fail!"Cannot set attribute @[{attr_name}]. The corresponding user attribute {user_attr_nm} has a parameter.",
tac
else fail msg
end tactic
/--
`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) :
tactic (expr × v) :=
m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
|
b4dc3c9cf87b7bdd4380cf40801bb5b919838ae6 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/ring/boolean_ring.lean | c5ab68f32355c1f4f8a80eb396ce2cc5156c63d4 | [
"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 | 15,985 | lean | /-
Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen, Yaël Dillies
-/
import algebra.punit_instances
import order.hom.lattice
import tactic.abel
import tactic.ring
/-!
# Boolean rings
A Boolean ring is a ring where multiplication is idempotent. They are equivalent to Boolean
algebras.
## Main declarations
* `boolean_ring`: a typeclass for rings where multiplication is idempotent.
* `boolean_ring.to_boolean_algebra`: Turn a Boolean ring into a Boolean algebra.
* `boolean_algebra.to_boolean_ring`: Turn a Boolean algebra into a Boolean ring.
* `as_boolalg`: Type-synonym for the Boolean algebra associated to a Boolean ring.
* `as_boolring`: Type-synonym for the Boolean ring associated to a Boolean algebra.
## Implementation notes
We provide two ways of turning a Boolean algebra/ring into a Boolean ring/algebra:
* Instances on the same type accessible in locales `boolean_algebra_of_boolean_ring` and
`boolean_ring_of_boolean_algebra`.
* Type-synonyms `as_boolalg` and `as_boolring`.
At this point in time, it is not clear the first way is useful, but we keep it for educational
purposes and because it is easier than dealing with
`of_boolalg`/`to_boolalg`/`of_boolring`/`to_boolring` explicitly.
## Tags
boolean ring, boolean algebra
-/
variables {α β γ : Type*}
/-- A Boolean ring is a ring where multiplication is idempotent. -/
class boolean_ring α extends ring α :=
(mul_self : ∀ a : α, a * a = a)
section boolean_ring
variables [boolean_ring α] (a b : α)
instance : is_idempotent α (*) := ⟨boolean_ring.mul_self⟩
@[simp] lemma mul_self : a * a = a := boolean_ring.mul_self _
@[simp] lemma add_self : a + a = 0 :=
have a + a = a + a + (a + a) :=
calc a + a = (a+a) * (a+a) : by rw mul_self
... = a*a + a*a + (a*a + a*a) : by rw [add_mul, mul_add]
... = a + a + (a + a) : by rw mul_self,
by rwa self_eq_add_left at this
@[simp] lemma neg_eq : -a = a :=
calc -a = -a + 0 : by rw add_zero
... = -a + -a + a : by rw [←neg_add_self, add_assoc]
... = a : by rw [add_self, zero_add]
lemma add_eq_zero : a + b = 0 ↔ a = b :=
calc a + b = 0 ↔ a = -b : add_eq_zero_iff_eq_neg
... ↔ a = b : by rw neg_eq
@[simp] lemma mul_add_mul : a*b + b*a = 0 :=
have a + b = a + b + (a*b + b*a) :=
calc a + b = (a + b) * (a + b) : by rw mul_self
... = a*a + a*b + (b*a + b*b) : by rw [add_mul, mul_add, mul_add]
... = a + a*b + (b*a + b) : by simp only [mul_self]
... = a + b + (a*b + b*a) : by abel,
by rwa self_eq_add_right at this
@[simp] lemma sub_eq_add : a - b = a + b :=
by rw [sub_eq_add_neg, add_right_inj, neg_eq]
@[simp] lemma mul_one_add_self : a * (1 + a) = 0 := by rw [mul_add, mul_one, mul_self, add_self]
@[priority 100] -- Note [lower instance priority]
instance boolean_ring.to_comm_ring : comm_ring α :=
{ mul_comm := λ a b, by rw [←add_eq_zero, mul_add_mul],
.. (infer_instance : boolean_ring α) }
end boolean_ring
instance : boolean_ring punit := ⟨λ _, subsingleton.elim _ _⟩
/-! ### Turning a Boolean ring into a Boolean algebra -/
section ring_to_algebra
/-- Type synonym to view a Boolean ring as a Boolean algebra. -/
def as_boolalg (α : Type*) := α
/-- The "identity" equivalence between `as_boolalg α` and `α`. -/
def to_boolalg : α ≃ as_boolalg α := equiv.refl _
/-- The "identity" equivalence between `α` and `as_boolalg α`. -/
def of_boolalg : as_boolalg α ≃ α := equiv.refl _
@[simp] lemma to_boolalg_symm_eq : (@to_boolalg α).symm = of_boolalg := rfl
@[simp] lemma of_boolalg_symm_eq : (@of_boolalg α).symm = to_boolalg := rfl
@[simp] lemma to_boolalg_of_boolalg (a : as_boolalg α) : to_boolalg (of_boolalg a) = a := rfl
@[simp] lemma of_boolalg_to_boolalg (a : α) : of_boolalg (to_boolalg a) = a := rfl
@[simp] lemma to_boolalg_inj {a b : α} : to_boolalg a = to_boolalg b ↔ a = b := iff.rfl
@[simp] lemma of_boolalg_inj {a b : as_boolalg α} : of_boolalg a = of_boolalg b ↔ a = b := iff.rfl
instance [inhabited α] : inhabited (as_boolalg α) := ‹inhabited α›
variables [boolean_ring α] [boolean_ring β] [boolean_ring γ]
namespace boolean_ring
/-- The join operation in a Boolean ring is `x + y + x * y`. -/
def has_sup : has_sup α := ⟨λ x y, x + y + x * y⟩
/-- The meet operation in a Boolean ring is `x * y`. -/
def has_inf : has_inf α := ⟨(*)⟩
-- Note [lower instance priority]
localized "attribute [instance, priority 100] boolean_ring.has_sup" in
boolean_algebra_of_boolean_ring
localized "attribute [instance, priority 100] boolean_ring.has_inf" in
boolean_algebra_of_boolean_ring
lemma sup_comm (a b : α) : a ⊔ b = b ⊔ a := by { dsimp only [(⊔)], ring }
lemma inf_comm (a b : α) : a ⊓ b = b ⊓ a := by { dsimp only [(⊓)], ring }
lemma sup_assoc (a b c : α) : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by { dsimp only [(⊔)], ring }
lemma inf_assoc (a b c : α) : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by { dsimp only [(⊓)], ring }
lemma sup_inf_self (a b : α) : a ⊔ a ⊓ b = a :=
by { dsimp only [(⊔), (⊓)], assoc_rw [mul_self, add_self, add_zero] }
lemma inf_sup_self (a b : α) : a ⊓ (a ⊔ b) = a :=
begin
dsimp only [(⊔), (⊓)],
rw [mul_add, mul_add, mul_self, ←mul_assoc, mul_self, add_assoc, add_self, add_zero]
end
lemma le_sup_inf_aux (a b c : α) : (a + b + a * b) * (a + c + a * c) = a + b * c + a * (b * c) :=
calc (a + b + a * b) * (a + c + a * c) =
a * a + b * c + a * (b * c) +
(a * b + (a * a) * b) +
(a * c + (a * a) * c) +
(a * b * c + (a * a) * b * c) : by ring
... = a + b * c + a * (b * c) : by simp only [mul_self, add_self, add_zero]
lemma le_sup_inf (a b c : α) : (a ⊔ b) ⊓ (a ⊔ c) ⊔ (a ⊔ b ⊓ c) = a ⊔ b ⊓ c :=
by { dsimp only [(⊔), (⊓)], rw [le_sup_inf_aux, add_self, mul_self, zero_add] }
/--
The Boolean algebra structure on a Boolean ring.
The data is defined so that:
* `a ⊔ b` unfolds to `a + b + a * b`
* `a ⊓ b` unfolds to `a * b`
* `a ≤ b` unfolds to `a + b + a * b = b`
* `⊥` unfolds to `0`
* `⊤` unfolds to `1`
* `aᶜ` unfolds to `1 + a`
* `a \ b` unfolds to `a * (1 + b)`
-/
def to_boolean_algebra : boolean_algebra α :=
boolean_algebra.of_core
{ le_sup_inf := le_sup_inf,
top := 1,
le_top := λ a, show a + 1 + a * 1 = 1, by assoc_rw [mul_one, add_comm, add_self, add_zero],
bot := 0,
bot_le := λ a, show 0 + a + 0 * a = a, by rw [zero_mul, zero_add, add_zero],
compl := λ a, 1 + a,
inf_compl_le_bot := λ a,
show a*(1+a) + 0 + a*(1+a)*0 = 0,
by norm_num [mul_add, mul_self, add_self],
top_le_sup_compl := λ a,
begin
change 1 + (a + (1+a) + a*(1+a)) + 1*(a + (1+a) + a*(1+a)) = a + (1+a) + a*(1+a),
norm_num [mul_add, mul_self],
rw [←add_assoc, add_self],
end,
.. lattice.mk' sup_comm sup_assoc inf_comm inf_assoc sup_inf_self inf_sup_self }
localized "attribute [instance, priority 100] boolean_ring.to_boolean_algebra" in
boolean_algebra_of_boolean_ring
end boolean_ring
instance : boolean_algebra (as_boolalg α) := @boolean_ring.to_boolean_algebra α _
@[simp] lemma of_boolalg_top : of_boolalg (⊤ : as_boolalg α) = 1 := rfl
@[simp] lemma of_boolalg_bot : of_boolalg (⊥ : as_boolalg α) = 0 := rfl
@[simp] lemma of_boolalg_sup (a b : as_boolalg α) :
of_boolalg (a ⊔ b) = of_boolalg a + of_boolalg b + of_boolalg a * of_boolalg b := rfl
@[simp] lemma of_boolalg_inf (a b : as_boolalg α) :
of_boolalg (a ⊓ b) = of_boolalg a * of_boolalg b := rfl
@[simp] lemma of_boolalg_compl (a : as_boolalg α) : of_boolalg aᶜ = 1 + of_boolalg a := rfl
@[simp] lemma of_boolalg_sdiff (a b : as_boolalg α) :
of_boolalg (a \ b) = of_boolalg a * (1 + of_boolalg b) := rfl
private lemma of_boolalg_symm_diff_aux (a b : α) : (a + b + a * b) * (1 + a * b) = a + b :=
calc (a + b + a * b) * (1 + a * b)
= a + b + (a * b + (a * b) * (a * b)) + (a * (b * b) + (a * a) * b) : by ring
... = a + b : by simp only [mul_self, add_self, add_zero]
@[simp] lemma of_boolalg_symm_diff (a b : as_boolalg α) :
of_boolalg (a ∆ b) = of_boolalg a + of_boolalg b :=
by { rw symm_diff_eq_sup_sdiff_inf, exact of_boolalg_symm_diff_aux _ _ }
@[simp] lemma of_boolalg_mul_of_boolalg_eq_left_iff {a b : as_boolalg α} :
of_boolalg a * of_boolalg b = of_boolalg a ↔ a ≤ b :=
@inf_eq_left (as_boolalg α) _ _ _
@[simp] lemma to_boolalg_zero : to_boolalg (0 : α) = ⊥ := rfl
@[simp] lemma to_boolalg_one : to_boolalg (1 : α) = ⊤ := rfl
@[simp] lemma to_boolalg_mul (a b : α) :
to_boolalg (a * b) = to_boolalg a ⊓ to_boolalg b := rfl
-- `to_boolalg_add` simplifies the LHS but this lemma is eligible to `dsimp`
@[simp, nolint simp_nf] lemma to_boolalg_add_add_mul (a b : α) :
to_boolalg (a + b + a * b) = to_boolalg a ⊔ to_boolalg b := rfl
@[simp] lemma to_boolalg_add (a b : α) : to_boolalg (a + b) = to_boolalg a ∆ to_boolalg b :=
(of_boolalg_symm_diff _ _).symm
/-- Turn a ring homomorphism from Boolean rings `α` to `β` into a bounded lattice homomorphism
from `α` to `β` considered as Boolean algebras. -/
@[simps] protected def ring_hom.as_boolalg (f : α →+* β) :
bounded_lattice_hom (as_boolalg α) (as_boolalg β) :=
{ to_fun := to_boolalg ∘ f ∘ of_boolalg,
map_sup' := λ a b, begin
dsimp,
simp_rw [map_add f, map_mul f],
refl,
end,
map_inf' := f.map_mul',
map_top' := f.map_one',
map_bot' := f.map_zero' }
@[simp] lemma ring_hom.as_boolalg_id : (ring_hom.id α).as_boolalg = bounded_lattice_hom.id _ := rfl
@[simp] lemma ring_hom.as_boolalg_comp (g : β →+* γ) (f : α →+* β) :
(g.comp f).as_boolalg = g.as_boolalg.comp f.as_boolalg := rfl
end ring_to_algebra
/-! ### Turning a Boolean algebra into a Boolean ring -/
section algebra_to_ring
/-- Type synonym to view a Boolean ring as a Boolean algebra. -/
def as_boolring (α : Type*) := α
/-- The "identity" equivalence between `as_boolring α` and `α`. -/
def to_boolring : α ≃ as_boolring α := equiv.refl _
/-- The "identity" equivalence between `α` and `as_boolring α`. -/
def of_boolring : as_boolring α ≃ α := equiv.refl _
@[simp] lemma to_boolring_symm_eq : (@to_boolring α).symm = of_boolring := rfl
@[simp] lemma of_boolring_symm_eq : (@of_boolring α).symm = to_boolring := rfl
@[simp] lemma to_boolring_of_boolring (a : as_boolring α) : to_boolring (of_boolring a) = a := rfl
@[simp] lemma of_boolring_to_boolring (a : α) : of_boolring (to_boolring a) = a := rfl
@[simp] lemma to_boolring_inj {a b : α} : to_boolring a = to_boolring b ↔ a = b := iff.rfl
@[simp] lemma of_boolring_inj {a b : as_boolring α} : of_boolring a = of_boolring b ↔ a = b :=
iff.rfl
instance [inhabited α] : inhabited (as_boolring α) := ‹inhabited α›
/-- Every generalized Boolean algebra has the structure of a non unital commutative ring with the
following data:
* `a + b` unfolds to `a ∆ b` (symmetric difference)
* `a * b` unfolds to `a ⊓ b`
* `-a` unfolds to `a`
* `0` unfolds to `⊥`
-/
@[reducible] -- See note [reducible non-instances]
def generalized_boolean_algebra.to_non_unital_comm_ring [generalized_boolean_algebra α] :
non_unital_comm_ring α :=
{ add := (∆),
add_assoc := symm_diff_assoc,
zero := ⊥,
zero_add := bot_symm_diff,
add_zero := symm_diff_bot,
zero_mul := λ _, bot_inf_eq,
mul_zero := λ _, inf_bot_eq,
neg := id,
add_left_neg := symm_diff_self,
add_comm := symm_diff_comm,
mul := (⊓),
mul_assoc := λ _ _ _, inf_assoc,
mul_comm := λ _ _, inf_comm,
left_distrib := inf_symm_diff_distrib_left,
right_distrib := inf_symm_diff_distrib_right }
instance [generalized_boolean_algebra α] : non_unital_comm_ring (as_boolring α) :=
@generalized_boolean_algebra.to_non_unital_comm_ring α _
variables [boolean_algebra α] [boolean_algebra β] [boolean_algebra γ]
/-- Every Boolean algebra has the structure of a Boolean ring with the following data:
* `a + b` unfolds to `a ∆ b` (symmetric difference)
* `a * b` unfolds to `a ⊓ b`
* `-a` unfolds to `a`
* `0` unfolds to `⊥`
* `1` unfolds to `⊤`
-/
@[reducible] -- See note [reducible non-instances]
def boolean_algebra.to_boolean_ring : boolean_ring α :=
{ one := ⊤,
one_mul := λ _, top_inf_eq,
mul_one := λ _, inf_top_eq,
mul_self := λ b, inf_idem,
..generalized_boolean_algebra.to_non_unital_comm_ring }
localized "attribute [instance, priority 100] generalized_boolean_algebra.to_non_unital_comm_ring
boolean_algebra.to_boolean_ring" in boolean_ring_of_boolean_algebra
instance : boolean_ring (as_boolring α) := @boolean_algebra.to_boolean_ring α _
@[simp] lemma of_boolring_zero : of_boolring (0 : as_boolring α) = ⊥ := rfl
@[simp] lemma of_boolring_one : of_boolring (1 : as_boolring α) = ⊤ := rfl
-- `sub_eq_add` proves this lemma but it is eligible for `dsimp`
@[simp, nolint simp_nf] lemma of_boolring_neg (a : as_boolring α) :
of_boolring (-a) = of_boolring a := rfl
@[simp] lemma of_boolring_add (a b : as_boolring α) :
of_boolring (a + b) = of_boolring a ∆ of_boolring b := rfl
-- `sub_eq_add` simplifies the LHS but this lemma is eligible for `dsimp`
@[simp, nolint simp_nf] lemma of_boolring_sub (a b : as_boolring α) :
of_boolring (a - b) = of_boolring a ∆ of_boolring b := rfl
@[simp] lemma of_boolring_mul (a b : as_boolring α) :
of_boolring (a * b) = of_boolring a ⊓ of_boolring b := rfl
@[simp] lemma of_boolring_le_of_boolring_iff {a b : as_boolring α} :
of_boolring a ≤ of_boolring b ↔ a * b = a := inf_eq_left.symm
@[simp] lemma to_boolring_bot : to_boolring (⊥ : α) = 0 := rfl
@[simp] lemma to_boolring_top : to_boolring (⊤ : α) = 1 := rfl
@[simp] lemma to_boolring_inf (a b : α) : to_boolring (a ⊓ b) = to_boolring a * to_boolring b := rfl
@[simp] lemma to_boolring_symm_diff (a b : α) :
to_boolring (a ∆ b) = to_boolring a + to_boolring b := rfl
/-- Turn a bounded lattice homomorphism from Boolean algebras `α` to `β` into a ring homomorphism
from `α` to `β` considered as Boolean rings. -/
@[simps] protected def bounded_lattice_hom.as_boolring (f : bounded_lattice_hom α β) :
as_boolring α →+* as_boolring β :=
{ to_fun := to_boolring ∘ f ∘ of_boolring,
map_zero' := f.map_bot',
map_one' := f.map_top',
map_add' := map_symm_diff f,
map_mul' := f.map_inf' }
@[simp] lemma bounded_lattice_hom.as_boolring_id :
(bounded_lattice_hom.id α).as_boolring = ring_hom.id _ := rfl
@[simp] lemma bounded_lattice_hom.as_boolring_comp (g : bounded_lattice_hom β γ)
(f : bounded_lattice_hom α β) :
(g.comp f).as_boolring = g.as_boolring.comp f.as_boolring := rfl
end algebra_to_ring
/-! ### Equivalence between Boolean rings and Boolean algebras -/
/-- Order isomorphism between `α` considered as a Boolean ring considered as a Boolean algebra and
`α`. -/
@[simps] def order_iso.as_boolalg_as_boolring (α : Type*) [boolean_algebra α] :
as_boolalg (as_boolring α) ≃o α :=
⟨of_boolalg.trans of_boolring, λ a b,
of_boolring_le_of_boolring_iff.trans of_boolalg_mul_of_boolalg_eq_left_iff⟩
/-- Ring isomorphism between `α` considered as a Boolean algebra considered as a Boolean ring and
`α`. -/
@[simps] def ring_equiv.as_boolring_as_boolalg (α : Type*) [boolean_ring α] :
as_boolring (as_boolalg α) ≃+* α :=
{ map_mul' := λ a b, rfl,
map_add' := of_boolalg_symm_diff,
..of_boolring.trans of_boolalg }
open bool
instance : boolean_ring bool :=
{ add := bxor,
add_assoc := bxor_assoc,
zero := ff,
zero_add := ff_bxor,
add_zero := bxor_ff,
neg := id,
sub := bxor,
sub_eq_add_neg := λ _ _, rfl,
add_left_neg := bxor_self,
add_comm := bxor_comm,
one := tt,
mul := band,
mul_assoc := band_assoc,
one_mul := tt_band,
mul_one := band_tt,
left_distrib := band_bxor_distrib_left,
right_distrib := band_bxor_distrib_right,
mul_self := band_self }
|
09a1e39bfedc279c5100975b28a1726dac4e9aa3 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/endomorphism.lean | 7c015e20481f3fac5f079cd9915d9d832d16f158 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,134 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
-/
import category_theory.groupoid
import data.equiv.mul_add
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [category_struct.{v} C] (X : C)
instance has_one : has_one (End X) := ⟨𝟙 X⟩
instance inhabited : inhabited (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
variables {C : Type u} [category.{v} C] (X : C)
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩
instance : group (Aut X) :=
by refine { one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans,
div_eq_mul_inv := λ _ _, rfl, .. } ;
simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one,
has_inv.inv]
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : units (End X) ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
422031cb00bd855fb59b31b25ba8ac69d2c3aac7 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Elab/PreDefinition/Structural/Eqns.lean | 6eb2de8a50f58ce2f80bbadcdfeda07f4410be0c | [
"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,914 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Eqns
import Lean.Meta.Tactic.Split
import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Apply
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Eqns
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab
open Meta
open Eqns
namespace Structural
structure EqnInfo extends EqnInfoCore where
recArgPos : Nat
deriving Inhabited
private partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do
trace[Elab.definition.structural.eqns] "proving: {type}"
withNewMCtxDepth do
let main ← mkFreshExprSyntheticOpaqueMVar type
let (_, mvarId) ← main.mvarId!.intros
unless (← tryURefl mvarId) do -- catch easy cases
go (← deltaLHS mvarId)
instantiateMVars main
where
go (mvarId : MVarId) : MetaM Unit := do
trace[Elab.definition.structural.eqns] "step\n{MessageData.ofGoal mvarId}"
if (← tryURefl mvarId) then
return ()
else if (← tryContradiction mvarId) then
return ()
else if let some mvarId ← simpMatch? mvarId then
go mvarId
else if let some mvarId ← simpIf? mvarId then
go mvarId
else if let some mvarId ← whnfReducibleLHS? mvarId then
go mvarId
else match (← simpTargetStar mvarId {}).1 with
| TacticResultCNM.closed => return ()
| TacticResultCNM.modified mvarId => go mvarId
| TacticResultCNM.noChange =>
if let some mvarId ← deltaRHS? mvarId declName then
go mvarId
else if let some mvarIds ← casesOnStuckLHS? mvarId then
mvarIds.forM go
else if let some mvarIds ← splitTarget? mvarId then
mvarIds.forM go
else
throwError "failed to generate equational theorem for '{declName}'\n{MessageData.ofGoal mvarId}"
def mkEqns (info : EqnInfo) : MetaM (Array Name) :=
withOptions (tactic.hygienic.set · false) do
let eqnTypes ← withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do
let us := info.levelParams.map mkLevelParam
let target ← mkEq (mkAppN (Lean.mkConst info.declName us) xs) body
let goal ← mkFreshExprSyntheticOpaqueMVar target
mkEqnTypes #[info.declName] goal.mvarId!
let baseName := mkPrivateName (← getEnv) info.declName
let mut thmNames := #[]
for i in [: eqnTypes.size] do
let type := eqnTypes[i]!
trace[Elab.definition.structural.eqns] "{eqnTypes[i]!}"
let name := baseName ++ (`_eq).appendIndexAfter (i+1)
thmNames := thmNames.push name
let value ← mkProof info.declName type
let (type, value) ← removeUnusedEqnHypotheses type value
addDecl <| Declaration.thmDecl {
name, type, value
levelParams := info.levelParams
}
return thmNames
builtin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo ← mkMapDeclarationExtension `structEqInfo
def registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do
modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }
def getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do
if let some info := eqnInfoExt.find? (← getEnv) declName then
mkEqns info
else
return none
def getUnfoldFor? (declName : Name) : MetaM (Option Name) := do
let env ← getEnv
Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (·.toEqnInfoCore)
@[export lean_get_structural_rec_arg_pos]
def getStructuralRecArgPosImp? (declName : Name) : CoreM (Option Nat) := do
let some info := eqnInfoExt.find? (← getEnv) declName | return none
return some info.recArgPos
builtin_initialize
registerGetEqnsFn getEqnsFor?
registerGetUnfoldEqnFn getUnfoldFor?
registerTraceClass `Elab.definition.structural.eqns
end Structural
end Lean.Elab
|
f21fc6f5be04808eeda5fa0ba081d6852b926db7 | c45b34bfd44d8607a2e8762c926e3cfaa7436201 | /uexp/src/uexp/rules/cse344.lean | dddeb44175a47fea1403ffb95bd23b8c01ee24d2 | [
"BSD-2-Clause"
] | permissive | Shamrock-Frost/Cosette | b477c442c07e45082348a145f19ebb35a7f29392 | 24cbc4adebf627f13f5eac878f04ffa20d1209af | refs/heads/master | 1,619,721,304,969 | 1,526,082,841,000 | 1,526,082,841,000 | 121,695,605 | 1 | 0 | null | 1,518,737,210,000 | 1,518,737,210,000 | null | UTF-8 | Lean | false | false | 1,465 | lean | import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..cosette_tactics
open Expr
open Proj
open Pred
open SQL
section
parameter uid : datatype
parameter uname : datatype
parameter size : datatype
parameter city : datatype
parameter pid : datatype
parameter Usr : Schema
parameter usr : relation Usr
parameter usrUid : Column uid Usr
parameter usrUname : Column uname Usr
parameter usrCity : Column city Usr
parameter Pic : Schema
parameter pic : relation Pic
parameter picUid : Column uid Pic
parameter picSize : Column size Pic
parameter picPid : Column pid Pic
parameter denver : const city
parameter denverNonNull : null ≠ denver
parameter gt1000000 : Pred (tree.leaf size)
parameter gt3000000 : Pred (tree.leaf size)
parameter Γ : Schema
definition x'' : Proj (Γ ++ Usr) Usr := right
noncomputable definition x''' : Proj ((Γ ++ Usr) ++ Pic) Usr := left ⋅ right
noncomputable definition y'' : Proj ((Γ ++ Usr) ++ Pic) Pic := right
noncomputable definition x'''' : Proj (Γ ++ (Usr ++ Pic)) Usr := right ⋅ left
noncomputable definition y'''' : Proj (Γ ++ (Usr ++ Pic)) Pic := right ⋅ right
noncomputable definition leftOuterJoin {s0 s1 : Schema}
(q0 : SQL Γ s0) (q1 : SQL Γ s1) (b : Pred (Γ ++ (s0 ++ s1)))
: SQL Γ (s0 ++ s1)
:= SELECT * (FROM2 q0, q1) WHERE b
-- Precedence?
local notation q0 `LEFT` `OUTER` `JOIN` q1 `ON` b := leftOuterJoin q0 q1 b
theorem problem3 : sorry := sorry
end |
71db31cca3f1bb7c7af1a3ab0dbfd5f5b1d60f67 | 7850aae797be6c31052ce4633d86f5991178d3df | /stage0/src/Lean/Elab/Command.lean | 6a67225a10d691fca29b253a866c9dda4594b38b | [
"Apache-2.0"
] | permissive | miriamgoetze/lean4 | 4dc24d4dbd360cc969713647c2958c6691947d16 | 062cc5d5672250be456a168e9c7b9299a9c69bdb | refs/heads/master | 1,685,865,971,011 | 1,624,107,703,000 | 1,624,107,703,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,032 | 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.Parser.Command
import Lean.ResolveName
import Lean.Meta.Reduce
import Lean.Elab.Log
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclModifiers
import Lean.Elab.InfoTree
import Lean.Elab.Open
import Lean.Elab.SetOption
namespace Lean.Elab.Command
structure Scope where
header : String
opts : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
levelNames : List Name := []
/-- section variables as `bracketedBinder`s -/
varDecls : Array Syntax := #[]
/-- Globally unique internal identifiers for the `varDecls` -/
varUIds : Array Name := #[]
deriving Inhabited
structure State where
env : Environment
messages : MessageLog := {}
scopes : List Scope := [{ header := "" }]
nextMacroScope : Nat := firstFrontendMacroScope + 1
maxRecDepth : Nat
nextInstIdx : Nat := 1 -- for generating anonymous instance names
ngen : NameGenerator := {}
infoState : InfoState := {}
traceState : TraceState := {}
deriving Inhabited
structure Context where
fileName : String
fileMap : FileMap
currRecDepth : Nat := 0
cmdPos : String.Pos := 0
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
ref : Syntax := Syntax.missing
abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε
abbrev CommandElabM := CommandElabCoreM Exception
abbrev CommandElab := Syntax → CommandElabM Unit
abbrev Linter := Syntax → CommandElabM Unit
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad CommandElabM := { inferInstanceAs (Monad CommandElabM) with }
def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := {
env := env
messages := messages
scopes := [{ header := "", opts := opts }]
maxRecDepth := maxRecDepth.get opts
}
/- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the
environment (which only contains `import`ed objects). -/
builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[]
def addLinter (l : Linter) : IO Unit := do
let ls ← lintersRef.get
lintersRef.set (ls.push l)
instance : MonadInfoTree CommandElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
instance : MonadEnv CommandElabM where
getEnv := do pure (← get).env
modifyEnv f := modify fun s => { s with env := f s.env }
instance : MonadOptions CommandElabM where
getOptions := do pure (← get).scopes.head!.opts
protected def getRef : CommandElabM Syntax :=
return (← read).ref
instance : AddMessageContext CommandElabM where
addMessageContext := addMessageContextPartial
instance : MonadRef CommandElabM where
getRef := Command.getRef
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadTrace CommandElabM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
instance : AddErrorMessageContext CommandElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
return (ref, msg)
def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message :=
mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos?.getD ctx.cmdPos)
private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context :=
let scope := s.scopes.head!
{ options := scope.opts
currRecDepth := ctx.currRecDepth
maxRecDepth := s.maxRecDepth
ref := ctx.ref
currNamespace := scope.currNamespace
openDecls := scope.openDecls
initHeartbeats := heartbeats }
def liftCoreM {α} (x : CoreM α) : CommandElabM α := do
let s ← get
let ctx ← read
let heartbeats ← IO.getNumHeartbeats (ε := Exception)
let Eα := Except Exception α
let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex
let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen }
let (ea, coreS) ← liftM x
modify fun s => { s with env := coreS.env, ngen := coreS.ngen }
match ea with
| Except.ok a => pure a
| Except.error e => throw e
private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message :=
let ref := getBetterRef ref ctx.macroStack
mkMessageAux ctx ref (toString err) MessageSeverity.error
@[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x
@[inline] def liftIO {α} (x : IO α) : CommandElabM α := do
let ctx ← read
IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x
instance : MonadLiftT IO CommandElabM where
monadLift := liftIO
def getScope : CommandElabM Scope := do pure (← get).scopes.head!
instance : MonadResolveName CommandElabM where
getCurrNamespace := return (← getScope).currNamespace
getOpenDecls := return (← getScope).openDecls
instance : MonadLog CommandElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data }
modify fun s => { s with messages := s.messages.add msg }
def runLinters (stx : Syntax) : CommandElabM Unit := do
let linters ← lintersRef.get
unless linters.isEmpty do
for linter in linters do
let savedState ← get
try
linter stx
catch ex =>
logException ex
finally
modify fun s => { savedState with messages := s.messages }
protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope
protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule
@[inline] protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do
let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation CommandElabM where
getCurrMacroScope := Command.getCurrMacroScope
getMainModule := Command.getMainModule
withFreshMacroScope := Command.withFreshMacroScope
unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) :=
mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command"
@[implementedBy mkCommandElabAttributeUnsafe]
constant mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab)
builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute
private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog :=
traceState.traces.foldl (init := log) fun (log : MessageLog) traceElem =>
let ref := replaceRef traceElem.ref ctx.ref;
let pos := ref.getPos?.getD 0;
log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos)
private def addTraceAsMessages : CommandElabM Unit := do
let ctx ← read
modify fun s => { s with
messages := addTraceAsMessagesCore ctx s.messages s.traceState
traceState.traces := {}
}
private def elabCommandUsing (s : State) (stx : Syntax) : List CommandElab → CommandElabM Unit
| [] => throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
catchInternalId unsupportedSyntaxExceptionId
(do elabFn stx; addTraceAsMessages)
(fun _ => do set s; addTraceAsMessages; elabCommandUsing s stx elabFns)
/- Elaborate `x` with `stx` on the macro stack -/
@[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α :=
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
instance : MonadMacroAdapter CommandElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← get).nextMacroScope
setNextMacroScope next := modify fun s => { s with nextMacroScope := next }
instance : MonadRecDepth CommandElabM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← get).maxRecDepth
register_builtin_option showPartialSyntaxErrors : Bool := {
defValue := false
descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)"
}
@[inline] def withLogging (x : CommandElabM Unit) : CommandElabM Unit := do
try
x
catch ex => match ex with
| Exception.error _ _ => logException ex
| Exception.internal id _ =>
if isAbortExceptionId id then
pure ()
else
let idName ← liftIO <| id.getName;
logError m!"internal exception {idName}"
builtin_initialize registerTraceClass `Elab.command
partial def elabCommand (stx : Syntax) : CommandElabM Unit := do
let mkInfoTree trees := do
let ctx ← read
let s ← get
let scope := s.scopes.head!
let tree := InfoTree.node (Info.ofCommandInfo { stx := stx }) trees
let tree := InfoTree.context {
env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts
} tree
if checkTraceOption (← getOptions) `Elab.info then
logTrace `Elab.info m!"{← tree.format}"
return tree
let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} })
withLogging <| withRef stx <| withInfoTreeContext (mkInfoTree := mkInfoTree) <| withIncRecDepth <| withFreshMacroScope do
runLinters stx
match stx with
| Syntax.node k args =>
if k == nullKind then
-- list of commands => elaborate in order
-- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones
args.forM elabCommand
else do
trace `Elab.command fun _ => stx;
let s ← get
let stxNew? ← catchInternalId unsupportedSyntaxExceptionId
(do let newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx))
(fun ex => pure none)
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew <| elabCommand stxNew
| _ =>
match commandElabAttribute.getValues s.env k with
| [] => throwError "elaboration function for '{k}' has not been implemented"
| elabFns => elabCommandUsing s stx elabFns
| _ => throwError "unexpected command"
let mut msgs ← (← get).messages
-- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general
if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then
-- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error
msgs := ⟨msgs.msgs.filter fun msg =>
msg.data.hasTag `Elab.synthPlaceholder || msg.data.hasTag `Tactic.unsolvedGoals⟩
modify ({ · with messages := initMsgs ++ msgs })
/-- Adapt a syntax transformation to a regular, command-producing elaborator. -/
def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do
let stx' ← exp stx
withMacroExpansion stx stx' <| elabCommand stx'
private def getVarDecls (s : State) : Array Syntax :=
s.scopes.head!.varDecls
instance {α} : Inhabited (CommandElabM α) where
default := throw arbitrary
private def mkMetaContext : Meta.Context := {
config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true }
}
def getBracketedBinderIds : Syntax → Array Name
| `(bracketedBinder|($ids* $[: $ty?]? $(annot?)?)) => ids.map Syntax.getId
| `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId
| `(bracketedBinder|[$id : $ty]) => #[id.getId]
| `(bracketedBinder|[$ty]) => #[Name.anonymous]
| _ => #[]
private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := do
let scope := s.scopes.head!
let mut sectionVars := {}
for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do
sectionVars := sectionVars.insert id uid
{ macroStack := ctx.macroStack
fileName := ctx.fileName
fileMap := ctx.fileMap
currMacroScope := ctx.currMacroScope
declName? := declName?
sectionVars := sectionVars }
private def mkTermState (scope : Scope) (s : State) : Term.State := {
messages := {}
levelNames := scope.levelNames
infoState.enabled := s.infoState.enabled
}
def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do
let ctx ← read
let s ← get
let heartbeats ← IO.getNumHeartbeats (ε := Exception)
-- dbg_trace "heartbeats: {heartbeats}"
let scope := s.scopes.head!
-- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands.
-- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog`
let x : MetaM _ := (observing x).run (mkTermContext ctx s declName?) (mkTermState scope s)
let x : CoreM _ := x.run mkMetaContext {}
let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope }
let (((ea, termS), metaS), coreS) ← liftEIO x
let infoTrees := termS.infoState.trees.map fun tree =>
let tree := tree.substitute termS.infoState.assignment
InfoTree.context {
env := coreS.env, fileMap := ctx.fileMap, mctx := metaS.mctx, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts
} tree
modify fun s => { s with
env := coreS.env
messages := addTraceAsMessagesCore ctx (s.messages ++ termS.messages) coreS.traceState
nextMacroScope := coreS.nextMacroScope
ngen := coreS.ngen
infoState.trees := s.infoState.trees.append infoTrees
}
match ea with
| Except.ok a => pure a
| Except.error ex => throw ex
@[inline] def runTermElabM {α} (declName? : Option Name) (elabFn : Array Expr → TermElabM α) : CommandElabM α := do
let scope ← getScope
liftTermElabM declName? <|
Term.withAutoBoundImplicit <|
Term.elabBinders scope.varDecls fun xs => do
-- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature
-- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly.
Term.synthesizeSyntheticMVarsNoPostponing
let mut sectionFVars := {}
for uid in scope.varUIds, x in xs do
sectionFVars := sectionFVars.insert uid x
withReader ({ · with sectionFVars := sectionFVars }) do
-- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command.
-- So, we use `Term.resetMessageLog`.
Term.resetMessageLog
let xs ← Term.addAutoBoundImplicits xs
Term.withoutAutoBoundImplicit <| elabFn xs
@[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref =>
EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ())
private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do
liftCoreM x
private def addScope (isNewNamespace : Bool) (header : String) (newNamespace : Name) : CommandElabM Unit := do
modify fun s => { s with
env := s.env.registerNamespace newNamespace,
scopes := { s.scopes.head! with header := header, currNamespace := newNamespace } :: s.scopes
}
pushScope
if isNewNamespace then
activateScoped newNamespace
private def addScopes (isNewNamespace : Bool) : Name → CommandElabM Unit
| Name.anonymous => pure ()
| Name.str p header _ => do
addScopes isNewNamespace p
let currNamespace ← getCurrNamespace
addScope isNewNamespace header (if isNewNamespace then Name.mkStr currNamespace header else currNamespace)
| _ => throwError "invalid scope"
private def addNamespace (header : Name) : CommandElabM Unit :=
addScopes (isNewNamespace := true) header
@[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun stx =>
match stx with
| `(namespace $n) => addNamespace n.getId
| _ => throwUnsupportedSyntax
@[builtinCommandElab «section»] def elabSection : CommandElab := fun stx =>
match stx with
| `(section $header:ident) => addScopes (isNewNamespace := false) header.getId
| `(section) => do let currNamespace ← getCurrNamespace; addScope (isNewNamespace := false) "" currNamespace
| _ => throwUnsupportedSyntax
def getScopes : CommandElabM (List Scope) := do
pure (← get).scopes
private def checkAnonymousScope : List Scope → Bool
| { header := "", .. } :: _ => true
| _ => false
private def checkEndHeader : Name → List Scope → Bool
| Name.anonymous, _ => true
| Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes
| _, _ => false
private def popScopes (numScopes : Nat) : CommandElabM Unit :=
for i in [0:numScopes] do
popScope
@[builtinCommandElab «end»] def elabEnd : CommandElab := fun stx => do
let header? := (stx.getArg 1).getOptionalIdent?;
let endSize := match header? with
| none => 1
| some n => n.getNumParts
let scopes ← getScopes
if endSize < scopes.length then
modify fun s => { s with scopes := s.scopes.drop endSize }
popScopes endSize
else -- we keep "root" scope
let n := (← get).scopes.length - 1
modify fun s => { s with scopes := s.scopes.drop n }
popScopes n
throwError "invalid 'end', insufficient scopes"
match header? with
| none =>
unless checkAnonymousScope scopes do
throwError "invalid 'end', name is missing"
| some header =>
unless checkEndHeader header scopes do
addCompletionInfo <| CompletionInfo.endSection stx (scopes.map fun scope => scope.header)
throwError "invalid 'end', name mismatch"
@[inline] def withNamespace {α} (ns : Name) (elabFn : CommandElabM α) : CommandElabM α := do
addNamespace ns
let a ← elabFn
modify fun s => { s with scopes := s.scopes.drop ns.getNumParts }
pure a
@[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit :=
modify fun s => { s with
scopes := match s.scopes with
| h::t => f h :: t
| [] => unreachable!
}
def getLevelNames : CommandElabM (List Name) :=
return (← getScope).levelNames
def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do
let id := idStx.getId
let levelNames ← getLevelNames
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel id
else
modifyScope fun scope => { scope with levelNames := id :: scope.levelNames }
partial def elabChoiceAux (cmds : Array Syntax) (i : Nat) : CommandElabM Unit :=
if h : i < cmds.size then
let cmd := cmds.get ⟨i, h⟩;
catchInternalId unsupportedSyntaxExceptionId
(elabCommand cmd)
(fun ex => elabChoiceAux cmds (i+1))
else
throwUnsupportedSyntax
@[builtinCommandElab choice] def elbChoice : CommandElab := fun stx =>
elabChoiceAux stx.getArgs 0
@[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do
addUnivLevel n[1]
@[builtinCommandElab «universes»] def elabUniverses : CommandElab := fun n => do
n[1].forArgsM addUnivLevel
@[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun stx => do
match (← getEnv).addDecl Declaration.quotDecl with
| Except.ok env => setEnv env
| Except.error ex => throwError (ex.toMessageData (← getOptions))
@[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do
-- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")")
let id := stx[1].getId
let ns ← resolveNamespace id
let currNamespace ← getCurrNamespace
if ns == currNamespace then throwError "invalid 'export', self export"
let env ← getEnv
let ids := stx[3].getArgs
let aliases ← ids.foldlM (init := []) fun (aliases : List (Name × Name)) (idStx : Syntax) => do
let id := idStx.getId
let declName := ns ++ id
if env.contains declName then
pure <| (currNamespace ++ id, declName) :: aliases
else
withRef idStx <| logUnknownDecl declName
pure aliases
modify fun s => { s with env := aliases.foldl (init := s.env) fun env p => addAlias env p.1 p.2 }
@[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do
let openDecls ← elabOpenDecl n[1]
modifyScope fun scope => { scope with openDecls := openDecls }
@[builtinCommandElab «variable»] def elabVariable : CommandElab
| `(variable $binders*) => do
-- Try to elaborate `binders` for sanity checking
runTermElabM none fun _ => Term.withAutoBoundImplicit <|
Term.elabBinders binders fun _ => pure ()
let varUIds ← binders.concatMap getBracketedBinderIds |>.mapM (withFreshMacroScope ∘ MonadQuotation.addMacroScope)
modifyScope fun scope => { scope with varDecls := scope.varDecls ++ binders, varUIds := scope.varUIds ++ varUIds }
| _ => throwUnsupportedSyntax
open Meta
@[builtinCommandElab Lean.Parser.Command.check] def elabCheck : CommandElab
| `(#check%$tk $term) => withoutModifyingEnv $ runTermElabM (some `_check) fun _ => do
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let (e, _) ← Term.levelMVarToParam (← instantiateMVars e)
let type ← inferType e
unless e.isSyntheticSorry do
logInfoAt tk m!"{e} : {type}"
| _ => throwUnsupportedSyntax
@[builtinCommandElab Lean.Parser.Command.reduce] def elabReduce : CommandElab
| `(#reduce%$tk $term) => withoutModifyingEnv <| runTermElabM (some `_check) fun _ => do
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let (e, _) ← Term.levelMVarToParam (← instantiateMVars e)
-- TODO: add options or notation for setting the following parameters
withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding false }) do
let e ← withTransparency (mode := TransparencyMode.all) <| reduce e (skipProofs := false) (skipTypes := false)
logInfoAt tk e
| _ => throwUnsupportedSyntax
def hasNoErrorMessages : CommandElabM Bool := do
return !(← get).messages.hasErrors
def failIfSucceeds (x : CommandElabM Unit) : CommandElabM Unit := do
let resetMessages : CommandElabM MessageLog := do
let s ← get
let messages := s.messages;
modify fun s => { s with messages := {} };
pure messages
let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do
modify fun s => { s with messages := prevMessages ++ s.messages.errorsToWarnings }
let prevMessages ← resetMessages
let succeeded ←
try
x
hasNoErrorMessages
catch
| ex@(Exception.error _ _) => do logException ex; pure false
| Exception.internal id _ => do logError (← id.getName); pure false
finally
restoreMessages prevMessages
if succeeded then
throwError "unexpected success"
@[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab
| `(#check_failure $term) => do
failIfSucceeds <| elabCheck (← `(#check $term))
| _ => throwUnsupportedSyntax
unsafe def elabEvalUnsafe : CommandElab
| `(#eval%$tk $term) => do
let n := `_eval
let ctx ← read
let addAndCompile (value : Expr) : TermElabM Unit := do
let type ← inferType value
let decl := Declaration.defnDecl {
name := n
levelParams := []
type := type
value := value
hints := ReducibilityHints.opaque
safety := DefinitionSafety.unsafe
}
Term.ensureNoUnassignedMVars decl
addAndCompile decl
let elabMetaEval : CommandElabM Unit := runTermElabM (some n) fun _ => do
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let e ← withLocalDeclD `env (mkConst ``Lean.Environment) fun env =>
withLocalDeclD `opts (mkConst ``Lean.Options) fun opts => do
let e ← mkAppM ``Lean.runMetaEval #[env, opts, e];
mkLambdaFVars #[env, opts] e
let env ← getEnv
let opts ← getOptions
let act ← try addAndCompile e; evalConst (Environment → Options → IO (String × Except IO.Error Environment)) n finally setEnv env
let (out, res) ← act env opts -- we execute `act` using the environment
logInfoAt tk out
match res with
| Except.error e => throwError e.toString
| Except.ok env => do setEnv env; pure ()
let elabEval : CommandElabM Unit := runTermElabM (some n) fun _ => do
-- fall back to non-meta eval if MetaEval hasn't been defined yet
-- modify e to `runEval e`
let e ← Term.elabTerm term none
let e := mkSimpleThunk e
Term.synthesizeSyntheticMVarsNoPostponing
let e ← mkAppM ``Lean.runEval #[e]
let env ← getEnv
let act ← try addAndCompile e; evalConst (IO (String × Except IO.Error Unit)) n finally setEnv env
let (out, res) ← liftM (m := IO) act
logInfoAt tk out
match res with
| Except.error e => throwError e.toString
| Except.ok _ => pure ()
if (← getEnv).contains ``Lean.MetaEval then do
elabMetaEval
else
elabEval
| _ => throwUnsupportedSyntax
@[builtinCommandElab «eval», implementedBy elabEvalUnsafe]
constant elabEval : CommandElab
@[builtinCommandElab «synth»] def elabSynth : CommandElab := fun stx => do
let term := stx[1]
withoutModifyingEnv <| runTermElabM `_synth_cmd fun _ => do
let inst ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let inst ← instantiateMVars inst
let val ← synthInstance inst
logInfo val
pure ()
@[builtinCommandElab «set_option»] def elabSetOption : CommandElab := fun stx => do
let options ← Elab.elabSetOption stx[1] stx[2]
modify fun s => { s with maxRecDepth := maxRecDepth.get options }
modifyScope fun scope => { scope with opts := options }
@[builtinMacro Lean.Parser.Command.«in»] def expandInCmd : Macro := fun stx => do
let cmd₁ := stx[0]
let cmd₂ := stx[2]
`(section $cmd₁:command $cmd₂:command end)
def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do
let currNamespace ← getCurrNamespace
let currLevelNames ← getLevelNames
Lean.Elab.expandDeclId currNamespace currLevelNames declId modifiers
end Elab.Command
export Elab.Command (Linter addLinter)
end Lean
|
c203a69dd9ad925ba6573f68314c7543510f3040 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0607.lean | e5c8fcf6ec12281bb387cb63a9d620ddf21e0d5f | [] | 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 | 120 | lean | #check sub_self
example (x : ℤ) : x * 0 = 0 :=
by rw [←sub_self (1 : ℤ), mul_sub, mul_one, sub_self, sub_self]
|
790535779496d5473ff01bbe2a98bc8a4af14a66 | c86b74188c4b7a462728b1abd659ab4e5828dd61 | /src/Init/Prelude.lean | e49640f52ab274b45edcad2536306a1281033dbd | [
"Apache-2.0"
] | permissive | cwb96/lean4 | 75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89 | b48831cda76e64f13dd1c0edde7ba5fb172ed57a | refs/heads/master | 1,686,347,881,407 | 1,624,483,842,000 | 1,624,483,842,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 75,059 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
universes u v w
@[inline] def id {α : Sort u} (a : α) : α := a
/- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=
fun x => f (g x)
abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=
fun x => a
set_option checkBinderAnnotations false in
@[reducible] def inferInstance {α : Sort u} [i : α] : α := i
set_option checkBinderAnnotations false in
@[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PUnit : Sort u where
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
inductive True : Prop where
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=
False.elim (h₂ h₁)
inductive Eq {α : Sort u} (a : α) : α → Prop where
| refl {} : Eq a a
@[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=
Eq.rec (motive := fun α _ => motive α) m h
@[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a
@[simp] theorem id_eq (a : α) : Eq (id a) a := rfl
theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=
Eq.ndrec h₂ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=
h ▸ rfl
theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c :=
h₂ ▸ h₁
@[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=
Eq.rec (motive := fun α _ => α) a h
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=
h ▸ rfl
theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) :=
h₁ ▸ h₂ ▸ rfl
theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) :=
h ▸ rfl
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where
| refl {} : HEq a a
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a :=
HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=
have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=
fun α β a b h₁ =>
HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)
(fun (h₂ : Eq α α) => rfl)
h₁
this α α a a' h rfl
structure Prod (α : Type u) (β : Type v) where
fst : α
snd : β
attribute [unbox] Prod
/-- Similar to `Prod`, but `α` and `β` can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) where
fst : α
snd : β
/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/
structure MProd (α β : Type u) where
fst : α
snd : β
structure And (a b : Prop) : Prop where
intro :: (left : a) (right : b)
inductive Or (a b : Prop) : Prop where
| inl (h : a) : Or a b
| inr (h : b) : Or a b
inductive Bool : Type where
| false : Bool
| true : Bool
export Bool (false true)
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) where
val : α
property : p val
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
/- Auxiliary axiom used to implement `sorry`. -/
@[extern "lean_sorry", neverExtract]
axiom sorryAx (α : Sort u) (synthetic := true) : α
theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false)
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true)
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
class Inhabited (α : Sort u) where
mk {} :: (default : α)
constant arbitrary [Inhabited α] : α :=
Inhabited.default
instance : Inhabited (Sort u) where
default := PUnit
instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where
default := fun _ => arbitrary
instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where
default := fun _ => arbitrary
deriving instance Inhabited for Bool
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u where
up :: (down : α)
/- Bijection between α and PLift α -/
theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b
| up a => rfl
theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a :=
rfl
/- Pointed types -/
structure PointedType where
(type : Type u)
(val : type)
instance : Inhabited PointedType.{u} where
default := { type := PUnit.{u+1}, val := ⟨⟩ }
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) where
up :: (down : α)
/- Bijection between α and ULift.{v} α -/
theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b
| up a => rfl
theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=
rfl
class inductive Decidable (p : Prop) where
| isFalse (h : Not p) : Decidable p
| isTrue (h : p) : Decidable p
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)
export Decidable (isTrue isFalse decide)
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
(a : α) → Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
(a b : α) → Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
(a b : α) → Decidable (Eq a b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=
s a b
theorem decideEqTrue : [s : Decidable p] → p → Eq (decide p) true
| isTrue _, _ => rfl
| isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : [s : Decidable p] → Not p → Eq (decide p) false
| isTrue h₁, h₂ => absurd h₁ h₂
| isFalse h, _ => rfl
theorem ofDecideEqTrue [s : Decidable p] : Eq (decide p) true → p := fun h =>
match (generalizing := false) s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse [s : Decidable p] : Eq (decide p) false → Not p := fun h =>
match (generalizing := false) s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse (fun h => Bool.noConfusion h)
| true, false => isFalse (fun h => Bool.noConfusion h)
| true, true => isTrue rfl
class BEq (α : Type u) where
beq : α → α → Bool
open BEq (beq)
instance [DecidableEq α] : BEq α where
beq a b := decide (Eq a b)
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=
Decidable.casesOn (motive := fun _ => α) h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t)
@[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) :=
match dp with
| isTrue hp =>
match dq with
| isTrue hq => isTrue ⟨hp, hq⟩
| isFalse hq => isFalse (fun h => hq (And.right h))
| isFalse hp =>
isFalse (fun h => hp (And.left h))
@[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) :=
match dp with
| isTrue hp => isTrue (Or.inl hp)
| isFalse hp =>
match dq with
| isTrue hq => isTrue (Or.inr hq)
| isFalse hq =>
isFalse fun h => match h with
| Or.inl h => hp h
| Or.inr h => hq h
instance [dp : Decidable p] : Decidable (Not p) :=
match dp with
| isTrue hp => isFalse (absurd hp)
| isFalse hp => isTrue hp
/- Boolean operators -/
@[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α :=
match c with
| true => x
| false => y
@[macroInline] def or (x y : Bool) : Bool :=
match x with
| true => true
| false => y
@[macroInline] def and (x y : Bool) : Bool :=
match x with
| false => false
| true => y
@[inline] def not : Bool → Bool
| true => false
| false => true
inductive Nat where
| zero : Nat
| succ (n : Nat) : Nat
instance : Inhabited Nat where
default := Nat.zero
/- For numeric literals notation -/
class OfNat (α : Type u) (n : Nat) where
ofNat : α
@[defaultInstance 100] /- low prio -/
instance (n : Nat) : OfNat Nat n where
ofNat := n
class LE (α : Type u) where le : α → α → Prop
class LT (α : Type u) where lt : α → α → Prop
@[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a
@[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a
@[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α :=
ite (LT.lt b a) a b
@[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α :=
ite (LE.le a b) a b
class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAdd : α → β → γ
class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hSub : α → β → γ
class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMul : α → β → γ
class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hDiv : α → β → γ
class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMod : α → β → γ
class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hPow : α → β → γ
class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAppend : α → β → γ
class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hOrElse : α → β → γ
class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAndThen : α → β → γ
class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAnd : α → β → γ
class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hXor : α → β → γ
class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hOr : α → β → γ
class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hShiftLeft : α → β → γ
class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hShiftRight : α → β → γ
class Add (α : Type u) where
add : α → α → α
class Sub (α : Type u) where
sub : α → α → α
class Mul (α : Type u) where
mul : α → α → α
class Neg (α : Type u) where
neg : α → α
class Div (α : Type u) where
div : α → α → α
class Mod (α : Type u) where
mod : α → α → α
class Pow (α : Type u) where
pow : α → α → α
class Append (α : Type u) where
append : α → α → α
class OrElse (α : Type u) where
orElse : α → α → α
class AndThen (α : Type u) where
andThen : α → α → α
class AndOp (α : Type u) where
and : α → α → α
class Xor (α : Type u) where
xor : α → α → α
class OrOp (α : Type u) where
or : α → α → α
class Complement (α : Type u) where
complement : α → α
class ShiftLeft (α : Type u) where
shiftLeft : α → α → α
class ShiftRight (α : Type u) where
shiftRight : α → α → α
@[defaultInstance]
instance [Add α] : HAdd α α α where
hAdd a b := Add.add a b
@[defaultInstance]
instance [Sub α] : HSub α α α where
hSub a b := Sub.sub a b
@[defaultInstance]
instance [Mul α] : HMul α α α where
hMul a b := Mul.mul a b
@[defaultInstance]
instance [Div α] : HDiv α α α where
hDiv a b := Div.div a b
@[defaultInstance]
instance [Mod α] : HMod α α α where
hMod a b := Mod.mod a b
@[defaultInstance]
instance [Pow α] : HPow α α α where
hPow a b := Pow.pow a b
@[defaultInstance]
instance [Append α] : HAppend α α α where
hAppend a b := Append.append a b
@[defaultInstance]
instance [OrElse α] : HOrElse α α α where
hOrElse a b := OrElse.orElse a b
@[defaultInstance]
instance [AndThen α] : HAndThen α α α where
hAndThen a b := AndThen.andThen a b
@[defaultInstance]
instance [AndOp α] : HAnd α α α where
hAnd a b := AndOp.and a b
@[defaultInstance]
instance [Xor α] : HXor α α α where
hXor a b := Xor.xor a b
@[defaultInstance]
instance [OrOp α] : HOr α α α where
hOr a b := OrOp.or a b
@[defaultInstance]
instance [ShiftLeft α] : HShiftLeft α α α where
hShiftLeft a b := ShiftLeft.shiftLeft a b
@[defaultInstance]
instance [ShiftRight α] : HShiftRight α α α where
hShiftRight a b := ShiftRight.shiftRight a b
open HAdd (hAdd)
open HMul (hMul)
open HPow (hPow)
open HAppend (hAppend)
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
instance : Add Nat where
add := Nat.add
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_mul"]
protected def Nat.mul : (@& Nat) → (@& Nat) → Nat
| a, 0 => 0
| a, Nat.succ b => Nat.add (Nat.mul a b) a
instance : Mul Nat where
mul := Nat.mul
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_pow"]
protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat
| 0 => 1
| succ n => Nat.mul (Nat.pow m n) m
instance : Pow Nat where
pow := Nat.pow
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_eq"]
def Nat.beq : (@& Nat) → (@& Nat) → Bool
| zero, zero => true
| zero, succ m => false
| succ n, zero => false
| succ n, succ m => beq n m
theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m
| zero, zero, h => rfl
| zero, succ m, h => Bool.noConfusion h
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have : Eq (beq n m) true := h
have : Eq n m := eqOfBeqEqTrue this
this ▸ rfl
theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m)
| zero, zero, h₁, h₂ => Bool.noConfusion h₁
| zero, succ m, h₁, h₂ => Nat.noConfusion h₂
| succ n, zero, h₁, h₂ => Nat.noConfusion h₂
| succ n, succ m, h₁, h₂ =>
have : Eq (beq n m) false := h₁
Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this))
@[extern "lean_nat_dec_eq"]
protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) :=
match h:beq n m with
| true => isTrue (eqOfBeqEqTrue h)
| false => isFalse (neOfBeqEqFalse h)
@[inline] instance : DecidableEq Nat := Nat.decEq
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_le"]
def Nat.ble : @& Nat → @& Nat → Bool
| zero, zero => true
| zero, succ m => true
| succ n, zero => false
| succ n, succ m => ble n m
protected def Nat.le (n m : Nat) : Prop :=
Eq (ble n m) true
instance : LE Nat where
le := Nat.le
protected def Nat.lt (n m : Nat) : Prop :=
Nat.le (succ n) m
instance : LT Nat where
lt := Nat.lt
theorem Nat.notSuccLeZero : ∀ (n : Nat), LE.le (succ n) 0 → False
| 0, h => nomatch h
| succ n, h => nomatch h
theorem Nat.notLtZero (n : Nat) : Not (LT.lt n 0) :=
notSuccLeZero n
@[extern "lean_nat_dec_le"]
instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) :=
decEq (Nat.ble n m) true
@[extern "lean_nat_dec_lt"]
instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) :=
decLe (succ n) m
theorem Nat.zeroLe : (n : Nat) → LE.le 0 n
| zero => rfl
| succ n => rfl
theorem Nat.succLeSucc {n m : Nat} (h : LE.le n m) : LE.le (succ n) (succ m) :=
h
theorem Nat.zeroLtSucc (n : Nat) : LT.lt 0 (succ n) :=
succLeSucc (zeroLe n)
theorem Nat.leStep : {n m : Nat} → LE.le n m → LE.le n (succ m)
| zero, zero, h => rfl
| zero, succ n, h => rfl
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have : LE.le n m := h
have : LE.le n (succ m) := leStep this
succLeSucc this
protected theorem Nat.leTrans : {n m k : Nat} → LE.le n m → LE.le m k → LE.le n k
| zero, m, k, h₁, h₂ => zeroLe _
| succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁
| succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂
| succ n, succ m, succ k, h₁, h₂ =>
have h₁' : LE.le n m := h₁
have h₂' : LE.le m k := h₂
show LE.le n k from
Nat.leTrans h₁' h₂'
protected theorem Nat.ltTrans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k :=
Nat.leTrans (leStep h₁)
theorem Nat.leSucc : (n : Nat) → LE.le n (succ n)
| zero => rfl
| succ n => leSucc n
theorem Nat.leSuccOfLe {n m : Nat} (h : LE.le n m) : LE.le n (succ m) :=
Nat.leTrans h (leSucc m)
protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m)
| zero, zero, h => Or.inl rfl
| zero, succ n, h => Or.inr (zeroLe n)
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have : LE.le n m := h
match Nat.eqOrLtOfLe this with
| Or.inl h => Or.inl (h ▸ rfl)
| Or.inr h => Or.inr (succLeSucc h)
protected def Nat.leRefl : (n : Nat) → LE.le n n
| zero => rfl
| succ n => Nat.leRefl n
protected theorem Nat.ltOrGe (n m : Nat) : Or (LT.lt n m) (GE.ge n m) :=
match m with
| zero => Or.inr (zeroLe n)
| succ m =>
match Nat.ltOrGe n m with
| Or.inl h => Or.inl (leSuccOfLe h)
| Or.inr h =>
match Nat.eqOrLtOfLe h with
| Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _)
| Or.inr h1 => Or.inr h1
protected theorem Nat.leAntisymm : {n m : Nat} → LE.le n m → LE.le m n → Eq n m
| zero, zero, h₁, h₂ => rfl
| succ n, zero, h₁, h₂ => Bool.noConfusion h₁
| zero, succ m, h₁, h₂ => Bool.noConfusion h₂
| succ n, succ m, h₁, h₂ =>
have h₁' : LE.le n m := h₁
have h₂' : LE.le m n := h₂
(Nat.leAntisymm h₁' h₂') ▸ rfl
protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m :=
match Nat.ltOrGe n m with
| Or.inl h₃ => h₃
| Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂
set_option bootstrap.genMatcherCode false in
@[extern c inline "lean_nat_sub(#1, lean_box(1))"]
def Nat.pred : (@& Nat) → Nat
| 0 => 0
| succ a => a
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_sub"]
protected def Nat.sub : (@& Nat) → (@& Nat) → Nat
| a, 0 => a
| a, succ b => pred (Nat.sub a b)
instance : Sub Nat where
sub := Nat.sub
theorem Nat.predLePred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m)
| zero, zero, h => rfl
| zero, succ n, h => zeroLe n
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h => h
theorem Nat.leOfSuccLeSucc {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m :=
predLePred
theorem Nat.leOfLtSucc {m n : Nat} : LT.lt m (succ n) → LE.le m n :=
leOfSuccLeSucc
@[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) :=
fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant
def System.Platform.numBits : Nat :=
(getNumBits ()).val
theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) :=
(getNumBits ()).property
structure Fin (n : Nat) where
val : Nat
isLt : LT.lt val n
theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val :=
h ▸ rfl
theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) :=
fun h' => absurd (veqOfEq h') h
instance (n : Nat) : DecidableEq (Fin n) :=
fun i j =>
match decEq i.val j.val with
| isTrue h => isTrue (Fin.eqOfVeq h)
| isFalse h => isFalse (Fin.neOfVne h)
instance {n} : LT (Fin n) where
lt a b := LT.lt a.val b.val
instance {n} : LE (Fin n) where
le a b := LE.le a.val b.val
instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt ..
instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe ..
def UInt8.size : Nat := 256
structure UInt8 where
val : Fin UInt8.size
attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk
attribute [extern "lean_uint8_to_nat"] UInt8.val
@[extern "lean_uint8_of_nat"]
def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt8 := UInt8.decEq
instance : Inhabited UInt8 where
default := UInt8.ofNatCore 0 (by decide)
def UInt16.size : Nat := 65536
structure UInt16 where
val : Fin UInt16.size
attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk
attribute [extern "lean_uint16_to_nat"] UInt16.val
@[extern "lean_uint16_of_nat"]
def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt16 := UInt16.decEq
instance : Inhabited UInt16 where
default := UInt16.ofNatCore 0 (by decide)
def UInt32.size : Nat := 4294967296
structure UInt32 where
val : Fin UInt32.size
attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk
attribute [extern "lean_uint32_to_nat"] UInt32.val
@[extern "lean_uint32_of_nat"]
def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := {
val := { val := n, isLt := h }
}
@[extern "lean_uint32_to_nat"]
def UInt32.toNat (n : UInt32) : Nat := n.val.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt32 := UInt32.decEq
instance : Inhabited UInt32 where
default := UInt32.ofNatCore 0 (by decide)
instance : LT UInt32 where
lt a b := LT.lt a.val b.val
instance : LE UInt32 where
le a b := LE.le a.val b.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m))
instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b
instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b
def UInt64.size : Nat := 18446744073709551616
structure UInt64 where
val : Fin UInt64.size
attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk
attribute [extern "lean_uint64_to_nat"] UInt64.val
@[extern "lean_uint64_of_nat"]
def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt64 := UInt64.decEq
instance : Inhabited UInt64 where
default := UInt64.ofNatCore 0 (by decide)
def USize.size : Nat := hPow 2 System.Platform.numBits
theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) :=
show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from
match System.Platform.numBits, System.Platform.numBitsEq with
| _, Or.inl rfl => Or.inl (by decide)
| _, Or.inr rfl => Or.inr (by decide)
structure USize where
val : Fin USize.size
attribute [extern "lean_usize_of_nat_mk"] USize.mk
attribute [extern "lean_usize_to_nat"] USize.val
@[extern "lean_usize_of_nat"]
def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def USize.decEq (a b : USize) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq USize := USize.decEq
instance : Inhabited USize where
default := USize.ofNatCore 0 (match USize.size, usizeSzEq with
| _, Or.inl rfl => by decide
| _, Or.inr rfl => by decide)
@[extern "lean_usize_of_nat"]
def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := {
val := {
val := n
isLt := match USize.size, usizeSzEq with
| _, Or.inl rfl => h
| _, Or.inr rfl => Nat.ltTrans h (by decide)
}
}
abbrev Nat.isValidChar (n : Nat) : Prop :=
Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000))
abbrev UInt32.isValidChar (n : UInt32) : Prop :=
n.toNat.isValidChar
/-- The `Char` Type represents an unicode scalar value.
See http://www.unicode.org/glossary/#unicode_scalar_value). -/
structure Char where
val : UInt32
valid : val.isValidChar
private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size :=
match h with
| Or.inl h => Nat.ltTrans h (by decide)
| Or.inr ⟨_, h⟩ => Nat.ltTrans h (by decide)
@[extern "lean_uint32_of_nat"]
private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char :=
{ val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h }
@[noinline, matchPattern]
def Char.ofNat (n : Nat) : Char :=
dite (n.isValidChar)
(fun h => Char.ofNatAux n h)
(fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) })
theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val
| _, _, rfl => rfl
theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) :=
fun h' => absurd (veqOfEq h') h
theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) :=
fun h' => absurd (eqOfVeq h') h
instance : DecidableEq Char :=
fun c d =>
match decEq c.val d.val with
| isTrue h => isTrue (Char.eqOfVeq h)
| isFalse h => isFalse (Char.neOfVne h)
def Char.utf8Size (c : Char) : UInt32 :=
let v := c.val
ite (LE.le v (UInt32.ofNatCore 0x7F (by decide)))
(UInt32.ofNatCore 1 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide)))
(UInt32.ofNatCore 2 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide)))
(UInt32.ofNatCore 3 (by decide))
(UInt32.ofNatCore 4 (by decide))))
inductive Option (α : Type u) where
| none : Option α
| some (val : α) : Option α
attribute [unbox] Option
export Option (none some)
instance {α} : Inhabited (Option α) where
default := none
@[macroInline] def Option.getD : Option α → α → α
| some x, _ => x
| none, e => e
inductive List (α : Type u) where
| nil : List α
| cons (head : α) (tail : List α) : List α
instance {α} : Inhabited (List α) where
default := List.nil
protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b)
| nil, nil => isTrue rfl
| cons a as, nil => isFalse (fun h => List.noConfusion h)
| nil, cons b bs => isFalse (fun h => List.noConfusion h)
| cons a as, cons b bs =>
match decEq a b with
| isTrue hab =>
match List.hasDecEq as bs with
| isTrue habs => isTrue (hab ▸ habs ▸ rfl)
| isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs))
| isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab))
instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq
@[specialize]
def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α
| a, nil => a
| a, cons b l => foldl f (f a b) l
def List.set : List α → Nat → α → List α
| cons a as, 0, b => cons b as
| cons a as, Nat.succ n, b => cons a (set as n b)
| nil, _, _ => nil
def List.lengthAux {α : Type u} : List α → Nat → Nat
| nil, n => n
| cons a as, n => lengthAux as (Nat.succ n)
def List.length {α : Type u} (as : List α) : Nat :=
lengthAux as 0
@[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ :=
let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ :=
match as with
| nil => fun _ => rfl
| cons a as => fun n => aux a as n.succ
aux a as 0
def List.concat {α : Type u} : List α → α → List α
| nil, b => cons b nil
| cons a as, b => cons a (concat as b)
def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α
| nil, i, h => absurd h (Nat.notLtZero _)
| cons a as, 0, h => a
| cons a as, Nat.succ i, h =>
have : LT.lt i.succ as.length.succ := length_cons .. ▸ h
get as i (Nat.leOfSuccLeSucc this)
structure String where
data : List Char
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq String := String.decEq
/-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded.
Codepoint positions (counting the Unicode codepoints rather than bytes)
are represented by plain `Nat`s instead.
Indexing a `String` by a byte position is constant-time, while codepoint
positions need to be translated internally to byte positions in linear-time. -/
abbrev String.Pos := Nat
structure Substring where
str : String
startPos : String.Pos
stopPos : String.Pos
@[inline] def Substring.bsize : Substring → Nat
| ⟨_, b, e⟩ => e.sub b
def String.csize (c : Char) : Nat :=
c.utf8Size.toNat
private def String.utf8ByteSizeAux : List Char → Nat → Nat
| List.nil, r => r
| List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c))
@[extern "lean_string_utf8_byte_size"]
def String.utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def String.bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def String.toSubstring (s : String) : Substring := {
str := s
startPos := 0
stopPos := s.bsize
}
@[extern c inline "#3"]
unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β :=
cast lcProof (PUnit.{v})
@[neverExtract, extern "lean_panic_fn"]
constant panic {α : Type u} [Inhabited α] (msg : String) : α
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (α : Type u) where
data : List α
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_mk"] Array.mk
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := {
data := List.nil
}
def Array.empty {α : Type u} : Array α :=
mkEmpty 0
@[reducible, extern "lean_array_get_size"]
def Array.size {α : Type u} (a : @& Array α) : Nat :=
a.data.length
@[extern "lean_array_fget"]
def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α :=
a.data.get i.val i.isLt
@[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α :=
dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀)
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
Array.getD a i arbitrary
def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α :=
self.get! idx
@[extern "lean_array_push"]
def Array.push {α : Type u} (a : Array α) (v : α) : Array α := {
data := List.concat a.data v
}
@[extern "lean_array_fset"]
def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := {
data := a.data.set i.val v
}
@[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α :=
dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a)
@[extern "lean_array_set"]
def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α :=
Array.setD a i v
-- Slower `Array.append` used in quotations.
protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α :=
let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α :=
dite (LT.lt j bs.size)
(fun hlt =>
match i with
| 0 => as
| Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩)))
(fun _ => as)
loop bs.size 0 as
@[inlineIfReduce]
def List.toArrayAux : List α → Array α → Array α
| nil, r => r
| cons a as, r => toArrayAux as (r.push a)
@[inlineIfReduce]
def List.redLength : List α → Nat
| nil => 0
| cons _ as => as.redLength.succ
@[inline, matchPattern, export lean_list_to_array]
def List.toArray (as : List α) : Array α :=
as.toArrayAux (Array.mkEmpty as.redLength)
class Bind (m : Type u → Type v) where
bind : {α β : Type u} → m α → (α → m β) → m β
export Bind (bind)
class Pure (f : Type u → Type v) where
pure {α : Type u} : α → f α
export Pure (pure)
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)
class Seq (f : Type u → Type v) : Type (max (u+1) v) where
seq : {α β : Type u} → f (α → β) → f α → f β
class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
seqLeft : {α β : Type u} → f α → f β → f α
class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
seqRight : {α β : Type u} → f α → f β → f β
class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y x
seqLeft x y := bind x fun a => bind y (fun _ => pure a)
seqRight x y := bind x fun _ => y
instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where
default := pure
instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where
default := pure arbitrary
-- A fusion of Haskell's `sequence` and `map`
def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) :=
let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) :=
dite (LT.lt j as.size)
(fun hlt =>
match i with
| 0 => pure bs
| Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b))
(fun _ => bs)
loop as.size 0 Array.empty
/-- A Function for lifting a computation from an inner Monad to an outer Monad.
Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),
but `n` does not have to be a monad transformer.
Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/
class MonadLift (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
/-- The reflexive-transitive closure of `MonadLift`.
`monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`.
Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/
class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
export MonadLiftT (monadLift)
abbrev liftM := @monadLift
instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where
monadLift x := MonadLift.monadLift (m := n) (monadLift x)
instance (m) : MonadLiftT m m where
monadLift x := x
/-- A functor in the category of monads. Can be used to lift monad-transforming functions.
Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),
but not restricted to monad transformers.
Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/
class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
/-- The reflexive-transitive closure of `MonadFunctor`.
`monadMap` is used to transitively lift Monad morphisms -/
class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α
export MonadFunctorT (monadMap)
instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where
monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f)
instance monadFunctorRefl (m) : MonadFunctorT m m where
monadMap f := f
inductive Except (ε : Type u) (α : Type v) where
| error : ε → Except ε α
| ok : α → Except ε α
attribute [unbox] Except
instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where
default := Except.error arbitrary
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class MonadExceptOf (ε : Type u) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α :=
MonadExceptOf.throw e
abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α :=
MonadExceptOf.tryCatch x handle
/-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
export MonadExcept (throw tryCatch)
instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where
throw := throwThe ε
tryCatch := tryCatchThe ε
namespace MonadExcept
variable {ε : Type u} {m : Type v → Type w}
@[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α :=
tryCatch t₁ fun _ => t₂
instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where
orElse := MonadExcept.orelse
end MonadExcept
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
ρ → m α
instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where
default := fun _ => arbitrary
@[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α :=
x r
namespace ReaderT
section
variable {ρ : Type u} {m : Type u → Type v} {α : Type u}
instance : MonadLift m (ReaderT ρ m) where
monadLift x := fun _ => x
instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where
throw e := liftM (m := m) (throw e)
tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r)
end
section
variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u}
@[inline] protected def read : ReaderT ρ m ρ :=
pure
@[inline] protected def pure (a : α) : ReaderT ρ m α :=
fun r => pure a
@[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β :=
fun r => bind (x r) fun a => f a r
@[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β :=
fun r => Functor.map f (x r)
instance : Monad (ReaderT ρ m) where
pure := ReaderT.pure
bind := ReaderT.bind
map := ReaderT.map
instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where
monadMap f x := fun ctx => f (x ctx)
@[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α :=
fun x r => x (f r)
end
end ReaderT
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this Function cannot be lifted using `monadLift`.
Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where
lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α
```
-/
class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where
read : m ρ
@[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ :=
MonadReaderOf.read
/-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/
class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where
read : m ρ
export MonadReader (read)
instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where
read := readThe ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where
read := liftM (m := m) read
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where
read := ReaderT.read
class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
@[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α :=
MonadWithReaderOf.withReader f x
class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
export MonadWithReader (withReader)
instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where
withReader := withTheReader ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where
withReader f := monadMap (m := m) (withTheReader ρ f)
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where
withReader f x := fun ctx => x (f ctx)
/-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html).
In contrast to the Haskell implementation, we use overlapping instances to derive instances
automatically from `monadLift`. -/
class MonadStateOf (σ : Type u) (m : Type u → Type v) where
/- Obtain the top-most State of a Monad stack. -/
get : m σ
/- Set the top-most State of a Monad stack. -/
set : σ → m PUnit
/- Map the top-most State of a Monad stack.
Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a`
because the latter does not use the State linearly (without sufficient inlining). -/
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadStateOf (set)
abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ :=
MonadStateOf.get
@[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit :=
MonadStateOf.modifyGet fun s => (PUnit.unit, f s)
@[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α :=
MonadStateOf.modifyGet f
/-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/
class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where
get : m σ
set : σ → m PUnit
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadState (get modifyGet)
instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where
set := MonadStateOf.set
get := getThe σ
modifyGet f := MonadStateOf.modifyGet f
@[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit :=
modifyGet fun s => (PUnit.unit, f s)
@[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ :=
modifyGet fun s => (s, f s)
-- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer
-- will be picked first
instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where
get := liftM (m := m) MonadStateOf.get
set s := liftM (m := m) (MonadStateOf.set s)
modifyGet f := monadLift (m := m) (MonadState.modifyGet f)
namespace EStateM
inductive Result (ε σ α : Type u) where
| ok : α → σ → Result ε σ α
| error : ε → σ → Result ε σ α
variable {ε σ α : Type u}
instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where
default := Result.error arbitrary arbitrary
end EStateM
open EStateM (Result) in
def EStateM (ε σ α : Type u) := σ → Result ε σ α
namespace EStateM
variable {ε σ α β : Type u}
instance [Inhabited ε] : Inhabited (EStateM ε σ α) where
default := fun s => Result.error arbitrary s
@[inline] protected def pure (a : α) : EStateM ε σ α := fun s =>
Result.ok a s
@[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ =>
Result.ok ⟨⟩ s
@[inline] protected def get : EStateM ε σ σ := fun s =>
Result.ok s s
@[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s =>
match f s with
| (a, s) => Result.ok a s
@[inline] protected def throw (e : ε) : EStateM ε σ α := fun s =>
Result.error e s
/-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/
class Backtrackable (δ : outParam (Type u)) (σ : Type u) where
save : σ → δ
restore : σ → δ → σ
@[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s
match x s with
| Result.error e s => handle e (Backtrackable.restore s d)
| ok => ok
@[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s;
match x₁ s with
| Result.error _ s => x₂ (Backtrackable.restore s d)
| ok => ok
@[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s =>
match x s with
| Result.error e s => Result.error (f e) s
| Result.ok a s => Result.ok a s
@[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => f a s
| Result.error e s => Result.error e s
@[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => Result.ok (f a) s
| Result.error e s => Result.error e s
@[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok _ s => y s
| Result.error e s => Result.error e s
instance : Monad (EStateM ε σ) where
bind := EStateM.bind
pure := EStateM.pure
map := EStateM.map
seqRight := EStateM.seqRight
instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where
orElse := EStateM.orElse
instance : MonadStateOf σ (EStateM ε σ) where
set := EStateM.set
get := EStateM.get
modifyGet := EStateM.modifyGet
instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where
throw := EStateM.throw
tryCatch := EStateM.tryCatch
@[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α :=
x s
@[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α :=
match run x s with
| Result.ok v _ => some v
| Result.error .. => none
@[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩
@[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s
/- Dummy default instance -/
instance nonBacktrackable : Backtrackable PUnit σ where
save := dummySave
restore := dummyRestore
end EStateM
class Hashable (α : Sort u) where
hash : α → UInt64
export Hashable (hash)
@[extern c inline "(size_t)#1"]
constant UInt64.toUSize (u : UInt64) : USize
@[extern c inline "(uint64_t)#1"]
constant USize.toUInt64 (u : USize) : UInt64
@[extern "lean_uint64_mix_hash"]
constant mixHash (u₁ u₂ : UInt64) : UInt64
@[extern "lean_string_hash"]
protected constant String.hash (s : @& String) : UInt64
instance : Hashable String where
hash := String.hash
namespace Lean
/- Hierarchical names -/
inductive Name where
| anonymous : Name
| str : Name → String → UInt64 → Name
| num : Name → Nat → UInt64 → Name
instance : Inhabited Name where
default := Name.anonymous
protected def Name.hash : Name → UInt64
| Name.anonymous => UInt64.ofNatCore 1723 (by decide)
| Name.str p s h => h
| Name.num p v h => h
instance : Hashable Name where
hash := Name.hash
namespace Name
@[export lean_name_mk_string]
def mkStr (p : Name) (s : String) : Name :=
Name.str p s (mixHash (hash p) (hash s))
@[export lean_name_mk_numeral]
def mkNum (p : Name) (v : Nat) : Name :=
Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide))))
def mkSimple (s : String) : Name :=
mkStr Name.anonymous s
@[extern "lean_name_eq"]
protected def beq : (@& Name) → (@& Name) → Bool
| anonymous, anonymous => true
| str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂)
| num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂)
| _, _ => false
instance : BEq Name where
beq := Name.beq
protected def append : Name → Name → Name
| n, anonymous => n
| n, str p s _ => Name.mkStr (Name.append n p) s
| n, num p d _ => Name.mkNum (Name.append n p) d
instance : Append Name where
append := Name.append
end Name
/- Syntax -/
/-- Source information of tokens. -/
inductive SourceInfo where
/-
Token from original input with whitespace and position information.
`leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing,
it is not at all clear what the preceding token was, especially with backtracking. -/
| original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos)
/-
Synthesized token (e.g. from a quotation) annotated with a span from the original source.
In the delaborator, we "misuse" this constructor to store synthetic positions identifying
subterms. -/
| synthetic (pos : String.Pos) (endPos : String.Pos)
/- Synthesized token without position information. -/
| protected none
instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩
namespace SourceInfo
def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos :=
match info, originalOnly with
| original (pos := pos) .., _ => some pos
| synthetic (pos := pos) .., false => some pos
| _, _ => none
end SourceInfo
abbrev SyntaxNodeKind := Name
/- Syntax AST -/
inductive Syntax where
| missing : Syntax
| node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax
| atom (info : SourceInfo) (val : String) : Syntax
| ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax
instance : Inhabited Syntax where
default := Syntax.missing
/- Builtin kinds -/
def choiceKind : SyntaxNodeKind := `choice
def nullKind : SyntaxNodeKind := `null
def groupKind : SyntaxNodeKind := `group
def identKind : SyntaxNodeKind := `ident
def strLitKind : SyntaxNodeKind := `strLit
def charLitKind : SyntaxNodeKind := `charLit
def numLitKind : SyntaxNodeKind := `numLit
def scientificLitKind : SyntaxNodeKind := `scientificLit
def nameLitKind : SyntaxNodeKind := `nameLit
def fieldIdxKind : SyntaxNodeKind := `fieldIdx
def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind
def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind
namespace Syntax
def getKind (stx : Syntax) : SyntaxNodeKind :=
match stx with
| Syntax.node k args => k
-- We use these "pseudo kinds" for antiquotation kinds.
-- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident)
-- is compiled to ``if stx.isOfKind `ident ...``
| Syntax.missing => `missing
| Syntax.atom _ v => Name.mkSimple v
| Syntax.ident .. => identKind
def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax :=
match stx with
| Syntax.node _ args => Syntax.node k args
| _ => stx
def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool :=
beq stx.getKind k
def getArg (stx : Syntax) (i : Nat) : Syntax :=
match stx with
| Syntax.node _ args => args.getD i Syntax.missing
| _ => Syntax.missing
-- Add `stx[i]` as sugar for `stx.getArg i`
@[inline] def getOp (self : Syntax) (idx : Nat) : Syntax :=
self.getArg idx
def getArgs (stx : Syntax) : Array Syntax :=
match stx with
| Syntax.node _ args => args
| _ => Array.empty
def getNumArgs (stx : Syntax) : Nat :=
match stx with
| Syntax.node _ args => args.size
| _ => 0
def isMissing : Syntax → Bool
| Syntax.missing => true
| _ => false
def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool :=
and (stx.isOfKind k) (beq stx.getNumArgs n)
def isIdent : Syntax → Bool
| ident _ _ _ _ => true
| _ => false
def getId : Syntax → Name
| ident _ _ val _ => val
| _ => Name.anonymous
def matchesNull (stx : Syntax) (n : Nat) : Bool :=
isNodeOf stx nullKind n
def matchesIdent (stx : Syntax) (id : Name) : Bool :=
and stx.isIdent (beq stx.getId id)
def setArgs (stx : Syntax) (args : Array Syntax) : Syntax :=
match stx with
| node k _ => node k args
| stx => stx
def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax :=
match stx with
| node k args => node k (args.setD i arg)
| stx => stx
/-- Retrieve the left-most leaf's info in the Syntax tree. -/
partial def getHeadInfo? : Syntax → Option SourceInfo
| atom info _ => some info
| ident info .. => some info
| node _ args =>
let rec loop (i : Nat) : Option SourceInfo :=
match decide (LT.lt i args.size) with
| true => match getHeadInfo? (args.get! i) with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _ => none
/-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/
partial def getHeadInfo (stx : Syntax) : SourceInfo :=
match stx.getHeadInfo? with
| some info => info
| none => SourceInfo.none
def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
stx.getHeadInfo.getPos? originalOnly
partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
match stx, originalOnly with
| atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos
| ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos
| node _ args, _ =>
let rec loop (i : Nat) : Option String.Pos :=
match decide (LT.lt i args.size) with
| true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _, _ => none
/--
An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically
remove/insert the separators. -/
structure SepArray (sep : String) where
elemsAndSeps : Array Syntax
end Syntax
def SourceInfo.fromRef (ref : Syntax) : SourceInfo :=
match ref.getPos?, ref.getTailPos? with
| some pos, some tailPos => SourceInfo.synthetic pos tailPos
| _, _ => SourceInfo.none
def mkAtom (val : String) : Syntax :=
Syntax.atom SourceInfo.none val
def mkAtomFrom (src : Syntax) (val : String) : Syntax :=
Syntax.atom src.getHeadInfo val
/- Parser descriptions -/
inductive ParserDescr where
| const (name : Name)
| unary (name : Name) (p : ParserDescr)
| binary (name : Name) (p₁ p₂ : ParserDescr)
| node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr)
| trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr)
| symbol (val : String)
| nonReservedSymbol (val : String) (includeIdent : Bool)
| cat (catName : Name) (rbp : Nat)
| parser (declName : Name)
| nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr)
| sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
| sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
instance : Inhabited ParserDescr where
default := ParserDescr.symbol ""
abbrev TrailingParserDescr := ParserDescr
/-
Runtime support for making quotation terms auto-hygienic, by mangling identifiers
introduced by them with a "macro scope" supplied by the context. Details to appear in a
paper soon.
-/
abbrev MacroScope := Nat
/-- Macro scope used internally. It is not available for our frontend. -/
def reservedMacroScope := 0
/-- First macro scope available for our frontend -/
def firstFrontendMacroScope := hAdd reservedMacroScope 1
class MonadRef (m : Type → Type) where
getRef : m Syntax
withRef {α} : Syntax → m α → m α
export MonadRef (getRef)
instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where
getRef := liftM (getRef : m _)
withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x
def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax :=
match ref.getPos? with
| some _ => ref
| _ => oldRef
@[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α :=
bind getRef fun oldRef =>
let ref := replaceRef ref oldRef
MonadRef.withRef ref x
/-- A monad that supports syntax quotations. Syntax quotations (in term
position) are monadic values that when executed retrieve the current "macro
scope" from the monad and apply it to every identifier they introduce
(independent of whether this identifier turns out to be a reference to an
existing declaration, or an actually fresh binding during further
elaboration). We also apply the position of the result of `getRef` to each
introduced symbol, which results in better error positions than not applying
any position. -/
class MonadQuotation (m : Type → Type) extends MonadRef m where
-- Get the fresh scope of the current macro invocation
getCurrMacroScope : m MacroScope
getMainModule : m Name
/- Execute action in a new macro invocation context. This transformer should be
used at all places that morally qualify as the beginning of a "macro call",
e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it
can also be used internally inside a "macro" if identifiers introduced by
e.g. different recursive calls should be independent and not collide. While
returning an intermediate syntax tree that will recursively be expanded by
the elaborator can be used for the same effect, doing direct recursion inside
the macro guarded by this transformer is often easier because one is not
restricted to passing a single syntax tree. Modelling this helper as a
transformer and not just a monadic action ensures that the current macro
scope before the recursive call is restored after it, as expected. -/
withFreshMacroScope {α : Type} : m α → m α
export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope)
def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do
SourceInfo.fromRef (← getRef)
instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where
getCurrMacroScope := liftM (m := m) getCurrMacroScope
getMainModule := liftM (m := m) getMainModule
withFreshMacroScope := monadMap (m := m) withFreshMacroScope
/-
We represent a name with macro scopes as
```
<actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes>
```
Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5]
```
foo.bla._@.Init.Data.List.Basic._hyg.2.5
```
We may have to combine scopes from different files/modules.
The main modules being processed is always the right most one.
This situation may happen when we execute a macro generated in
an imported file in the current file.
```
foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4
```
The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance.
-/
def Name.hasMacroScopes : Name → Bool
| str _ s _ => beq s "_hyg"
| num p _ _ => hasMacroScopes p
| _ => false
private def eraseMacroScopesAux : Name → Name
| Name.str p s _ => match beq s "_@" with
| true => p
| false => eraseMacroScopesAux p
| Name.num p _ _ => eraseMacroScopesAux p
| Name.anonymous => Name.anonymous
@[export lean_erase_macro_scopes]
def Name.eraseMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => eraseMacroScopesAux n
| false => n
private def simpMacroScopesAux : Name → Name
| Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i
| n => eraseMacroScopesAux n
/- Helper function we use to create binder names that do not need to be unique. -/
@[export lean_simp_macro_scopes]
def Name.simpMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => simpMacroScopesAux n
| false => n
structure MacroScopesView where
name : Name
imported : Name
mainModule : Name
scopes : List MacroScope
instance : Inhabited MacroScopesView where
default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩
def MacroScopesView.review (view : MacroScopesView) : Name :=
match view.scopes with
| List.nil => view.name
| List.cons _ _ =>
let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg")
view.scopes.foldl Name.mkNum base
private def assembleParts : List Name → Name → Name
| List.nil, acc => acc
| List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s)
| List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n)
| _, acc => panic "Error: unreachable @ assembleParts"
private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps }
| false => extractImported scps mainModule p (List.cons n parts)
| n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts)
| _, _ => panic "Error: unreachable @ extractImported"
private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps }
| false => extractMainModule scps p (List.cons n parts)
| n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil
| _, _ => panic "Error: unreachable @ extractMainModule"
private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView
| Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc)
| Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg"
| _, _ => panic "Error: unreachable @ extractMacroScopesAux"
/--
Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`.
This operation is useful for analyzing/transforming the original identifiers, then adding back
the scopes (via `MacroScopesView.review`). -/
def extractMacroScopes (n : Name) : MacroScopesView :=
match n.hasMacroScopes with
| true => extractMacroScopesAux n List.nil
| false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous }
def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name :=
match n.hasMacroScopes with
| true =>
let view := extractMacroScopes n
match beq view.mainModule mainModule with
| true => Name.mkNum n scp
| false =>
{ view with
imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule)
mainModule := mainModule
scopes := List.cons scp List.nil
}.review
| false =>
Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp
@[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name :=
bind getMainModule fun mainModule =>
bind getCurrMacroScope fun scp =>
pure (Lean.addMacroScope mainModule n scp)
def defaultMaxRecDepth := 512
def maxRecDepthErrorMessage : String :=
"maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)"
namespace Macro
/- References -/
private constant MethodsRefPointed : PointedType.{0}
private def MethodsRef : Type := MethodsRefPointed.type
structure Context where
methods : MethodsRef
mainModule : Name
currMacroScope : MacroScope
currRecDepth : Nat := 0
maxRecDepth : Nat := defaultMaxRecDepth
ref : Syntax
inductive Exception where
| error : Syntax → String → Exception
| unsupportedSyntax : Exception
structure State where
macroScope : MacroScope
traceMsgs : List (Prod Name String) := List.nil
deriving Inhabited
end Macro
abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State)
abbrev Macro := Syntax → MacroM Syntax
namespace Macro
instance : MonadRef MacroM where
getRef := bind read fun ctx => pure ctx.ref
withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x
def addMacroScope (n : Name) : MacroM Name :=
bind read fun ctx =>
pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope)
def throwUnsupported {α} : MacroM α :=
throw Exception.unsupportedSyntax
def throwError {α} (msg : String) : MacroM α :=
bind getRef fun ref =>
throw (Exception.error ref msg)
def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α :=
withRef ref (throwError msg)
@[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α :=
bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh =>
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
@[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α :=
bind read fun ctx =>
match beq ctx.currRecDepth ctx.maxRecDepth with
| true => throw (Exception.error ref maxRecDepthErrorMessage)
| false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x
instance : MonadQuotation MacroM where
getCurrMacroScope ctx := pure ctx.currMacroScope
getMainModule ctx := pure ctx.mainModule
withFreshMacroScope := Macro.withFreshMacroScope
structure Methods where
expandMacro? : Syntax → MacroM (Option Syntax)
getCurrNamespace : MacroM Name
hasDecl : Name → MacroM Bool
resolveNamespace? : Name → MacroM (Option Name)
resolveGlobalName : Name → MacroM (List (Prod Name (List String)))
deriving Inhabited
unsafe def mkMethodsImp (methods : Methods) : MethodsRef :=
unsafeCast methods
@[implementedBy mkMethodsImp]
constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val
instance : Inhabited MethodsRef where
default := mkMethods arbitrary
unsafe def getMethodsImp : MacroM Methods :=
bind read fun ctx => pure (unsafeCast (ctx.methods))
@[implementedBy getMethodsImp] constant getMethods : MacroM Methods
/-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/
def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do
(← getMethods).expandMacro? stx
/-- Return `true` if the environment contains a declaration with name `declName` -/
def hasDecl (declName : Name) : MacroM Bool := do
(← getMethods).hasDecl declName
def getCurrNamespace : MacroM Name := do
(← getMethods).getCurrNamespace
def resolveNamespace? (n : Name) : MacroM (Option Name) := do
(← getMethods).resolveNamespace? n
def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do
(← getMethods).resolveGlobalName n
def trace (clsName : Name) (msg : String) : MacroM Unit := do
modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs }
end Macro
export Macro (expandMacro?)
namespace PrettyPrinter
abbrev UnexpandM := EStateM Unit Unit
/--
Function that tries to reverse macro expansions as a post-processing step of delaboration.
While less general than an arbitrary delaborator, it can be declared without importing `Lean`.
Used by the `[appUnexpander]` attribute. -/
-- a `kindUnexpander` could reasonably be added later
abbrev Unexpander := Syntax → UnexpandM Syntax
-- unexpanders should not need to introduce new names
instance : MonadQuotation UnexpandM where
getRef := pure Syntax.missing
withRef := fun _ => id
getCurrMacroScope := pure 0
getMainModule := pure `_fakeMod
withFreshMacroScope := id
end PrettyPrinter
end Lean
|
4d5baf0e7c3e63fec60b97db2d90868a7e229789 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/monoid/prod.lean | e7f0d95f7729e3d3356b2df216f1eb4cd603eda4 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,481 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.group.prod
import algebra.order.monoid.cancel.defs
import algebra.order.monoid.canonical.defs
/-! # Products of ordered monoids -/
namespace prod
variables {α β M N : Type*}
@[to_additive]
instance [ordered_comm_monoid α] [ordered_comm_monoid β] : ordered_comm_monoid (α × β) :=
{ mul_le_mul_left := λ a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩,
.. prod.comm_monoid, .. prod.partial_order _ _ }
@[to_additive]
instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] :
ordered_cancel_comm_monoid (M × N) :=
{ le_of_mul_le_mul_left := λ a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩,
.. prod.ordered_comm_monoid }
@[to_additive] instance [has_le α] [has_le β] [has_mul α] [has_mul β] [has_exists_mul_of_le α]
[has_exists_mul_of_le β] : has_exists_mul_of_le (α × β) :=
⟨λ a b h, let ⟨c, hc⟩ := exists_mul_of_le h.1, ⟨d, hd⟩ := exists_mul_of_le h.2 in
⟨(c, d), ext hc hd⟩⟩
@[to_additive] instance [canonically_ordered_monoid α] [canonically_ordered_monoid β] :
canonically_ordered_monoid (α × β) :=
{ le_self_mul := λ a b, ⟨le_self_mul, le_self_mul⟩,
..prod.ordered_comm_monoid, ..prod.order_bot _ _, ..prod.has_exists_mul_of_le }
end prod
|
f8705293045ade8290fc8cd1ce2eb0439668e9c3 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/pempty.lean | 892f9a461cefaebc4bf2bddd019aeeaf2fa6b5b5 | [
"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 | 1,295 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.discrete_category
/-!
# The empty category
Defines a category structure on `pempty`, and the unique functor `pempty ⥤ C` for any category `C`.
-/
universes v u w -- morphism levels before object levels. See note [category_theory universes].
namespace category_theory
namespace functor
variables (C : Type u) [category.{v} C]
/-- The canonical functor out of the empty category. -/
def empty : discrete pempty.{v+1} ⥤ C := discrete.functor pempty.elim
variable {C}
/-- Any two functors out of the empty category are isomorphic. -/
def empty_ext (F G : discrete pempty.{v+1} ⥤ C) : F ≅ G :=
discrete.nat_iso (λ x, pempty.elim x)
/--
Any functor out of the empty category is isomorphic to the canonical functor from the empty
category.
-/
def unique_from_empty (F : discrete pempty.{v+1} ⥤ C) : F ≅ empty C :=
empty_ext _ _
/--
Any two functors out of the empty category are *equal*. You probably want to use
`empty_ext` instead of this.
-/
lemma empty_ext' (F G : discrete pempty.{v+1} ⥤ C) : F = G :=
functor.ext (λ x, x.elim) (λ x _ _, x.elim)
end functor
end category_theory
|
675b139ca117714ef31128f66853ac760b0e514a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/compilerTest1.lean | d025ffd96a166b5dadf24a776ddd488b9610ef17 | [
"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 | 207 | lean | import Lean
#eval Lean.Compiler.compile #[``Lean.Elab.Structural.structuralRecursion, ``Lean.Elab.Command.elabStructure, ``Lean.Environment.displayStats, ``Lean.Meta.IndPredBelow.mkBelow, ``unexpandExists]
|
34675eb229e0905510733855a25f92605d0c15b9 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/group_theory/complement.lean | e20a2320602b260c83679a9ff0e2d27710bf7457 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,254 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import group_theory.group_action
import group_theory.order_of_element
import group_theory.quotient_group
/-!
# Complements
In this file we define the complement of a subgroup.
## Main definitions
- `is_complement S T` where `S` and `T` are subsets of `G` states that every `g : G` can be
written uniquely as a product `s * t` for `s ∈ S`, `t ∈ T`.
- `left_transversals T` where `T` is a subset of `G` is the set of all left-complements of `T`,
i.e. the set of all `S : set G` that contain exactly one element of each left coset of `T`.
- `right_transversals S` where `S` is a subset of `G` is the set of all right-complements of `S`,
i.e. the set of all `T : set G` that contain exactly one element of each right coset of `S`.
## Main results
- `is_complement_of_coprime` : Subgroups of coprime order are complements.
- `exists_right_complement_of_coprime` : **Schur-Zassenhaus** for abelian normal subgroups:
If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists
a subgroup `K` which is a (right) complement of `H`.
-/
open_locale big_operators
namespace subgroup
variables {G : Type*} [group G] (H K : subgroup G) (S T : set G)
/-- `S` and `T` are complements if `(*) : S × T → G` is a bijection.
This notion generalizes left transversals, right transversals, and complementary subgroups. -/
@[to_additive "`S` and `T` are complements if `(*) : S × T → G` is a bijection"]
def is_complement : Prop := function.bijective (λ x : S × T, x.1.1 * x.2.1)
/-- The set of left-complements of `T : set G` -/
@[to_additive "The set of left-complements of `T : set G`"]
def left_transversals : set (set G) := {S : set G | is_complement S T}
/-- The set of right-complements of `S : set G` -/
@[to_additive "The set of right-complements of `S : set G`"]
def right_transversals : set (set G) := {T : set G | is_complement S T}
variables {H K S T}
@[to_additive] lemma is_complement_iff_exists_unique :
is_complement S T ↔ ∀ g : G, ∃! x : S × T, x.1.1 * x.2.1 = g :=
function.bijective_iff_exists_unique _
@[to_additive] lemma is_complement.exists_unique (h : is_complement S T) (g : G) :
∃! x : S × T, x.1.1 * x.2.1 = g :=
is_complement_iff_exists_unique.mp h g
@[to_additive] lemma is_complement.symm (h : is_complement (H : set G) (K : set G)) :
is_complement (K : set G) (H : set G) :=
begin
let ϕ : H × K ≃ K × H := equiv.mk (λ x, ⟨x.2⁻¹, x.1⁻¹⟩) (λ x, ⟨x.2⁻¹, x.1⁻¹⟩)
(λ x, prod.ext (inv_inv _) (inv_inv _)) (λ x, prod.ext (inv_inv _) (inv_inv _)),
let ψ : G ≃ G := equiv.mk (λ g : G, g⁻¹) (λ g : G, g⁻¹) inv_inv inv_inv,
suffices : ψ ∘ (λ x : H × K, x.1.1 * x.2.1) = (λ x : K × H, x.1.1 * x.2.1) ∘ ϕ,
{ rwa [is_complement, ←equiv.bijective_comp, ←this, equiv.comp_bijective] },
exact funext (λ x, mul_inv_rev _ _),
end
@[to_additive] lemma is_complement_comm :
is_complement (H : set G) (K : set G) ↔ is_complement (K : set G) (H : set G) :=
⟨is_complement.symm, is_complement.symm⟩
@[to_additive] lemma mem_left_transversals_iff_exists_unique_inv_mul_mem :
S ∈ left_transversals T ↔ ∀ g : G, ∃! s : S, (s : G)⁻¹ * g ∈ T :=
begin
rw [left_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique],
refine ⟨λ h g, _, λ h g, _⟩,
{ obtain ⟨x, h1, h2⟩ := h g,
exact ⟨x.1, (congr_arg (∈ T) (eq_inv_mul_of_mul_eq h1)).mp x.2.2, λ y hy,
(prod.ext_iff.mp (h2 ⟨y, y⁻¹ * g, hy⟩ (mul_inv_cancel_left y g))).1⟩ },
{ obtain ⟨x, h1, h2⟩ := h g,
refine ⟨⟨x, x⁻¹ * g, h1⟩, mul_inv_cancel_left x g, λ y hy, _⟩,
have := h2 y.1 ((congr_arg (∈ T) (eq_inv_mul_of_mul_eq hy)).mp y.2.2),
exact prod.ext this (subtype.ext (eq_inv_mul_of_mul_eq ((congr_arg _ this).mp hy))) },
end
@[to_additive] lemma mem_right_transversals_iff_exists_unique_mul_inv_mem :
S ∈ right_transversals T ↔ ∀ g : G, ∃! s : S, g * (s : G)⁻¹ ∈ T :=
begin
rw [right_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique],
refine ⟨λ h g, _, λ h g, _⟩,
{ obtain ⟨x, h1, h2⟩ := h g,
exact ⟨x.2, (congr_arg (∈ T) (eq_mul_inv_of_mul_eq h1)).mp x.1.2, λ y hy,
(prod.ext_iff.mp (h2 ⟨⟨g * y⁻¹, hy⟩, y⟩ (inv_mul_cancel_right g y))).2⟩ },
{ obtain ⟨x, h1, h2⟩ := h g,
refine ⟨⟨⟨g * x⁻¹, h1⟩, x⟩, inv_mul_cancel_right g x, λ y hy, _⟩,
have := h2 y.2 ((congr_arg (∈ T) (eq_mul_inv_of_mul_eq hy)).mp y.1.2),
exact prod.ext (subtype.ext (eq_mul_inv_of_mul_eq ((congr_arg _ this).mp hy))) this },
end
@[to_additive] lemma mem_left_transversals_iff_exists_unique_quotient_mk'_eq :
S ∈ left_transversals (H : set G) ↔
∀ q : quotient (quotient_group.left_rel H), ∃! s : S, quotient.mk' s.1 = q :=
begin
have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ g⁻¹ * h ∈ H :=
@quotient.eq' G (quotient_group.left_rel H),
simp_rw [mem_left_transversals_iff_exists_unique_inv_mul_mem, set_like.mem_coe, ←key],
exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩,
end
@[to_additive] lemma mem_right_transversals_iff_exists_unique_quotient_mk'_eq :
S ∈ right_transversals (H : set G) ↔
∀ q : quotient (quotient_group.right_rel H), ∃! s : S, quotient.mk' s.1 = q :=
begin
have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ h * g⁻¹ ∈ H :=
@quotient.eq' G (quotient_group.right_rel H),
simp_rw [mem_right_transversals_iff_exists_unique_mul_inv_mem, set_like.mem_coe, ←key],
exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩,
end
@[to_additive] lemma mem_left_transversals_iff_bijective : S ∈ left_transversals (H : set G) ↔
function.bijective (S.restrict (quotient.mk' : G → quotient (quotient_group.left_rel H))) :=
mem_left_transversals_iff_exists_unique_quotient_mk'_eq.trans
(function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm
@[to_additive] lemma mem_right_transversals_iff_bijective : S ∈ right_transversals (H : set G) ↔
function.bijective (set.restrict (quotient.mk' : G → quotient (quotient_group.right_rel H)) S) :=
mem_right_transversals_iff_exists_unique_quotient_mk'_eq.trans
(function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm
@[to_additive] instance : inhabited (left_transversals (H : set G)) :=
⟨⟨set.range quotient.out', mem_left_transversals_iff_bijective.mpr ⟨by
{ rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg,
rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩
@[to_additive] instance : inhabited (right_transversals (H : set G)) :=
⟨⟨set.range quotient.out', mem_right_transversals_iff_bijective.mpr ⟨by
{ rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg,
rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩
lemma is_complement_of_disjoint [fintype G] [fintype H] [fintype K]
(h1 : fintype.card H * fintype.card K = fintype.card G)
(h2 : disjoint H K) :
is_complement (H : set G) (K : set G) :=
begin
refine (fintype.bijective_iff_injective_and_card _).mpr
⟨λ x y h, _, (fintype.card_prod H K).trans h1⟩,
rw [←eq_inv_mul_iff_mul_eq, ←mul_assoc, ←mul_inv_eq_iff_eq_mul] at h,
change ↑(x.2 * y.2⁻¹) = ↑(x.1⁻¹ * y.1) at h,
rw [prod.ext_iff, ←@inv_mul_eq_one H _ x.1 y.1, ←@mul_inv_eq_one K _ x.2 y.2, subtype.ext_iff,
subtype.ext_iff, coe_one, coe_one, h, and_self, ←mem_bot, ←h2.eq_bot, mem_inf],
exact ⟨subtype.mem ((x.1)⁻¹ * (y.1)), (congr_arg (∈ K) h).mp (subtype.mem (x.2 * (y.2)⁻¹))⟩,
end
lemma is_complement_of_coprime [fintype G] [fintype H] [fintype K]
(h1 : fintype.card H * fintype.card K = fintype.card G)
(h2 : nat.coprime (fintype.card H) (fintype.card K)) :
is_complement (H : set G) (K : set G) :=
is_complement_of_disjoint h1 (disjoint_iff.mpr (inf_eq_bot_of_coprime h2))
section schur_zassenhaus
@[to_additive] instance : mul_action G (left_transversals (H : set G)) :=
{ smul := λ g T, ⟨left_coset g T, mem_left_transversals_iff_exists_unique_inv_mul_mem.mpr (λ g', by
{ obtain ⟨t, ht1, ht2⟩ := mem_left_transversals_iff_exists_unique_inv_mul_mem.mp T.2 (g⁻¹ * g'),
simp_rw [←mul_assoc, ←mul_inv_rev] at ht1 ht2,
refine ⟨⟨g * t, mem_left_coset g t.2⟩, ht1, _⟩,
rintros ⟨_, t', ht', rfl⟩ h,
exact subtype.ext ((mul_right_inj g).mpr (subtype.ext_iff.mp (ht2 ⟨t', ht'⟩ h))) })⟩,
one_smul := λ T, subtype.ext (one_left_coset T),
mul_smul := λ g g' T, subtype.ext (left_coset_assoc ↑T g g').symm }
lemma smul_symm_apply_eq_mul_symm_apply_inv_smul
(g : G) (α : left_transversals (H : set G)) (q : quotient_group.quotient H) :
↑((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)).symm q) =
g * ((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm
(g⁻¹ • q : quotient_group.quotient H)) :=
begin
let w := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)),
let y := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)),
change ↑(y.symm q) = ↑(⟨_, mem_left_coset g (subtype.mem _)⟩ : (g • α).1),
refine subtype.ext_iff.mp (y.symm_apply_eq.mpr _),
change q = g • (w (w.symm (g⁻¹ • q : quotient_group.quotient H))),
rw [equiv.apply_symm_apply, ←mul_smul, mul_inv_self, one_smul],
end
variables [is_commutative H] [fintype (quotient_group.quotient H)]
variables (α β γ : left_transversals (H : set G))
/-- The difference of two left transversals -/
@[to_additive "The difference of two left transversals"]
noncomputable def diff [hH : normal H] : H :=
let α' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm,
β' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp β.2)).symm in
∏ (q : quotient_group.quotient H), ⟨(α' q) * (β' q)⁻¹,
hH.mem_comm (quotient.exact' ((β'.symm_apply_apply q).trans (α'.symm_apply_apply q).symm))⟩
@[to_additive] lemma diff_mul_diff [normal H] : diff α β * diff β γ = diff α γ :=
finset.prod_mul_distrib.symm.trans (finset.prod_congr rfl (λ x hx, subtype.ext
(by rw [coe_mul, coe_mk, coe_mk, coe_mk, mul_assoc, inv_mul_cancel_left])))
@[to_additive] lemma diff_self [normal H] : diff α α = 1 :=
mul_right_eq_self.mp (diff_mul_diff α α α)
@[to_additive] lemma diff_inv [normal H]: (diff α β)⁻¹ = diff β α :=
inv_eq_of_mul_eq_one ((diff_mul_diff α β α).trans (diff_self α))
lemma smul_diff_smul [hH : normal H] (g : G) :
diff (g • α) (g • β) = ⟨g * diff α β * g⁻¹, hH.conj_mem (diff α β).1 (diff α β).2 g⟩ :=
begin
let ϕ : H →* H :=
{ to_fun := λ h, ⟨g * h * g⁻¹, hH.conj_mem h.1 h.2 g⟩,
map_one' := subtype.ext (by rw [coe_mk, coe_one, mul_one, mul_inv_self]),
map_mul' := λ h₁ h₂, subtype.ext (by rw [coe_mk, coe_mul, coe_mul, coe_mk, coe_mk, mul_assoc,
mul_assoc, mul_assoc, mul_assoc, mul_assoc, inv_mul_cancel_left]) },
refine eq.trans (finset.prod_bij' (λ q _, (↑g)⁻¹ * q) (λ _ _, finset.mem_univ _)
(λ q _, subtype.ext _) (λ q _, ↑g * q) (λ _ _, finset.mem_univ _)
(λ q _, mul_inv_cancel_left g q) (λ q _, inv_mul_cancel_left g q)) (ϕ.map_prod _ _).symm,
change _ * _ = g * (_ * _) * g⁻¹,
simp_rw [smul_symm_apply_eq_mul_symm_apply_inv_smul, mul_inv_rev, mul_assoc],
refl,
end
lemma smul_diff [H.normal] (h : H) :
diff (h • α) β = h ^ (fintype.card (quotient_group.quotient H)) * diff α β :=
begin
rw [diff, diff, ←finset.card_univ, ←finset.prod_const, ←finset.prod_mul_distrib],
refine finset.prod_congr rfl (λ q _, _),
rw [subtype.ext_iff, coe_mul, coe_mk, coe_mk, ←mul_assoc, mul_right_cancel_iff],
rw [show h • α = (h : G) • α, from rfl, smul_symm_apply_eq_mul_symm_apply_inv_smul],
rw [mul_left_cancel_iff, ←subtype.ext_iff, equiv.apply_eq_iff_eq, inv_smul_eq_iff],
exact self_eq_mul_left.mpr ((quotient_group.eq_one_iff _).mpr h.2),
end
variables (H)
instance setoid_diff [H.normal] : setoid (left_transversals (H : set G)) :=
setoid.mk (λ α β, diff α β = 1) ⟨λ α, diff_self α, λ α β h₁,
by rw [←diff_inv, h₁, one_inv], λ α β γ h₁ h₂, by rw [←diff_mul_diff, h₁, h₂, one_mul]⟩
/-- The quotient of the transversals of an abelian normal `N` by the `diff` relation -/
def quotient_diff [H.normal] :=
quotient H.setoid_diff
instance [H.normal] : inhabited H.quotient_diff :=
quotient.inhabited
variables {H}
instance [H.normal] : mul_action G H.quotient_diff :=
{ smul := λ g, quotient.map (λ α, g • α) (λ α β h, (smul_diff_smul α β g).trans
(subtype.ext (mul_inv_eq_one.mpr (mul_right_eq_self.mpr (subtype.ext_iff.mp h))))),
mul_smul := λ g₁ g₂ q, quotient.induction_on q (λ α, congr_arg quotient.mk (mul_smul g₁ g₂ α)),
one_smul := λ q, quotient.induction_on q (λ α, congr_arg quotient.mk (one_smul G α)) }
variables [fintype H]
lemma exists_smul_eq [H.normal] (α β : H.quotient_diff)
(hH : nat.coprime (fintype.card H) (fintype.card (quotient_group.quotient H))) :
∃ h : H, h • α = β :=
quotient.induction_on α (quotient.induction_on β
(λ β α, exists_imp_exists (λ n, quotient.sound)
⟨(pow_coprime hH).symm (diff α β)⁻¹, by
{ change diff ((_ : H) • _) _ = 1,
rw smul_diff,
change pow_coprime hH ((pow_coprime hH).symm (diff α β)⁻¹) * (diff α β) = 1,
rw [equiv.apply_symm_apply, inv_mul_self] }⟩))
lemma smul_left_injective [H.normal] (α : H.quotient_diff)
(hH : nat.coprime (fintype.card H) (fintype.card (quotient_group.quotient H))) :
function.injective (λ h : H, h • α) :=
λ h₁ h₂, begin
refine quotient.induction_on α (λ α hα, _),
replace hα : diff (h₁ • α) (h₂ • α) = 1 := quotient.exact hα,
rw [smul_diff, ←diff_inv, smul_diff, diff_self, mul_one, mul_inv_eq_one] at hα,
exact (pow_coprime hH).injective hα,
end
lemma is_complement_stabilizer_of_coprime [fintype G] [H.normal] {α : H.quotient_diff}
(hH : nat.coprime (fintype.card H) (fintype.card (quotient_group.quotient H))) :
is_complement (H : set G) (mul_action.stabilizer G α : set G) :=
begin
classical,
let ϕ : H ≃ mul_action.orbit G α := equiv.of_bijective (λ h, ⟨h • α, h, rfl⟩)
⟨λ h₁ h₂ hh, smul_left_injective α hH (subtype.ext_iff.mp hh),
λ β, exists_imp_exists (λ h hh, subtype.ext hh) (exists_smul_eq α β hH)⟩,
have key := card_eq_card_quotient_mul_card_subgroup (mul_action.stabilizer G α),
rw ← fintype.card_congr (ϕ.trans (mul_action.orbit_equiv_quotient_stabilizer G α)) at key,
apply is_complement_of_coprime key.symm,
rw [card_eq_card_quotient_mul_card_subgroup H, mul_comm, mul_right_inj'] at key,
{ rw ← key, convert hH },
{ rw [←pos_iff_ne_zero, fintype.card_pos_iff],
apply_instance },
end
/-- **Schur-Zassenhaus** for abelian normal subgroups:
If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists
a subgroup `K` which is a (right) complement of `H`. -/
theorem exists_right_complement_of_coprime [fintype G] [H.normal]
(hH : nat.coprime (fintype.card H) (fintype.card (quotient_group.quotient H))) :
∃ K : subgroup G, is_complement (H : set G) (K : set G) :=
nonempty_of_inhabited.elim
(λ α : H.quotient_diff, ⟨mul_action.stabilizer G α, is_complement_stabilizer_of_coprime hH⟩)
/-- **Schur-Zassenhaus** for abelian normal subgroups:
If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists
a subgroup `K` which is a (left) complement of `H`. -/
theorem exists_left_complement_of_coprime [fintype G] [H.normal]
(hH : nat.coprime (fintype.card H) (fintype.card (quotient_group.quotient H))) :
∃ K : subgroup G, is_complement (K : set G) (H : set G) :=
Exists.imp (λ _, is_complement.symm) (exists_right_complement_of_coprime hH)
end schur_zassenhaus
end subgroup
|
ee3026de3d5a8316e87ab13413aed33b4c836850 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/algebraic_geometry/prime_spectrum.lean | 84136ec7cee67d3cde92011681322f6f1a4e26da | [
"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 | 14,252 | 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 topology.opens
import ring_theory.ideal.prod
import linear_algebra.finsupp
import algebra.punit_instances
/-!
# Prime spectrum of a commutative ring
The prime spectrum of a commutative ring is the type of all prime ideals.
It is naturally endowed with a topology: the Zariski topology.
(It is also naturally endowed with a sheaf of rings,
which is constructed in `algebraic_geometry.structure_sheaf`.)
## Main definitions
* `prime_spectrum R`: The prime spectrum of a commutative ring `R`,
i.e., the set of all prime ideals of `R`.
* `zero_locus s`: The zero locus of a subset `s` of `R`
is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`.
* `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R`
is the intersection of points in `t` (viewed as prime ideals).
## Conventions
We denote subsets of rings with `s`, `s'`, etc...
whereas we denote subsets of prime spectra with `t`, `t'`, etc...
## Inspiration/contributors
The contents of this file draw inspiration from
<https://github.com/ramonfmir/lean-scheme>
which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau,
and Chris Hughes (on an earlier repository).
-/
noncomputable theory
open_locale classical
universe variables u v
variables (R : Type u) [comm_ring R]
/-- The prime spectrum of a commutative ring `R`
is the type of all prime ideals of `R`.
It is naturally endowed with a topology (the Zariski topology),
and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`).
It is a fundamental building block in algebraic geometry. -/
@[nolint has_inhabited_instance]
def prime_spectrum := {I : ideal R // I.is_prime}
variable {R}
namespace prime_spectrum
/-- A method to view a point in the prime spectrum of a commutative ring
as an ideal of that ring. -/
abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val
instance is_prime (x : prime_spectrum R) :
x.as_ideal.is_prime := x.2
/--
The prime spectrum of the zero ring is empty.
-/
lemma punit (x : prime_spectrum punit) : false :=
x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem
section
variables (R) (S : Type v) [comm_ring S]
/-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of
`R` and the prime spectrum of `S`. -/
noncomputable def prime_spectrum_prod :
prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S :=
ideal.prime_ideals_equiv R S
variables {R S}
@[simp] lemma prime_spectrum_prod_symm_inl_as_ideal (x : prime_spectrum R) :
((prime_spectrum_prod R S).symm (sum.inl x)).as_ideal = ideal.prod x.as_ideal ⊤ :=
by { cases x, refl }
@[simp] lemma prime_spectrum_prod_symm_inr_as_ideal (x : prime_spectrum S) :
((prime_spectrum_prod R S).symm (sum.inr x)).as_ideal = ideal.prod ⊤ x.as_ideal :=
by { cases x, refl }
end
@[ext] lemma ext {x y : prime_spectrum R} :
x = y ↔ x.as_ideal = y.as_ideal :=
subtype.ext_iff_val
/-- The zero locus of a set `s` of elements of a commutative ring `R`
is the set of all prime ideals of the ring that contain the set `s`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R`
where all "functions" in `s` vanish simultaneously.
-/
def zero_locus (s : set R) : set (prime_spectrum R) :=
{x | s ⊆ x.as_ideal}
@[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) :
x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl
@[simp] lemma zero_locus_span (s : set R) :
zero_locus (ideal.span s : set R) = zero_locus s :=
by { ext x, exact (submodule.gi R R).gc s x.as_ideal }
/-- The vanishing ideal of a set `t` of points
of the prime spectrum of a commutative ring `R`
is the intersection of all the prime ideals in the set `t`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `vanishing_ideal t` is exactly the ideal of `R`
consisting of all "functions" that vanish on all of `t`.
-/
def vanishing_ideal (t : set (prime_spectrum R)) : ideal R :=
⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal
lemma coe_vanishing_ideal (t : set (prime_spectrum R)) :
(vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} :=
begin
ext f,
rw [vanishing_ideal, submodule.mem_coe, submodule.mem_infi],
apply forall_congr, intro x,
rw [submodule.mem_infi],
end
lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) :
f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal :=
by rw [← submodule.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq]
lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) :
t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t :=
begin
split; intro h,
{ intros f hf,
rw [mem_vanishing_ideal],
intros x hx,
have hxI := h hx,
rw mem_zero_locus at hxI,
exact hxI hf },
{ intros x hx,
rw mem_zero_locus,
refine le_trans h _,
intros f hf,
rw [mem_vanishing_ideal] at hf,
exact hf x hx }
end
section gc
variable (R)
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc : @galois_connection
(ideal R) (order_dual (set (prime_spectrum R))) _ _
(λ I, zero_locus I) (λ t, vanishing_ideal t) :=
λ I t, subset_zero_locus_iff_le_vanishing_ideal t I
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc_set : @galois_connection
(set R) (order_dual (set (prime_spectrum R))) _ _
(λ s, zero_locus s) (λ t, vanishing_ideal t) :=
have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc,
by simpa [zero_locus_span, function.comp] using galois_connection.compose _ _ _ _ ideal_gc (gc R)
lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) :
t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t :=
(gc_set R) s t
end gc
-- TODO: we actually get the radical ideal,
-- but I think that isn't in mathlib yet.
lemma subset_vanishing_ideal_zero_locus (s : set R) :
s ⊆ vanishing_ideal (zero_locus s) :=
(gc_set R).le_u_l s
lemma le_vanishing_ideal_zero_locus (I : ideal R) :
I ≤ vanishing_ideal (zero_locus I) :=
(gc R).le_u_l I
lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) :
t ⊆ zero_locus (vanishing_ideal t) :=
(gc R).l_u_le t
lemma zero_locus_bot :
zero_locus ((⊥ : ideal R) : set R) = set.univ :=
(gc R).l_bot
@[simp] lemma zero_locus_singleton_zero :
zero_locus (0 : set R) = set.univ :=
zero_locus_bot
@[simp] lemma zero_locus_empty :
zero_locus (∅ : set R) = set.univ :=
(gc_set R).l_bot
@[simp] lemma vanishing_ideal_univ :
vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ :=
by simpa using (gc R).u_top
lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) :
zero_locus s = ∅ :=
begin
rw set.eq_empty_iff_forall_not_mem,
intros x hx,
rw mem_zero_locus at hx,
have x_prime : x.as_ideal.is_prime := by apply_instance,
have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h },
apply x_prime.1 eq_top,
end
lemma zero_locus_empty_iff_eq_top {I : ideal R} :
zero_locus (I : set R) = ∅ ↔ I = ⊤ :=
begin
split,
{ contrapose!,
intro h,
apply set.ne_empty_iff_nonempty.mpr,
rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩,
exact ⟨⟨M, hM.is_prime⟩, hIM⟩ },
{ rintro rfl, apply zero_locus_empty_of_one_mem, trivial }
end
@[simp] lemma zero_locus_univ :
zero_locus (set.univ : set R) = ∅ :=
zero_locus_empty_of_one_mem (set.mem_univ 1)
lemma zero_locus_sup (I J : ideal R) :
zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J :=
(gc R).l_sup
lemma zero_locus_union (s s' : set R) :
zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' :=
(gc_set R).l_sup
lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) :
vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' :=
(gc R).u_inf
lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) :
zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) :=
(gc R).l_supr
lemma zero_locus_Union {ι : Sort*} (s : ι → set R) :
zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) :=
(gc_set R).l_supr
lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) :
vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) :=
(gc R).u_infi
lemma zero_locus_inf (I J : ideal R) :
zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J :=
begin
ext x,
split,
{ rintro h,
rw set.mem_union,
simp only [mem_zero_locus] at h ⊢,
-- TODO: The rest of this proof should be factored out.
rw or_iff_not_imp_right,
intros hs r hr,
rw set.not_subset at hs,
rcases hs with ⟨s, hs1, hs2⟩,
apply (ideal.is_prime.mem_or_mem (by apply_instance) _).resolve_left hs2,
apply h,
exact ⟨I.mul_mem_left _ hr, J.mul_mem_right _ hs1⟩ },
{ rintro (h|h),
all_goals
{ rw mem_zero_locus at h ⊢,
refine set.subset.trans _ h,
intros r hr, cases hr, assumption } }
end
lemma union_zero_locus (s s' : set R) :
zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) :=
by { rw zero_locus_inf, simp }
lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) :
vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') :=
begin
intros r,
rw [submodule.mem_sup, mem_vanishing_ideal],
rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩,
rw mem_vanishing_ideal at hf hg,
apply submodule.add_mem; solve_by_elim
end
/-- The Zariski topology on the prime spectrum of a commutative ring
is defined via the closed sets of the topology:
they are exactly those sets that are the zero locus of a subset of the ring. -/
instance zariski_topology : topological_space (prime_spectrum R) :=
topological_space.of_closed (set.range prime_spectrum.zero_locus)
(⟨set.univ, by simp⟩)
begin
intros Zs h,
rw set.sInter_eq_Inter,
let f : Zs → set R := λ i, classical.some (h i.2),
have hf : ∀ i : Zs, ↑i = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm,
simp only [hf],
exact ⟨_, zero_locus_Union _⟩
end
(by { rintro _ _ ⟨s, rfl⟩ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ })
lemma is_open_iff (U : set (prime_spectrum R)) :
is_open U ↔ ∃ s, Uᶜ = zero_locus s :=
by simp only [@eq_comm _ Uᶜ]; refl
lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) :
is_closed Z ↔ ∃ s, Z = zero_locus s :=
by rw [is_closed, is_open_iff, set.compl_compl]
lemma is_closed_zero_locus (s : set R) :
is_closed (zero_locus s) :=
by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ }
section comap
variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S']
/-- The function between prime spectra of commutative rings induced by a ring homomorphism.
This function is continuous. -/
def comap (f : R →+* S) : prime_spectrum S → prime_spectrum R :=
λ y, ⟨ideal.comap f y.as_ideal, by exact ideal.is_prime.comap _⟩
variables (f : R →+* S)
@[simp] lemma comap_as_ideal (y : prime_spectrum S) :
(comap f y).as_ideal = ideal.comap f y.as_ideal :=
rfl
@[simp] lemma comap_id : comap (ring_hom.id R) = id :=
funext $ λ x, ext.mpr $ by { rw [comap_as_ideal], apply ideal.ext, intros r, simp }
@[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') :
comap (g.comp f) = comap f ∘ comap g :=
funext $ λ x, ext.mpr $ by { simp, refl }
@[simp] lemma preimage_comap_zero_locus (s : set R) :
(comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) :=
begin
ext x,
simp only [mem_zero_locus, set.mem_preimage, comap_as_ideal, set.image_subset_iff],
refl
end
lemma comap_continuous (f : R →+* S) : continuous (comap f) :=
begin
rw continuous_iff_is_closed,
simp only [is_closed_iff_zero_locus],
rintro _ ⟨s, rfl⟩,
exact ⟨_, preimage_comap_zero_locus f s⟩
end
end comap
lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) :
zero_locus (vanishing_ideal t : set R) = closure t :=
begin
apply set.subset.antisymm,
{ rintro x hx t' ⟨ht', ht⟩,
obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s,
by rwa [is_closed_iff_zero_locus] at ht',
rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht,
calc fs ⊆ vanishing_ideal t : ht
... ⊆ x.as_ideal : hx },
{ rw (is_closed_zero_locus _).closure_subset_iff,
exact subset_zero_locus_vanishing_ideal t }
end
/-- The prime spectrum of a commutative ring is a compact topological space. -/
instance : compact_space (prime_spectrum R) :=
begin
apply compact_space_of_finite_subfamily_closed,
intros ι Z hZc hZ,
let I : ι → ideal R := λ i, vanishing_ideal (Z i),
have hI : ∀ i, Z i = zero_locus (I i),
{ intro i,
rw [zero_locus_vanishing_ideal_eq_closure, is_closed.closure_eq],
exact hZc i },
have one_mem : (1:R) ∈ ⨆ (i : ι), I i,
{ rw [← ideal.eq_top_iff_one, ← zero_locus_empty_iff_eq_top, zero_locus_supr],
simpa only [hI] using hZ },
obtain ⟨s, hs⟩ : ∃ s : finset ι, (1:R) ∈ ⨆ i ∈ s, I i :=
submodule.exists_finset_of_mem_supr I one_mem,
show ∃ t : finset ι, (⋂ i ∈ t, Z i) = ∅,
use s,
rw [← ideal.eq_top_iff_one, ←zero_locus_empty_iff_eq_top] at hs,
simpa only [zero_locus_supr, hI] using hs
end
section basic_open
/-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/
def basic_open (r : R) : topological_space.opens (prime_spectrum R) :=
{ val := { x | r ∉ x.as_ideal },
property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ }
end basic_open
end prime_spectrum
|
d54f14d6161ed0c140c8f6719e6fc484f943d5eb | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/category_theory/limits/preserves/basic.lean | 2e66af9883a7ff36b11766623ed77116a939622d | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 16,198 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton, Bhavik Mehta
-/
import category_theory.limits.limits
/-!
# Preservation and reflection of (co)limits.
There are various distinct notions of "preserving limits". The one we
aim to capture here is: A functor F : C → D "preserves limits" if it
sends every limit cone in C to a limit cone in D. Informally, F
preserves all the limits which exist in C.
Note that:
* Of course, we do not want to require F to *strictly* take chosen
limit cones of C to chosen limit cones of D. Indeed, the above
definition makes no reference to a choice of limit cones so it makes
sense without any conditions on C or D.
* Some diagrams in C may have no limit. In this case, there is no
condition on the behavior of F on such diagrams. There are other
notions (such as "flat functor") which impose conditions also on
diagrams in C with no limits, but these are not considered here.
In order to be able to express the property of preserving limits of a
certain form, we say that a functor F preserves the limit of a
diagram K if F sends every limit cone on K to a limit cone. This is
vacuously satisfied when K does not admit a limit, which is consistent
with the above definition of "preserves limits".
-/
open category_theory
noncomputable theory
namespace category_theory.limits
universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [category.{v} C]
variables {D : Type u₂} [category.{v} D]
variables {J : Type v} [small_category J] {K : J ⥤ C}
/--
A functor `F` preserves limits of shape `K` (written as `preserves_limit K F`)
if `F` maps any limit cone over `K` to a limit cone.
-/
class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c))
/--
A functor `F` preserves colimits of shape `K` (written as `preserves_colimit K F`)
if `F` maps any colimit cocone over `K` to a colimit cocone.
-/
class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c))
/--
A functor which preserves limits preserves
the arbitrary choice of limit provided by `has_limit`, up to isomorphism.
-/
def preserves_limit_iso (K : J ⥤ C) [has_limit K] (F : C ⥤ D) [has_limit (K ⋙ F)] [preserves_limit K F] :
F.obj (limit K) ≅ limit (K ⋙ F) :=
is_limit.cone_point_unique_up_to_iso (preserves_limit.preserves (limit.is_limit K)) (limit.is_limit (K ⋙ F))
/--
A functor which preserves colimits preserves
the arbitrary choice of colimit provided by `has_colimit` up to isomorphism.
-/
def preserves_colimit_iso (K : J ⥤ C) [has_colimit K] (F : C ⥤ D) [has_colimit (K ⋙ F)] [preserves_colimit K F] :
F.obj (colimit K) ≅ colimit (K ⋙ F) :=
is_colimit.cocone_point_unique_up_to_iso (preserves_colimit.preserves (colimit.is_colimit K)) (colimit.is_colimit (K ⋙ F))
class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(preserves_limit : Π {K : J ⥤ C}, preserves_limit K F)
class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F)
class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F)
class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F)
attribute [instance, priority 100] -- see Note [lower instance priority]
preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape
preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape
instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) :=
by split; rintros ⟨a⟩ ⟨b⟩; congr
instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) :=
by split; rintros ⟨a⟩ ⟨b⟩; congr
instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) :
subsingleton (preserves_limits_of_shape J F) :=
by { split, intros, cases a, cases b, congr }
instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) :
subsingleton (preserves_colimits_of_shape J F) :=
by { split, intros, cases a, cases b, congr }
instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) :=
by { split, intros, cases a, cases b, cc }
instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) :=
by { split, intros, cases a, cases b, cc }
instance id_preserves_limits : preserves_limits (𝟭 C) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ K, by exactI ⟨λ c h,
⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩,
by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j,
by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } }
instance id_preserves_colimits : preserves_colimits (𝟭 C) :=
{ preserves_colimits_of_shape := λ J 𝒥,
{ preserves_colimit := λ K, by exactI ⟨λ c h,
⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩,
by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j,
by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } }
section
variables {E : Type u₃} [ℰ : category.{v} E]
variables (F : C ⥤ D) (G : D ⥤ E)
local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves
instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] :
preserves_limit K (F ⋙ G) :=
⟨λ c h, preserves_limit.preserves (preserves_limit.preserves h)⟩
instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] :
preserves_colimit K (F ⋙ G) :=
⟨λ c h, preserves_colimit.preserves (preserves_colimit.preserves h)⟩
end
/-- If F preserves one limit cone for the diagram K,
then it preserves any limit cone for K. -/
def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K}
(h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F :=
⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique_up_to_iso h h'))⟩
/-- Transfer preservation of limits along a natural isomorphism in the shape. -/
def preserves_limit_of_iso {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [preserves_limit K₁ F] :
preserves_limit K₂ F :=
{ preserves := λ c t,
begin
have t' := is_limit.of_right_adjoint (cones.postcompose_equivalence h).inverse t,
let hF := iso_whisker_right h F,
have := is_limit.of_right_adjoint (cones.postcompose_equivalence hF).functor
(preserves_limit.preserves t'),
apply is_limit.of_iso_limit this,
refine cones.ext (iso.refl _) (λ j, _),
dsimp,
rw [← F.map_comp],
simp,
end }
/-- If F preserves one colimit cocone for the diagram K,
then it preserves any colimit cocone for K. -/
def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K}
(h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F :=
⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique_up_to_iso h h'))⟩
/-- Transfer preservation of colimits along a natural isomorphism in the shape. -/
def preserves_colimit_of_iso {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [preserves_colimit K₁ F] :
preserves_colimit K₂ F :=
{ preserves := λ c t,
begin
have t' := is_colimit.of_left_adjoint (cocones.precompose_equivalence h).functor t,
let hF := iso_whisker_right h F,
have := is_colimit.of_left_adjoint (cocones.precompose_equivalence hF).inverse
(preserves_colimit.preserves t'),
apply is_colimit.of_iso_colimit this,
refine cocones.ext (iso.refl _) (λ j, _),
dsimp,
rw [← F.map_comp],
simp,
end }
/--
A functor `F : C ⥤ D` reflects limits for `K : J ⥤ C` if
whenever the image of a cone over `K` under `F` is a limit cone in `D`,
the cone was already a limit cone in `C`.
Note that we do not assume a priori that `D` actually has any limits.
-/
class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c)
/--
A functor `F : C ⥤ D` reflects colimits for `K : J ⥤ C` if
whenever the image of a cocone over `K` under `F` is a colimit cocone in `D`,
the cocone was already a colimit cocone in `C`.
Note that we do not assume a priori that `D` actually has any colimits.
-/
class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c)
/--
A functor `F : C ⥤ D` reflects limits of shape `J` if
whenever the image of a cone over some `K : J ⥤ C` under `F` is a limit cone in `D`,
the cone was already a limit cone in `C`.
Note that we do not assume a priori that `D` actually has any limits.
-/
class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(reflects_limit : Π {K : J ⥤ C}, reflects_limit K F)
/--
A functor `F : C ⥤ D` reflects colimits of shape `J` if
whenever the image of a cocone over some `K : J ⥤ C` under `F` is a colimit cocone in `D`,
the cocone was already a colimit cocone in `C`.
Note that we do not assume a priori that `D` actually has any colimits.
-/
class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) :=
(reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F)
/--
A functor `F : C ⥤ D` reflects limits if
whenever the image of a cone over some `K : J ⥤ C` under `F` is a limit cone in `D`,
the cone was already a limit cone in `C`.
Note that we do not assume a priori that `D` actually has any limits.
-/
class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F)
/--
A functor `F : C ⥤ D` reflects colimits if
whenever the image of a cocone over some `K : J ⥤ C` under `F` is a colimit cocone in `D`,
the cocone was already a colimit cocone in `C`.
Note that we do not assume a priori that `D` actually has any colimits.
-/
class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) :=
(reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F)
instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) :=
by split; rintros ⟨a⟩ ⟨b⟩; congr
instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) :=
by split; rintros ⟨a⟩ ⟨b⟩; congr
instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) :
subsingleton (reflects_limits_of_shape J F) :=
by { split, intros, cases a, cases b, congr }
instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) :
subsingleton (reflects_colimits_of_shape J F) :=
by { split, intros, cases a, cases b, congr }
instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) :=
by { split, intros, cases a, cases b, cc }
instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) :=
by { split, intros, cases a, cases b, cc }
@[priority 100] -- see Note [lower instance priority]
instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D)
[H : reflects_limits_of_shape J F] : reflects_limit K F :=
reflects_limits_of_shape.reflects_limit
@[priority 100] -- see Note [lower instance priority]
instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D)
[H : reflects_colimits_of_shape J F] : reflects_colimit K F :=
reflects_colimits_of_shape.reflects_colimit
@[priority 100] -- see Note [lower instance priority]
instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D)
[H : reflects_limits F] : reflects_limits_of_shape J F :=
reflects_limits.reflects_limits_of_shape
@[priority 100] -- see Note [lower instance priority]
instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D)
[H : reflects_colimits F] : reflects_colimits_of_shape J F :=
reflects_colimits.reflects_colimits_of_shape
instance id_reflects_limits : reflects_limits (𝟭 C) :=
{ reflects_limits_of_shape := λ J 𝒥,
{ reflects_limit := λ K, by exactI ⟨λ c h,
⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩,
by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j,
by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } }
instance id_reflects_colimits : reflects_colimits (𝟭 C) :=
{ reflects_colimits_of_shape := λ J 𝒥,
{ reflects_colimit := λ K, by exactI ⟨λ c h,
⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩,
by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j,
by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } }
section
variables {E : Type u₃} [ℰ : category.{v} E]
variables (F : C ⥤ D) (G : D ⥤ E)
instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] :
reflects_limit K (F ⋙ G) :=
⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩
instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] :
reflects_colimit K (F ⋙ G) :=
⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩
/-- If `F ⋙ G` preserves limits for `K`, and `G` reflects limits for `K ⋙ F`,
then `F` preserves limits for `K`. -/
def preserves_limit_of_reflects_of_preserves [preserves_limit K (F ⋙ G)]
[reflects_limit (K ⋙ F) G] : preserves_limit K F :=
⟨λ c h,
begin
apply @reflects_limit.reflects _ _ _ _ _ _ _ G,
change limits.is_limit ((F ⋙ G).map_cone c),
exact preserves_limit.preserves h
end⟩
/-- If `F ⋙ G` preserves colimits for `K`, and `G` reflects colimits for `K ⋙ F`,
then `F` preserves colimits for `K`. -/
def preserves_colimit_of_reflects_of_preserves [preserves_colimit K (F ⋙ G)]
[reflects_colimit (K ⋙ F) G] : preserves_colimit K F :=
⟨λ c h,
begin
apply @reflects_colimit.reflects _ _ _ _ _ _ _ G,
change limits.is_colimit ((F ⋙ G).map_cocone c),
exact preserves_colimit.preserves h
end⟩
end
variable (F : C ⥤ D)
/-- A fully faithful functor reflects limits. -/
def fully_faithful_reflects_limits [full F] [faithful F] : reflects_limits F :=
{ reflects_limits_of_shape := λ J 𝒥₁, by exactI
{ reflects_limit := λ K,
{ reflects := λ c t,
is_limit.mk_cone_morphism (λ s, (cones.functoriality K F).preimage (t.lift_cone_morphism _)) $
begin
apply (λ s m, (cones.functoriality K F).map_injective _),
rw [functor.image_preimage],
apply t.uniq_cone_morphism,
end } } }
/-- A fully faithful functor reflects colimits. -/
def fully_faithful_reflects_colimits [full F] [faithful F] : reflects_colimits F :=
{ reflects_colimits_of_shape := λ J 𝒥₁, by exactI
{ reflects_colimit := λ K,
{ reflects := λ c t,
is_colimit.mk_cocone_morphism (λ s, (cocones.functoriality K F).preimage (t.desc_cocone_morphism _)) $
begin
apply (λ s m, (cocones.functoriality K F).map_injective _),
rw [functor.image_preimage],
apply t.uniq_cocone_morphism,
end } } }
end category_theory.limits
|
ecd7cb03efd01f35aebef73ce5f141ccaad1e5ef | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/sym/sym2.lean | 2e911abd94b8b1a9d1ef6c131fa38d4a8c06997a | [
"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 | 19,984 | lean | /-
Copyright (c) 2020 Kyle Miller All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import data.sym.basic
import tactic.linarith
/-!
# The symmetric square
This file defines the symmetric square, which is `α × α` modulo
swapping. This is also known as the type of unordered pairs.
More generally, the symmetric square is the second symmetric power
(see `data.sym.basic`). The equivalence is `sym2.equiv_sym`.
From the point of view that an unordered pair is equivalent to a
multiset of cardinality two (see `sym2.equiv_multiset`), there is a
`has_mem` instance `sym2.mem`, which is a `Prop`-valued membership
test. Given `h : a ∈ z` for `z : sym2 α`, then `h.other` is the other
element of the pair, defined using `classical.choice`. If `α` has
decidable equality, then `h.other'` computably gives the other element.
The universal property of `sym2` is provided as `sym2.lift`, which
states that functions from `sym2 α` are equivalent to symmetric
two-argument functions from `α`.
Recall that an undirected graph (allowing self loops, but no multiple
edges) is equivalent to a symmetric relation on the vertex type `α`.
Given a symmetric relation on `α`, the corresponding edge set is
constructed by `sym2.from_rel` which is a special case of `sym2.lift`.
## Notation
The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a
term of the symmetric square.
## Tags
symmetric square, unordered pairs, symmetric powers
-/
open finset fintype function sym
universe u
variables {α β γ : Type*}
namespace sym2
/--
This is the relation capturing the notion of pairs equivalent up to permutations.
-/
inductive rel (α : Type u) : (α × α) → (α × α) → Prop
| refl (x y : α) : rel (x, y) (x, y)
| swap (x y : α) : rel (x, y) (y, x)
attribute [refl] rel.refl
@[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x :=
by rintro ⟨_, _⟩; constructor
@[trans] lemma rel.trans {x y z : α × α} (a : rel α x y) (b : rel α y z) : rel α x z :=
by { cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap }
lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption
instance rel.setoid (α : Type u) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩
end sym2
/--
`sym2 α` is the symmetric square of `α`, which, in other words, is the
type of unordered pairs.
It is equivalent in a natural way to multisets of cardinality 2 (see
`sym2.equiv_multiset`).
-/
@[reducible]
def sym2 (α : Type u) := quotient (sym2.rel.setoid α)
namespace sym2
@[elab_as_eliminator]
protected lemma ind {f : sym2 α → Prop} (h : ∀ x y, f ⟦(x, y)⟧) : ∀ i, f i :=
quotient.ind $ prod.rec $ by exact h
@[elab_as_eliminator]
protected lemma induction_on {f : sym2 α → Prop} (i : sym2 α) (hf : ∀ x y, f ⟦(x,y)⟧) : f i :=
i.ind hf
protected lemma «exists» {α : Sort*} {f : sym2 α → Prop} :
(∃ (x : sym2 α), f x) ↔ ∃ x y, f ⟦(x, y)⟧ :=
(surjective_quotient_mk _).exists.trans prod.exists
protected lemma «forall» {α : Sort*} {f : sym2 α → Prop} :
(∀ (x : sym2 α), f x) ↔ ∀ x y, f ⟦(x, y)⟧ :=
(surjective_quotient_mk _).forall.trans prod.forall
lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ :=
by { rw quotient.eq, apply rel.swap }
@[simp] lemma mk_prod_swap_eq {p : α × α} : ⟦p.swap⟧ = ⟦p⟧ :=
by { cases p, exact eq_swap }
lemma congr_right {a b c : α} : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c :=
by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h }
lemma congr_left {a b c : α} : ⟦(b, a)⟧ = ⟦(c, a)⟧ ↔ b = c :=
by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h }
lemma eq_iff {x y z w : α} :
⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) :=
begin
split; intro h,
{ rw quotient.eq at h, cases h; tidy },
{ cases h; rw [h.1, h.2], rw eq_swap }
end
lemma mk_eq_mk_iff {p q : α × α} :
⟦p⟧ = ⟦q⟧ ↔ p = q ∨ p = q.swap :=
by { cases p, cases q, simp only [eq_iff, prod.mk.inj_iff, prod.swap_prod_mk] }
/-- The universal property of `sym2`; symmetric functions of two arguments are equivalent to
functions from `sym2`. Note that when `β` is `Prop`, it can sometimes be more convenient to use
`sym2.from_rel` instead. -/
def lift : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁} ≃ (sym2 α → β) :=
{ to_fun := λ f, quotient.lift (uncurry ↑f) $ by { rintro _ _ ⟨⟩, exacts [rfl, f.prop _ _] },
inv_fun := λ F, ⟨curry (F ∘ quotient.mk), λ a₁ a₂, congr_arg F eq_swap⟩,
left_inv := λ f, subtype.ext rfl,
right_inv := λ F, funext $ sym2.ind $ by exact λ x y, rfl }
@[simp]
lemma lift_mk (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) (a₁ a₂ : α) :
lift f ⟦(a₁, a₂)⟧ = (f : α → α → β) a₁ a₂ := rfl
@[simp]
lemma coe_lift_symm_apply (F : sym2 α → β) (a₁ a₂ : α) :
(lift.symm F : α → α → β) a₁ a₂ = F ⟦(a₁, a₂)⟧ := rfl
/--
The functor `sym2` is functorial, and this function constructs the induced maps.
-/
def map (f : α → β) : sym2 α → sym2 β :=
quotient.map (prod.map f f)
(by { rintros _ _ h, cases h, { refl }, apply rel.swap })
@[simp] lemma map_id : map (@id α) = id := by { ext ⟨⟨x,y⟩⟩, refl }
lemma map_comp {g : β → γ} {f : α → β} : sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f :=
by { ext ⟨⟨x, y⟩⟩, refl }
lemma map_map {g : β → γ} {f : α → β} (x : sym2 α) :
map g (map f x) = map (g ∘ f) x := by tidy
@[simp]
lemma map_pair_eq (f : α → β) (x y : α) : map f ⟦(x, y)⟧ = ⟦(f x, f y)⟧ := rfl
lemma map.injective {f : α → β} (hinj : injective f) : injective (map f) :=
begin
intros z z',
refine quotient.ind₂ (λ z z', _) z z',
cases z with x y,
cases z' with x' y',
repeat { rw [map_pair_eq, eq_iff] },
rintro (h|h); simp [hinj h.1, hinj h.2],
end
section membership
/-! ### Declarations about membership -/
/--
This is a predicate that determines whether a given term is a member of a term of the
symmetric square. From this point of view, the symmetric square is the subtype of
cardinality-two multisets on `α`.
-/
def mem (x : α) (z : sym2 α) : Prop :=
∃ (y : α), z = ⟦(x, y)⟧
instance : has_mem α (sym2 α) := ⟨mem⟩
lemma mem_mk_left (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩
lemma mem_mk_right (x y : α) : y ∈ ⟦(x, y)⟧ := eq_swap.subst $ mem_mk_left y x
@[simp] lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c :=
{ mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy },
mpr := by { rintro ⟨_⟩; subst a, { apply mem_mk_left }, apply mem_mk_right } }
lemma out_fst_mem (e : sym2 α) : e.out.1 ∈ e := ⟨e.out.2, by rw [prod.mk.eta, e.out_eq]⟩
lemma out_snd_mem (e : sym2 α) : e.out.2 ∈ e := ⟨e.out.1, by rw [eq_swap, prod.mk.eta, e.out_eq]⟩
lemma ball {p : α → Prop} {a b : α} : (∀ c ∈ ⟦(a, b)⟧, p c) ↔ p a ∧ p b :=
begin
refine ⟨λ h, ⟨h _ $ mem_mk_left _ _, h _ $ mem_mk_right _ _⟩, λ h c hc, _⟩,
obtain rfl | rfl := sym2.mem_iff.1 hc,
{ exact h.1 },
{ exact h.2 }
end
/--
Given an element of the unordered pair, give the other element using `classical.some`.
See also `mem.other'` for the computable version.
-/
noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α :=
classical.some h
@[simp]
lemma other_spec {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other)⟧ = z :=
by erw ← classical.some_spec h
lemma other_mem {a : α} {z : sym2 α} (h : a ∈ z) : h.other ∈ z :=
by { convert mem_mk_right a h.other, rw other_spec h }
lemma mem_and_mem_iff {x y : α} {z : sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = ⟦(x, y)⟧ :=
begin
split,
{ induction z using sym2.ind with x' y',
rw [mem_iff, mem_iff],
rintro ⟨rfl | rfl, rfl | rfl⟩;
try { trivial };
simp only [sym2.eq_swap] },
{ rintro rfl, simp },
end
lemma eq_of_ne_mem {x y : α} {z z' : sym2 α} (h : x ≠ y)
(h1 : x ∈ z) (h2 : y ∈ z) (h3 : x ∈ z') (h4 : y ∈ z') : z = z' :=
((mem_and_mem_iff h).mp ⟨h1, h2⟩).trans ((mem_and_mem_iff h).mp ⟨h3, h4⟩).symm
@[ext]
protected lemma ext (z z' : sym2 α) (h : ∀ x, x ∈ z ↔ x ∈ z') : z = z' :=
begin
induction z using sym2.ind with x y,
induction z' using sym2.ind with x' y',
have hx := h x, have hy := h y, have hx' := h x', have hy' := h y',
simp only [mem_iff, eq_self_iff_true, or_true, iff_true, true_or, true_iff] at hx hy hx' hy',
cases hx; cases hy; cases hx'; cases hy'; subst_vars,
simp only [sym2.eq_swap],
end
instance mem.decidable [decidable_eq α] (x : α) (z : sym2 α) : decidable (x ∈ z) :=
quotient.rec_on_subsingleton z (λ ⟨y₁, y₂⟩, decidable_of_iff' _ mem_iff)
end membership
@[simp] lemma mem_map {f : α → β} {b : β} {z : sym2 α} :
b ∈ sym2.map f z ↔ ∃ a, a ∈ z ∧ f a = b :=
begin
induction z using sym2.ind with x y,
simp only [map, quotient.map_mk, prod.map_mk, mem_iff],
split,
{ rintro (rfl | rfl),
{ exact ⟨x, by simp⟩, },
{ exact ⟨y, by simp⟩, } },
{ rintro ⟨w, rfl | rfl, rfl⟩; simp, },
end
@[congr] lemma map_congr {f g : α → β} {s : sym2 α} (h : ∀ x ∈ s, f x = g x) :
map f s = map g s :=
begin
ext y,
simp only [mem_map],
split; { rintro ⟨w, hw, rfl⟩, exact ⟨w, hw, by simp [hw, h]⟩ },
end
/-- Note: `sym2.map_id` will not simplify `sym2.map id z` due to `sym2.map_congr`. -/
@[simp] lemma map_id' : map (λ (x : α), x) = id := map_id
/-! ### Diagonal -/
/--
A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image
of this diagonal in `sym2 α`.
-/
def diag (x : α) : sym2 α := ⟦(x, x)⟧
lemma diag_injective : function.injective (sym2.diag : α → sym2 α) :=
λ x y h, by cases quotient.exact h; refl
/--
A predicate for testing whether an element of `sym2 α` is on the diagonal.
-/
def is_diag : sym2 α → Prop :=
lift ⟨eq, λ _ _, propext eq_comm⟩
lemma mk_is_diag_iff {x y : α} : is_diag ⟦(x, y)⟧ ↔ x = y := iff.rfl
@[simp]
lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 :=
prod.rec_on z $ λ _ _, mk_is_diag_iff
@[simp]
lemma diag_is_diag (a : α) : is_diag (diag a) := eq.refl a
lemma is_diag.mem_range_diag {z : sym2 α} : is_diag z → z ∈ set.range (@diag α) :=
begin
induction z using sym2.ind with x y,
rintro (rfl : x = y),
exact ⟨_, rfl⟩,
end
lemma is_diag_iff_mem_range_diag (z : sym2 α) : is_diag z ↔ z ∈ set.range (@diag α) :=
⟨is_diag.mem_range_diag, λ ⟨i, hi⟩, hi ▸ diag_is_diag i⟩
instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) :=
by { refine λ z, quotient.rec_on_subsingleton z (λ a, _), erw is_diag_iff_proj_eq, apply_instance }
lemma other_ne {a : α} {z : sym2 α} (hd : ¬is_diag z) (h : a ∈ z) : h.other ≠ a :=
begin
contrapose! hd,
have h' := sym2.other_spec h,
rw hd at h',
rw ←h',
simp,
end
section relations
/-! ### Declarations about symmetric relations -/
variables {r : α → α → Prop}
/--
Symmetric relations define a set on `sym2 α` by taking all those pairs
of elements that are related.
-/
def from_rel (sym : symmetric r) : set (sym2 α) :=
set_of (lift ⟨r, λ x y, propext ⟨λ h, sym h, λ h, sym h⟩⟩)
@[simp]
lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} : ⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := iff.rfl
@[simp]
lemma from_rel_prop {sym : symmetric r} {a b : α} : ⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := iff.rfl
lemma from_rel_irreflexive {sym : symmetric r} :
irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z :=
{ mp := λ h, sym2.ind $ by { rintros a b hr (rfl : a = b), exact h _ hr },
mpr := λ h x hr, h (from_rel_prop.mpr hr) rfl }
lemma mem_from_rel_irrefl_other_ne {sym : symmetric r} (irrefl : irreflexive r)
{a : α} {z : sym2 α} (hz : z ∈ from_rel sym) (h : a ∈ z) : h.other ≠ a :=
other_ne (from_rel_irreflexive.mp irrefl hz) h
instance from_rel.decidable_pred (sym : symmetric r) [h : decidable_rel r] :
decidable_pred (∈ sym2.from_rel sym) :=
λ z, quotient.rec_on_subsingleton z (λ x, h _ _)
/-- The inverse to `sym2.from_rel`. Given a set on `sym2 α`, give a symmetric relation on `α`
(see `sym2.to_rel_symmetric`). -/
def to_rel (s : set (sym2 α)) (x y : α) : Prop := ⟦(x, y)⟧ ∈ s
@[simp] lemma to_rel_prop (s : set (sym2 α)) (x y : α) : to_rel s x y ↔ ⟦(x, y)⟧ ∈ s := iff.rfl
lemma to_rel_symmetric (s : set (sym2 α)) : symmetric (to_rel s) := λ x y, by simp [eq_swap]
lemma to_rel_from_rel (sym : symmetric r) : to_rel (from_rel sym) = r := rfl
lemma from_rel_to_rel (s : set (sym2 α)) : from_rel (to_rel_symmetric s) = s :=
set.ext (λ z, sym2.ind (λ x y, iff.rfl) z)
end relations
section sym_equiv
/-! ### Equivalence to the second symmetric power -/
local attribute [instance] vector.perm.is_setoid
private def from_vector : vector α 2 → α × α
| ⟨[a, b], h⟩ := (a, b)
private lemma perm_card_two_iff {a₁ b₁ a₂ b₂ : α} :
[a₁, b₁].perm [a₂, b₂] ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ a₁ = b₂ ∧ b₁ = a₂ :=
{ mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy },
mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } }
/--
The symmetric square is equivalent to length-2 vectors up to permutations.
-/
def sym2_equiv_sym' : equiv (sym2 α) (sym' α 2) :=
{ to_fun := quotient.map
(λ (x : α × α), ⟨[x.1, x.2], rfl⟩)
(by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }),
inv_fun := quotient.map from_vector (begin
rintros ⟨x, hx⟩ ⟨y, hy⟩ h,
cases x with _ x, { simpa using hx, },
cases x with _ x, { simpa using hx, },
cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] },
cases y with _ y, { simpa using hy, },
cases y with _ y, { simpa using hy, },
cases y with _ y, swap, { exfalso, simp at hy, linarith [hy] },
rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl },
apply sym2.rel.swap,
end),
left_inv := by tidy,
right_inv := λ x, begin
refine quotient.rec_on_subsingleton x (λ x, _),
{ cases x with x hx,
cases x with _ x, { simpa using hx, },
cases x with _ x, { simpa using hx, },
cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] },
refl },
end }
/--
The symmetric square is equivalent to the second symmetric power.
-/
def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 :=
equiv.trans sym2_equiv_sym' sym_equiv_sym'.symm
/--
The symmetric square is equivalent to multisets of cardinality
two. (This is currently a synonym for `equiv_sym`, but it's provided
in case the definition for `sym` changes.)
-/
def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} :=
equiv_sym α
end sym_equiv
section decidable
/--
An algorithm for computing `sym2.rel`.
-/
def rel_bool [decidable_eq α] (x y : α × α) : bool :=
if x.1 = y.1 then x.2 = y.2 else
if x.1 = y.2 then x.2 = y.1 else ff
lemma rel_bool_spec [decidable_eq α] (x y : α × α) : ↥(rel_bool x y) ↔ rel α x y :=
begin
cases x with x₁ x₂, cases y with y₁ y₂,
dsimp [rel_bool], split_ifs;
simp only [false_iff, bool.coe_sort_ff, bool.of_to_bool_iff],
rotate 2, { contrapose! h, cases h; cc },
all_goals { subst x₁, split; intro h1,
{ subst h1; apply sym2.rel.swap },
{ cases h1; cc } }
end
/--
Given `[decidable_eq α]` and `[fintype α]`, the following instance gives `fintype (sym2 α)`.
-/
instance (α : Type*) [decidable_eq α] : decidable_rel (sym2.rel α) :=
λ x y, decidable_of_bool (rel_bool x y) (rel_bool_spec x y)
/-! ### The other element of an element of the symmetric square -/
/--
A function that gives the other element of a pair given one of the elements. Used in `mem.other'`.
-/
private def pair_other [decidable_eq α] (a : α) (z : α × α) : α := if a = z.1 then z.2 else z.1
/--
Get the other element of the unordered pair using the decidable equality.
This is the computable version of `mem.other`.
-/
def mem.other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : α :=
quot.rec (λ x h', pair_other a x) (begin
clear h z,
intros x y h,
ext hy,
convert_to pair_other a x = _,
{ have h' : ∀ {c e h}, @eq.rec _ ⟦x⟧ (λ s, a ∈ s → α)
(λ _, pair_other a x) c e h = pair_other a x,
{ intros _ e _, subst e },
apply h', },
have h' := (rel_bool_spec x y).mpr h,
cases x with x₁ x₂, cases y with y₁ y₂,
cases mem_iff.mp hy with hy'; subst a; dsimp [rel_bool] at h';
split_ifs at h'; try { rw bool.of_to_bool_iff at h', subst x₁, subst x₂ }; dsimp [pair_other],
simp only [ne.symm h_1, if_true, eq_self_iff_true, if_false],
exfalso, exact bool.not_ff h',
simp only [h_1, if_true, eq_self_iff_true, if_false],
exfalso, exact bool.not_ff h',
end) z h
@[simp]
lemma other_spec' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other')⟧ = z :=
begin
induction z, cases z with x y,
have h' := mem_iff.mp h,
dsimp [mem.other', quot.rec, pair_other],
cases h'; subst a,
{ simp only [if_true, eq_self_iff_true], refl, },
{ split_ifs, subst h_1, refl, rw eq_swap, refl, },
refl,
end
@[simp]
lemma other_eq_other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other = h.other' :=
by rw [←congr_right, other_spec' h, other_spec]
lemma other_mem' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other' ∈ z :=
by { rw ←other_eq_other', exact other_mem h }
lemma other_invol' [decidable_eq α] {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other' ∈ z) :
hb.other' = a :=
begin
induction z, cases z with x y,
dsimp [mem.other', quot.rec, pair_other] at hb,
split_ifs at hb; dsimp [mem.other', quot.rec, pair_other],
simp only [h, if_true, eq_self_iff_true],
split_ifs, assumption, refl,
simp only [h, if_false, if_true, eq_self_iff_true],
exact ((mem_iff.mp ha).resolve_left h).symm,
refl,
end
lemma other_invol {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other ∈ z) : hb.other = a :=
begin
classical,
rw other_eq_other' at hb ⊢,
convert other_invol' ha hb,
rw other_eq_other',
end
lemma filter_image_quotient_mk_is_diag [decidable_eq α] (s : finset α) :
((s.product s).image quotient.mk).filter is_diag = s.diag.image quotient.mk :=
begin
ext z,
induction z using quotient.induction_on,
rcases z with ⟨x, y⟩,
simp only [mem_image, mem_diag, exists_prop, mem_filter, prod.exists, mem_product],
split,
{ rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩,
rw [←h, sym2.mk_is_diag_iff] at hab,
exact ⟨a, b, ⟨ha, hab⟩, h⟩ },
{ rintro ⟨a, b, ⟨ha, rfl⟩, h⟩,
rw ←h,
exact ⟨⟨a, a, ⟨ha, ha⟩, rfl⟩, rfl⟩ }
end
lemma filter_image_quotient_mk_not_is_diag [decidable_eq α] (s : finset α) :
((s.product s).image quotient.mk).filter (λ a : sym2 α, ¬a.is_diag) =
s.off_diag.image quotient.mk :=
begin
ext z,
induction z using quotient.induction_on,
rcases z with ⟨x, y⟩,
simp only [mem_image, mem_off_diag, exists_prop, mem_filter, prod.exists, mem_product],
split,
{ rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩,
rw [←h, sym2.mk_is_diag_iff] at hab,
exact ⟨a, b, ⟨ha, hb, hab⟩, h⟩ },
{ rintro ⟨a, b, ⟨ha, hb, hab⟩, h⟩,
rw [ne.def, ←sym2.mk_is_diag_iff, h] at hab,
exact ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩ }
end
end decidable
instance [subsingleton α] : subsingleton (sym2 α) :=
(equiv_sym α).injective.subsingleton
instance [unique α] : unique (sym2 α) := unique.mk' _
instance [is_empty α] : is_empty (sym2 α) := (equiv_sym α).is_empty
instance [nontrivial α] : nontrivial (sym2 α) := diag_injective.nontrivial
end sym2
|
bc62a94c390e819ac1200c7fdd61aef6911b57c6 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/deps/x86_semantics/src/x86_semantics/buffer_map.lean | ca8ae5028c29c04cf203762d70f63bf13d6f2b7f | [
"Apache-2.0"
] | permissive | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 2,208 | lean | /- A map from indexes onto buffers -/
import data.buffer
structure {u v} buffer_map.entry (k : Type u) (val : Type v) : Type (max u v) :=
(start : k)
(value : buffer val)
-- distance here is essentially subtraction. distance k k' < 0 iff k < k'
structure {u v} buffer_map (k : Type u) (val : Type v) (distance : k -> k -> ℤ) :=
(entries : list (buffer_map.entry k val) )
namespace buffer_map
section
universes u v
parameters {k : Type u} {val : Type v} {distance : k -> k -> ℤ}
/- construction -/
def empty : buffer_map k val distance := buffer_map.mk distance []
/- lookup -/
def in_entry (key : k) (e : entry k val) : Prop :=
distance key e.start ≥ 0 ∧ int.nat_abs (distance key e.start) < e.value.size
def entry_idx (key : k) (e : entry k val) : option (fin e.value.size) :=
if H : distance key e.start ≥ 0 ∧ int.nat_abs (distance key e.start) < e.value.size
then some (fin.mk _ H.right)
else none
protected
def lookup' : list (buffer_map.entry k val) -> k -> option val
| [] _ := none
| (e :: m) key :=
match entry_idx key e with
| none := lookup' m key
| (some idx) := some (e.value.read idx)
end
def lookup (m : buffer_map k val distance) := lookup' m.entries
protected
def lookup_buffer' : list (buffer_map.entry k val) -> k -> option (k × buffer val)
| [] _ := none
| (e :: m) key :=
match entry_idx key e with
| none := lookup_buffer' m key
| (some idx) := some (e.start, e.value)
end
def lookup_buffer (m : buffer_map k val distance) := lookup_buffer' m.entries
/- insertion -/
-- FIXME: add overlap check
def insert (m : buffer_map k val distance) (start : k) (value : buffer val) : buffer_map k val distance :=
buffer_map.mk distance ({ start := start, value := value } :: m.entries)
end
end buffer_map
section
universes u v
parameters {k : Type u} {val : Type v} {distance : k -> k -> ℤ} [has_repr k]
instance : has_repr (buffer_map.entry k val) :=
⟨λe, "( [" ++ repr e.start ++ " ..+ " ++ repr e.value.size ++ "]" /-" -> " ++ has_repr.repr e.value -/ ++ ")"⟩
instance : has_repr (buffer_map k val distance) := ⟨λm, repr m.entries ⟩
end
|
12f2366f24b8e4245bf7016f8d4f175fdf1dde4c | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/order_iso_nat.lean | 7ec8311fd87e03bb4647b1d5e64cc12249a35419 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 5,999 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.nat.basic
import data.equiv.denumerable
import data.set.finite
import order.rel_iso
import logic.function.iterate
namespace rel_embedding
variables {α : Type*} {r : α → α → Prop} [is_strict_order α r]
/-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/
def nat_lt (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) :
((<) : ℕ → ℕ → Prop) ↪r r :=
of_monotone f $ λ a b h, begin
induction b with b IH, {exact (nat.not_lt_zero _ h).elim},
cases nat.lt_succ_iff_lt_or_eq.1 h with h e,
{ exact trans (IH h) (H _) },
{ subst b, apply H }
end
@[simp]
lemma nat_lt_apply {f : ℕ → α} {H : ∀ n:ℕ, r (f n) (f (n+1))} {n : ℕ} : nat_lt f H n = f n := rfl
/-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/
def nat_gt (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) :
((>) : ℕ → ℕ → Prop) ↪r r :=
by haveI := is_strict_order.swap r; exact rel_embedding.swap (nat_lt f H)
theorem well_founded_iff_no_descending_seq :
well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ↪r r) :=
⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩,
suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl,
λ a ac, begin
induction ac with a _ IH, intros n h, subst a,
exact IH (f (n+1)) (o.2 (nat.lt_succ_self _)) _ rfl
end,
λ N, ⟨λ a, classical.by_contradiction $ λ na,
let ⟨f, h⟩ := classical.axiom_of_choice $
show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1,
from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $
⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in
N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n,
by { rw [function.iterate_succ'], apply h }⟩⟩⟩
end rel_embedding
namespace nat
variables (s : set ℕ) [decidable_pred s] [infinite s]
/-- An order embedding from `ℕ` to itself with a specified range -/
def order_embedding_of_set : ℕ ↪o ℕ :=
(rel_embedding.order_embedding_of_lt_embedding
(rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))).trans
(order_embedding.subtype s)
/-- `nat.subtype.of_nat` as an order isomorphism between `ℕ` and an infinite decidable subset. -/
noncomputable def subtype.order_iso_of_nat :
ℕ ≃o s :=
rel_iso.of_surjective (rel_embedding.order_embedding_of_lt_embedding
(rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _)))
nat.subtype.of_nat_surjective
variable {s}
@[simp]
lemma order_embedding_of_set_apply {n : ℕ} : order_embedding_of_set s n = subtype.of_nat s n :=
rfl
@[simp]
lemma subtype.order_iso_of_nat_apply {n : ℕ} :
subtype.order_iso_of_nat s n = subtype.of_nat s n :=
by { simp [subtype.order_iso_of_nat] }
variable (s)
@[simp]
lemma order_embedding_of_set_range : set.range (nat.order_embedding_of_set s) = s :=
begin
ext x,
rw [set.mem_range, nat.order_embedding_of_set],
split; intro h,
{ rcases h with ⟨y, rfl⟩,
simp },
{ refine ⟨(nat.subtype.order_iso_of_nat s).symm ⟨x, h⟩, _⟩,
simp only [rel_embedding.coe_trans, rel_embedding.order_embedding_of_lt_embedding_apply,
rel_embedding.nat_lt_apply, function.comp_app, order_embedding.coe_subtype],
rw [← subtype.order_iso_of_nat_apply, order_iso.apply_symm_apply, subtype.coe_mk] }
end
end nat
theorem exists_increasing_or_nonincreasing_subseq' {α : Type*} (r : α → α → Prop) (f : ℕ → α) :
∃ (g : ℕ ↪o ℕ), (∀ n : ℕ, r (f (g n)) (f (g (n + 1)))) ∨
(∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) :=
begin
classical,
let bad : set ℕ := { m | ∀ n, m < n → ¬ r (f m) (f n) },
by_cases hbad : infinite bad,
{ haveI := hbad,
refine ⟨nat.order_embedding_of_set bad, or.intro_right _ (λ m n mn, _)⟩,
have h := set.mem_range_self m,
rw nat.order_embedding_of_set_range bad at h,
exact h _ ((order_embedding.lt_iff_lt _).2 mn) },
{ rw [set.infinite_coe_iff, set.infinite, not_not] at hbad,
obtain ⟨m, hm⟩ : ∃ m, ∀ n, m ≤ n → ¬ n ∈ bad,
{ by_cases he : hbad.to_finset.nonempty,
{ refine ⟨(hbad.to_finset.max' he).succ, λ n hn nbad, nat.not_succ_le_self _
(hn.trans (hbad.to_finset.le_max' n (hbad.mem_to_finset.2 nbad)))⟩ },
{ exact ⟨0, λ n hn nbad, he ⟨n, hbad.mem_to_finset.2 nbad⟩⟩ } },
have h : ∀ (n : ℕ), ∃ (n' : ℕ), n < n' ∧ r (f (n + m)) (f (n' + m)),
{ intro n,
have h := hm _ (le_add_of_nonneg_left n.zero_le),
simp only [exists_prop, not_not, set.mem_set_of_eq, not_forall] at h,
obtain ⟨n', hn1, hn2⟩ := h,
obtain ⟨x, hpos, rfl⟩ := exists_pos_add_of_lt hn1,
refine ⟨n + x, add_lt_add_left hpos n, _⟩,
rw [add_assoc, add_comm x m, ← add_assoc],
exact hn2 },
let g' : ℕ → ℕ := @nat.rec (λ _, ℕ) m (λ n gn, nat.find (h gn)),
exact ⟨(rel_embedding.nat_lt (λ n, g' n + m)
(λ n, nat.add_lt_add_right (nat.find_spec (h (g' n))).1 m)).order_embedding_of_lt_embedding,
or.intro_left _ (λ n, (nat.find_spec (h (g' n))).2)⟩ }
end
theorem exists_increasing_or_nonincreasing_subseq
{α : Type*} (r : α → α → Prop) [is_trans α r] (f : ℕ → α) :
∃ (g : ℕ ↪o ℕ), (∀ m n : ℕ, m < n → r (f (g m)) (f (g n))) ∨
(∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) :=
begin
obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f,
{ refine ⟨g, or.intro_left _ (λ m n mn, _)⟩,
obtain ⟨x, rfl⟩ := le_iff_exists_add.1 (nat.succ_le_iff.2 mn),
induction x with x ih,
{ apply hr },
{ apply is_trans.trans _ _ _ _ (hr _),
exact ih (lt_of_lt_of_le m.lt_succ_self (nat.le_add_right _ _)) } },
{ exact ⟨g, or.intro_right _ hnr⟩ }
end
|
639e48745c59f0fd3053918e9d0985986659d13d | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/analysis/asymptotics.lean | 0cd42ba902e742bcffc5b3c04ba92e79cbf6d57a | [
"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 | 29,388 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
We introduce these relations:
`is_O f g l` : "f is big O of g along l"
`is_o f g l` : "f is little o of g along l"
Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains
of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with
these types, and it is the norm that is compared asymptotically.
Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute
value. In general, we have
`is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`,
and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions
to the integers, rationals, complex numbers, or any normed vector space without mentioning the
norm explicitly.
If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always
nonzero, we have
`is_o f g l ↔ tendsto (λ x, f x / (g x)) (𝓝 0) l`.
In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction
it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining
the Fréchet derivative.)
-/
import analysis.normed_space.basic
open filter
open_locale topological_space
namespace asymptotics
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section
variables [has_norm β] [has_norm γ] [has_norm δ]
def is_O (f : α → β) (g : α → γ) (l : filter α) : Prop :=
∃ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l
def is_o (f : α → β) (g : α → γ) (l : filter α) : Prop :=
∀ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l
theorem is_O_refl (f : α → β) (l : filter α) : is_O f f l :=
⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩
theorem is_O.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_O f g l)
{δ : Type*} (k : δ → α) :
is_O (f ∘ k) (g ∘ k) (l.comap k) :=
let ⟨c, cpos, hfgc⟩ := hfg in
⟨c, cpos, mem_comap_sets.mpr ⟨_, hfgc, set.subset.refl _⟩⟩
theorem is_o.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_o f g l)
{δ : Type*} (k : δ → α) :
is_o (f ∘ k) (g ∘ k) (l.comap k) :=
λ c cpos, mem_comap_sets.mpr ⟨_, hfg c cpos, set.subset.refl _⟩
theorem is_O.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂)
(h' : is_O f g l₂) : is_O f g l₁ :=
let ⟨c, cpos, h'c⟩ := h' in ⟨c, cpos, h (h'c)⟩
theorem is_o.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂)
(h' : is_o f g l₂) : is_o f g l₁ :=
λ c cpos, h (h' c cpos)
theorem is_o.to_is_O {f : α → β} {g : α → γ} {l : filter α} (hgf : is_o f g l) : is_O f g l :=
⟨1, zero_lt_one, hgf 1 zero_lt_one⟩
theorem is_O.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α}
(h₁ : is_O f g l) (h₂ : is_O g k l) :
is_O f k l :=
let ⟨c, cpos, hc⟩ := h₁,
⟨c', c'pos, hc'⟩ := h₂ in
begin
use [c * c', mul_pos cpos c'pos],
filter_upwards [hc, hc'], dsimp,
intros x h₁x h₂x, rw mul_assoc,
exact le_trans h₁x (mul_le_mul_of_nonneg_left h₂x (le_of_lt cpos))
end
theorem is_o.trans_is_O {f : α → β} {g : α → γ} {k : α → δ} {l : filter α}
(h₁ : is_o f g l) (h₂ : is_O g k l) :
is_o f k l :=
begin
intros c cpos,
rcases h₂ with ⟨c', c'pos, hc'⟩,
have cc'pos := div_pos cpos c'pos,
filter_upwards [h₁ (c / c') cc'pos, hc'], dsimp,
intros x h₁x h₂x,
refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt cc'pos)) _),
rw [←mul_assoc, div_mul_cancel _ (ne_of_gt c'pos)]
end
theorem is_O.trans_is_o {f : α → β} {g : α → γ} {k : α → δ} {l : filter α}
(h₁ : is_O f g l) (h₂ : is_o g k l) :
is_o f k l :=
begin
intros c cpos,
rcases h₁ with ⟨c', c'pos, hc'⟩,
have cc'pos := div_pos cpos c'pos,
filter_upwards [hc', h₂ (c / c') cc'pos], dsimp,
intros x h₁x h₂x,
refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt c'pos)) _),
rw [←mul_assoc, mul_div_cancel' _ (ne_of_gt c'pos)]
end
theorem is_o.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α}
(h₁ : is_o f g l) (h₂ : is_o g k l) :
is_o f k l :=
h₁.to_is_O.trans_is_o h₂
theorem is_o_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α}
(h₁ : is_o f g l₁) (h₂ : is_o f g l₂) :
is_o f g (l₁ ⊔ l₂) :=
begin
intros c cpos,
rw mem_sup_sets,
exact ⟨h₁ c cpos, h₂ c cpos⟩
end
theorem is_O_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) :
is_O f₁ g₁ l ↔ is_O f₂ g₂ l :=
bex_congr $ λ c _, filter.congr_sets $
by filter_upwards [hf, hg] λ x e₁ e₂,
by dsimp at e₁ e₂ ⊢; rw [e₁, e₂]
theorem is_o_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) :
is_o f₁ g₁ l ↔ is_o f₂ g₂ l :=
ball_congr $ λ c _, filter.congr_sets $
by filter_upwards [hf, hg] λ x e₁ e₂,
by dsimp at e₁ e₂ ⊢; rw [e₁, e₂]
theorem is_O.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) :
is_O f₁ g₁ l → is_O f₂ g₂ l :=
(is_O_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1
theorem is_o.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) :
is_o f₁ g₁ l → is_o f₂ g₂ l :=
(is_o_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1
theorem is_O_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(h : {x | f₁ x = f₂ x} ∈ l) :
is_O f₁ g l ↔ is_O f₂ g l :=
is_O_congr h (univ_mem_sets' $ λ _, rfl)
theorem is_o_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(h : {x | f₁ x = f₂ x} ∈ l) :
is_o f₁ g l ↔ is_o f₂ g l :=
is_o_congr h (univ_mem_sets' $ λ _, rfl)
theorem is_O.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l :=
is_O.congr hf (λ _, rfl)
theorem is_o.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l :=
is_o.congr hf (λ _, rfl)
theorem is_O_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h : {x | g₁ x = g₂ x} ∈ l) :
is_O f g₁ l ↔ is_O f g₂ l :=
is_O_congr (univ_mem_sets' $ λ _, rfl) h
theorem is_o_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h : {x | g₁ x = g₂ x} ∈ l) :
is_o f g₁ l ↔ is_o f g₂ l :=
is_o_congr (univ_mem_sets' $ λ _, rfl) h
theorem is_O.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l :=
is_O.congr (λ _, rfl) hg
theorem is_o.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α}
(hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l :=
is_o.congr (λ _, rfl) hg
end
section
variables [has_norm β] [normed_group γ] [normed_group δ]
@[simp]
theorem is_O_norm_right {f : α → β} {g : α → γ} {l : filter α} :
is_O f (λ x, ∥g x∥) l ↔ is_O f g l :=
by simp only [is_O, norm_norm]
@[simp]
theorem is_o_norm_right {f : α → β} {g : α → γ} {l : filter α} :
is_o f (λ x, ∥g x∥) l ↔ is_o f g l :=
by simp only [is_o, norm_norm]
@[simp]
theorem is_O_neg_right {f : α → β} {g : α → γ} {l : filter α} :
is_O f (λ x, -(g x)) l ↔ is_O f g l :=
by { rw ←is_O_norm_right, simp only [norm_neg], rw is_O_norm_right }
@[simp]
theorem is_o_neg_right {f : α → β} {g : α → γ} {l : filter α} :
is_o f (λ x, -(g x)) l ↔ is_o f g l :=
by { rw ←is_o_norm_right, simp only [norm_neg], rw is_o_norm_right }
theorem is_O_iff {f : α → β} {g : α → γ} {l : filter α} :
is_O f g l ↔ ∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l :=
suffices (∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l) → is_O f g l,
from ⟨λ ⟨c, cpos, hc⟩, ⟨c, hc⟩, this⟩,
assume ⟨c, hc⟩,
or.elim (lt_or_ge 0 c)
(assume : c > 0, ⟨c, this, hc⟩)
(assume h'c : c ≤ 0,
have {x : α | ∥f x∥ ≤ 1 * ∥g x∥} ∈ l,
begin
filter_upwards [hc], intros x,
show ∥f x∥ ≤ c * ∥g x∥ → ∥f x∥ ≤ 1 * ∥g x∥,
{ intro hx, apply le_trans hx,
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
show c ≤ 1, from le_trans h'c zero_le_one }
end,
⟨1, zero_lt_one, this⟩)
theorem is_O_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α}
(h₁ : is_O f g l₁) (h₂ : is_O f g l₂) :
is_O f g (l₁ ⊔ l₂) :=
begin
rcases h₁ with ⟨c₁, c₁pos, hc₁⟩,
rcases h₂ with ⟨c₂, c₂pos, hc₂⟩,
have : 0 < max c₁ c₂, by { rw lt_max_iff, left, exact c₁pos },
use [max c₁ c₂, this],
rw mem_sup_sets, split,
{ filter_upwards [hc₁], dsimp, intros x hx,
exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)) },
filter_upwards [hc₂], dsimp, intros x hx,
exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _))
end
lemma is_O.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α}
(h : is_O f g₁ l) : is_O f (λx, (g₁ x, g₂ x)) l :=
begin
have : is_O g₁ (λx, (g₁ x, g₂ x)) l :=
⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩,
exact is_O.trans h this
end
lemma is_O.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α}
(h : is_O f g₂ l) : is_O f (λx, (g₁ x, g₂ x)) l :=
begin
have : is_O g₂ (λx, (g₁ x, g₂ x)) l :=
⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩,
exact is_O.trans h this
end
lemma is_o.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α}
(h : is_o f g₁ l) : is_o f (λx, (g₁ x, g₂ x)) l :=
is_o.trans_is_O h (is_O.prod_rightl (is_O_refl g₁ l))
lemma is_o.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α}
(h : is_o f g₂ l) : is_o f (λx, (g₁ x, g₂ x)) l :=
is_o.trans_is_O h (is_O.prod_rightr (is_O_refl g₂ l))
end
section
variables [normed_group β] [normed_group δ] [has_norm γ]
@[simp] theorem is_O_norm_left {f : α → β} {g : α → γ} {l : filter α} :
is_O (λ x, ∥f x∥) g l ↔ is_O f g l :=
by simp only [is_O, norm_norm]
@[simp] theorem is_o_norm_left {f : α → β} {g : α → γ} {l : filter α} :
is_o (λ x, ∥f x∥) g l ↔ is_o f g l :=
by simp only [is_o, norm_norm]
@[simp] theorem is_O_neg_left {f : α → β} {g : α → γ} {l : filter α} :
is_O (λ x, -f x) g l ↔ is_O f g l :=
by { rw ←is_O_norm_left, simp only [norm_neg], rw is_O_norm_left }
@[simp] theorem is_o_neg_left {f : α → β} {g : α → γ} {l : filter α} :
is_o (λ x, -f x) g l ↔ is_o f g l :=
by { rw ←is_o_norm_left, simp only [norm_neg], rw is_o_norm_left }
theorem is_O.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) :
is_O (λ x, f₁ x + f₂ x) g l :=
let ⟨c₁, c₁pos, hc₁⟩ := h₁,
⟨c₂, c₂pos, hc₂⟩ := h₂ in
begin
use [c₁ + c₂, add_pos c₁pos c₂pos],
filter_upwards [hc₁, hc₂],
intros x hx₁ hx₂,
show ∥f₁ x + f₂ x∥ ≤ (c₁ + c₂) * ∥g x∥,
apply le_trans (norm_triangle _ _),
rw add_mul,
exact add_le_add hx₁ hx₂
end
theorem is_o.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) :
is_o (λ x, f₁ x + f₂ x) g l :=
begin
intros c cpos,
filter_upwards [h₁ (c / 2) (half_pos cpos), h₂ (c / 2) (half_pos cpos)],
intros x hx₁ hx₂, dsimp at hx₁ hx₂,
apply le_trans (norm_triangle _ _),
apply le_trans (add_le_add hx₁ hx₂),
rw [←mul_add, ←two_mul, ←mul_assoc, div_mul_cancel _ two_ne_zero]
end
theorem is_O.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) :
is_O (λ x, f₁ x - f₂ x) g l :=
h₁.add (is_O_neg_left.mpr h₂)
theorem is_o.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) :
is_o (λ x, f₁ x - f₂ x) g l :=
h₁.add (is_o_neg_left.mpr h₂)
theorem is_O_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} :
is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l :=
by simpa using @is_O_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l
theorem is_O.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} :
is_O (λ x, f₁ x - f₂ x) g l → is_O (λ x, f₂ x - f₁ x) g l :=
is_O_comm.1
theorem is_O.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α}
(h₁ : is_O (λ x, f₁ x - f₂ x) g l)
(h₂ : is_O (λ x, f₂ x - f₃ x) g l) :
is_O (λ x, f₁ x - f₃ x) g l :=
(h₁.add h₂).congr_left (by simp)
theorem is_O.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(h : is_O (λ x, f₁ x - f₂ x) g l) :
is_O f₁ g l ↔ is_O f₂ g l :=
⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _),
λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩
theorem is_o_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} :
is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l :=
by simpa using @is_o_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l
theorem is_o.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} :
is_o (λ x, f₁ x - f₂ x) g l → is_o (λ x, f₂ x - f₁ x) g l :=
is_o_comm.1
theorem is_o.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α}
(h₁ : is_o (λ x, f₁ x - f₂ x) g l)
(h₂ : is_o (λ x, f₂ x - f₃ x) g l) :
is_o (λ x, f₁ x - f₃ x) g l :=
(h₁.add h₂).congr_left (by simp)
theorem is_o.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α}
(h : is_o (λ x, f₁ x - f₂ x) g l) :
is_o f₁ g l ↔ is_o f₂ g l :=
⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _),
λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩
@[simp] theorem is_O_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} :
is_O (λx, (f₁ x, f₂ x)) g l ↔ is_O f₁ g l ∧ is_O f₂ g l :=
begin
split,
{ assume h,
split,
{ exact is_O.trans (is_O.prod_rightl (is_O_refl f₁ l)) h },
{ exact is_O.trans (is_O.prod_rightr (is_O_refl f₂ l)) h } },
{ rintros ⟨h₁, h₂⟩,
have : is_O (λx, ∥f₁ x∥ + ∥f₂ x∥) g l :=
is_O.add (is_O_norm_left.2 h₁) (is_O_norm_left.2 h₂),
apply is_O.trans _ this,
refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩,
simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq],
split; exact le_trans (by simp) (le_abs_self _) }
end
@[simp] theorem is_o_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} :
is_o (λx, (f₁ x, f₂ x)) g l ↔ is_o f₁ g l ∧ is_o f₂ g l :=
begin
split,
{ assume h,
split,
{ exact is_O.trans_is_o (is_O.prod_rightl (is_O_refl f₁ l)) h },
{ exact is_O.trans_is_o (is_O.prod_rightr (is_O_refl f₂ l)) h } },
{ rintros ⟨h₁, h₂⟩,
have : is_o (λx, ∥f₁ x∥ + ∥f₂ x∥) g l :=
is_o.add (is_o_norm_left.2 h₁) (is_o_norm_left.2 h₂),
apply is_O.trans_is_o _ this,
refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩,
simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq],
split; exact le_trans (by simp) (le_abs_self _) }
end
end
section
variables [normed_group β] [normed_group γ]
theorem is_O_zero (g : α → γ) (l : filter α) :
is_O (λ x, (0 : β)) g l :=
⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩
theorem is_O_refl_left {f : α → β} {g : α → γ} {l : filter α} :
is_O (λ x, f x - f x) g l :=
by simpa using is_O_zero g l
theorem is_O_zero_right_iff {f : α → β} {l : filter α} :
is_O f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l :=
begin
rw [is_O_iff], split,
{ rintros ⟨c, hc⟩,
filter_upwards [hc], dsimp,
intro x, rw [norm_zero, mul_zero], intro hx,
rw ←norm_eq_zero,
exact le_antisymm hx (norm_nonneg _) },
intro h, use 0,
filter_upwards [h], dsimp,
intros x hx,
rw [hx, norm_zero, zero_mul]
end
theorem is_o_zero (g : α → γ) (l : filter α) :
is_o (λ x, (0 : β)) g l :=
λ c cpos,
by { filter_upwards [univ_mem_sets], intros x _, simp,
exact mul_nonneg (le_of_lt cpos) (norm_nonneg _)}
theorem is_o_refl_left {f : α → β} {g : α → γ} {l : filter α} :
is_o (λ x, f x - f x) g l :=
by simpa using is_o_zero g l
theorem is_o_zero_right_iff {f : α → β} (l : filter α) :
is_o f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l :=
begin
split,
{ intro h, exact is_O_zero_right_iff.mp h.to_is_O },
intros h c cpos,
filter_upwards [h], dsimp,
intros x hx,
rw [hx, norm_zero, norm_zero, mul_zero]
end
end
section
variables [has_norm β] [normed_field γ]
open normed_field
theorem is_O_const_one (c : β) (l : filter α) :
is_O (λ x : α, c) (λ x, (1 : γ)) l :=
begin
rw is_O_iff,
refine ⟨∥c∥, _⟩,
simp only [norm_one, mul_one],
apply univ_mem_sets',
simp [le_refl],
end
end
section
variables [normed_field β] [normed_group γ]
theorem is_O_const_mul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) (c : β) :
is_O (λ x, c * f x) g l :=
begin
cases classical.em (c = 0) with h'' h'',
{ simp [h''], apply is_O_zero },
rcases h with ⟨c', c'pos, h'⟩,
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'',
have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
refine ⟨∥c∥ * c', mul_pos cpos c'pos, _⟩,
filter_upwards [h'], dsimp,
intros x h₀,
rw [normed_field.norm_mul, mul_assoc],
exact mul_le_mul_of_nonneg_left h₀ (norm_nonneg _)
end
theorem is_O_const_mul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : β} (hc : c ≠ 0) :
is_O (λ x, c * f x) g l ↔ is_O f g l :=
begin
split,
{ intro h,
convert is_O_const_mul_left h c⁻¹, ext,
rw [←mul_assoc, inv_mul_cancel hc, one_mul] },
intro h, apply is_O_const_mul_left h
end
theorem is_o_const_mul_left {f : α → β} {g : α → γ} {l : filter α}
(h : is_o f g l) (c : β) :
is_o (λ x, c * f x) g l :=
begin
cases classical.em (c = 0) with h'' h'',
{ simp [h''], apply is_o_zero },
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'',
have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
intros c' c'pos, dsimp,
filter_upwards [h (c' / ∥c∥) (div_pos c'pos cpos)], dsimp,
intros x hx, rw [normed_field.norm_mul],
apply le_trans (mul_le_mul_of_nonneg_left hx (le_of_lt cpos)),
rw [←mul_assoc, mul_div_cancel' _ cne0]
end
theorem is_o_const_mul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : β} (hc : c ≠ 0) :
is_o (λ x, c * f x) g l ↔ is_o f g l :=
begin
split,
{ intro h,
convert is_o_const_mul_left h c⁻¹, ext,
rw [←mul_assoc, inv_mul_cancel hc, one_mul] },
intro h',
apply is_o_const_mul_left h'
end
end
section
variables [normed_group β] [normed_field γ]
theorem is_O_of_is_O_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ}
(h : is_O f (λ x, c * g x) l) :
is_O f g l :=
begin
cases classical.em (c = 0) with h' h',
{ simp [h', is_O_zero_right_iff] at h, rw is_O_congr_left h, apply is_O_zero },
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h',
have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
rcases h with ⟨c', c'pos, h''⟩,
refine ⟨c' * ∥c∥, mul_pos c'pos cpos, _⟩,
convert h'', ext x, dsimp,
rw [normed_field.norm_mul, mul_assoc]
end
theorem is_O_const_mul_right_iff {f : α → β} {g : α → γ} {l : filter α} {c : γ} (hc : c ≠ 0) :
is_O f (λ x, c * g x) l ↔ is_O f g l :=
begin
split,
{ intro h, exact is_O_of_is_O_const_mul_right h },
intro h,
apply is_O_of_is_O_const_mul_right,
show is_O f (λ (x : α), c⁻¹ * (c * g x)) l,
convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul]
end
theorem is_o_of_is_o_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ}
(h : is_o f (λ x, c * g x) l) :
is_o f g l :=
begin
cases classical.em (c = 0) with h' h',
{ simp [h', is_o_zero_right_iff] at h, rw is_o_congr_left h, apply is_o_zero },
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h',
have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
intros c' c'pos,
convert h (c' / ∥c∥) (div_pos c'pos cpos), dsimp,
ext x, rw [normed_field.norm_mul, ←mul_assoc, div_mul_cancel _ cne0]
end
theorem is_o_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ} (hc : c ≠ 0) :
is_o f (λ x, c * g x) l ↔ is_o f g l :=
begin
split,
{ intro h, exact is_o_of_is_o_const_mul_right h },
intro h,
apply is_o_of_is_o_const_mul_right,
show is_o f (λ (x : α), c⁻¹ * (c * g x)) l,
convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul]
end
theorem is_o_one_iff {f : α → β} {l : filter α} :
is_o f (λ x, (1 : γ)) l ↔ tendsto f l (𝓝 0) :=
begin
rw [normed_group.tendsto_nhds_zero, is_o], split,
{ intros h e epos,
filter_upwards [h (e / 2) (half_pos epos)], simp,
intros x hx,
exact lt_of_le_of_lt hx (half_lt_self epos) },
intros h e epos,
filter_upwards [h e epos], simp,
intros x hx,
exact le_of_lt hx
end
theorem is_O_one_of_tendsto {f : α → β} {l : filter α} {y : β}
(h : tendsto f l (𝓝 y)) : is_O f (λ x, (1 : γ)) l :=
begin
have Iy : ∥y∥ < ∥y∥ + 1 := lt_add_one _,
refine ⟨∥y∥ + 1, lt_of_le_of_lt (norm_nonneg _) Iy, _⟩,
simp only [mul_one, normed_field.norm_one],
have : tendsto (λx, ∥f x∥) l (𝓝 ∥y∥) :=
(continuous_norm.tendsto _).comp h,
exact this (ge_mem_nhds Iy)
end
end
section
variables [normed_group β] [normed_group γ]
theorem is_O.trans_tendsto {f : α → β} {g : α → γ} {l : filter α}
(h₁ : is_O f g l) (h₂ : tendsto g l (𝓝 0)) :
tendsto f l (𝓝 0) :=
(@is_o_one_iff _ _ ℝ _ _ _ _).1 $ h₁.trans_is_o $ is_o_one_iff.2 h₂
theorem is_o.trans_tendsto {f : α → β} {g : α → γ} {l : filter α}
(h₁ : is_o f g l) : tendsto g l (𝓝 0) → tendsto f l (𝓝 0) :=
h₁.to_is_O.trans_tendsto
end
section
variables [normed_field β] [normed_field γ]
theorem is_O_mul {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) :
is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l :=
begin
rcases h₁ with ⟨c₁, c₁pos, hc₁⟩,
rcases h₂ with ⟨c₂, c₂pos, hc₂⟩,
refine ⟨c₁ * c₂, mul_pos c₁pos c₂pos, _⟩,
filter_upwards [hc₁, hc₂], dsimp,
intros x hx₁ hx₂,
rw [normed_field.norm_mul, normed_field.norm_mul, mul_assoc, mul_left_comm c₂, ←mul_assoc],
exact mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _))
end
theorem is_o_mul_left {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) :
is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l :=
begin
intros c cpos,
rcases h₁ with ⟨c₁, c₁pos, hc₁⟩,
filter_upwards [hc₁, h₂ (c / c₁) (div_pos cpos c₁pos)], dsimp,
intros x hx₁ hx₂,
rw [normed_field.norm_mul, normed_field.norm_mul],
apply le_trans (mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _))),
rw [mul_comm c₁, mul_assoc, mul_left_comm c₁, ←mul_assoc _ c₁, div_mul_cancel _ (ne_of_gt c₁pos)],
rw [mul_left_comm]
end
theorem is_o_mul_right {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) :
is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l :=
by convert is_o_mul_left h₂ h₁; simp only [mul_comm]
theorem is_o_mul {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α}
(h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) :
is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l :=
is_o_mul_left h₁.to_is_O h₂
end
/-
Note: the theorems in the next two sections can also be used for the integers, since
scalar multiplication is multiplication.
-/
section
variables {K : Type*} [normed_field K] [normed_group β] [normed_space K β] [normed_group γ]
set_option class.instance_max_depth 43
theorem is_O_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) (c : K) :
is_O (λ x, c • f x) g l :=
begin
rw [←is_O_norm_left], simp only [norm_smul],
apply is_O_const_mul_left,
rw [is_O_norm_left],
apply h
end
theorem is_O_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) :
is_O (λ x, c • f x) g l ↔ is_O f g l :=
begin
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc,
rw [←is_O_norm_left], simp only [norm_smul],
rw [is_O_const_mul_left_iff cne0, is_O_norm_left]
end
theorem is_o_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) (c : K) :
is_o (λ x, c • f x) g l :=
begin
rw [←is_o_norm_left], simp only [norm_smul],
apply is_o_const_mul_left,
rw [is_o_norm_left],
apply h
end
theorem is_o_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) :
is_o (λ x, c • f x) g l ↔ is_o f g l :=
begin
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc,
rw [←is_o_norm_left], simp only [norm_smul],
rw [is_o_const_mul_left_iff cne0, is_o_norm_left]
end
end
section
variables {K : Type*} [normed_group β] [normed_field K] [normed_group γ] [normed_space K γ]
set_option class.instance_max_depth 43
theorem is_O_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) :
is_O f (λ x, c • g x) l ↔ is_O f g l :=
begin
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc,
rw [←is_O_norm_right], simp only [norm_smul],
rw [is_O_const_mul_right_iff cne0, is_O_norm_right]
end
theorem is_o_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) :
is_o f (λ x, c • g x) l ↔ is_o f g l :=
begin
have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc,
rw [←is_o_norm_right], simp only [norm_smul],
rw [is_o_const_mul_right cne0, is_o_norm_right]
end
end
section
variables {K : Type*} [normed_field K] [normed_group β] [normed_space K β]
[normed_group γ] [normed_space K γ]
set_option class.instance_max_depth 43
theorem is_O_smul {k : α → K} {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) :
is_O (λ x, k x • f x) (λ x, k x • g x) l :=
begin
rw [←is_O_norm_left, ←is_O_norm_right], simp only [norm_smul],
apply is_O_mul (is_O_refl _ _),
rw [is_O_norm_left, is_O_norm_right],
exact h
end
theorem is_o_smul {k : α → K} {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) :
is_o (λ x, k x • f x) (λ x, k x • g x) l :=
begin
rw [←is_o_norm_left, ←is_o_norm_right], simp only [norm_smul],
apply is_o_mul_left (is_O_refl _ _),
rw [is_o_norm_left, is_o_norm_right],
exact h
end
end
section
variables [normed_field β]
theorem tendsto_nhds_zero_of_is_o {f g : α → β} {l : filter α} (h : is_o f g l) :
tendsto (λ x, f x / (g x)) l (𝓝 0) :=
have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l,
from is_o_mul_right h (is_O_refl _ _),
have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : β)) l,
begin
use [1, zero_lt_one],
filter_upwards [univ_mem_sets], simp,
intro x,
cases classical.em (∥g x∥ = 0) with h' h'; simp [h'],
exact zero_le_one
end,
is_o_one_iff.mp (eq₁.trans_is_O eq₂)
private theorem is_o_of_tendsto {f g : α → β} {l : filter α}
(hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) :
is_o f g l :=
have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : β)) l,
from is_o_one_iff.mpr h,
have eq₂ : is_o (λ x, f x / g x * g x) g l,
by convert is_o_mul_right eq₁ (is_O_refl _ _); simp,
have eq₃ : is_O f (λ x, f x / g x * g x) l,
begin
use [1, zero_lt_one],
refine filter.univ_mem_sets' (assume x, _),
suffices : ∥f x∥ ≤ ∥f x∥ / ∥g x∥ * ∥g x∥, { simpa },
by_cases g x = 0,
{ simp only [h, hgf x h, norm_zero, mul_zero] },
{ rw [div_mul_cancel], exact mt (norm_eq_zero _).1 h }
end,
eq₃.trans_is_o eq₂
theorem is_o_iff_tendsto {f g : α → β} {l : filter α}
(hgf : ∀ x, g x = 0 → f x = 0) :
is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) :=
iff.intro tendsto_nhds_zero_of_is_o (is_o_of_tendsto hgf)
end
end asymptotics
|
b1395d69e72d73d114ed9c58f2aae3d10ca4a131 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/missing_mathlib/data/list/basic.lean | 1a764964fce3138143249bce8b4e65cae5616e09 | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 793 | lean | import data.list.basic
universe u
theorem list.foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, g (f x y) = f' (g x) (g y)) :
g (list.foldl f a l) = list.foldl f' (g a) (l.map g) :=
begin
induction l generalizing a,
{ simp },
{ simp [list.foldl_cons, l_ih, h] }
end
lemma function.injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective_comp hf,
apply hl _ (list.mem_cons_self _ _) }
end |
0b85a8f5fbe1e1b65bc439f1ea756059d887db16 | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/uniform_space/basic.lean | 972b23fb70b0262a1a5da640a3e3ad960ab68dfc | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 84,286 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import order.filter.small_sets
import topology.subset_properties
import topology.nhds_set
/-!
# Uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* uniform continuity (in this file)
* completeness (in `cauchy.lean`)
* extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`)
* totally bounded sets (in `cauchy.lean`)
* totally bounded complete sets are compact (in `cauchy.lean`)
A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions
which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means
"for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages
of `X`. The two main examples are:
* If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V`
* If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V`
Those examples are generalizations in two different directions of the elementary example where
`X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological
group structure on `ℝ` and its metric space structure.
Each uniform structure on `X` induces a topology on `X` characterized by
> `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)`
where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product
constructor.
The dictionary with metric spaces includes:
* an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X`
* a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}`
for some `V ∈ 𝓤 X`, but the later is more general (it includes in
particular both open and closed balls for suitable `V`).
In particular we have:
`is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s`
The triangle inequality is abstracted to a statement involving the composition of relations in `X`.
First note that the triangle inequality in a metric space is equivalent to
`∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`.
Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is
defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`.
In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }`
then the triangle inequality, as reformulated above, says `V ○ W` is contained in
`{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`.
In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`.
Note that this discussion does not depend on any axiom imposed on the uniformity filter,
it is simply captured by the definition of composition.
The uniform space axioms ask the filter `𝓤 X` to satisfy the following:
* every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact
that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that
`x - x` belongs to every neighborhood of zero in the topological group case.
* `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x`
in a metric space, and to continuity of negation in the topological group case.
* `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds
to cutting the radius of a ball in half and applying the triangle inequality.
In the topological group case, it comes from continuity of addition at `(0, 0)`.
These three axioms are stated more abstractly in the definition below, in terms of
operations on filters, without directly manipulating entourages.
## Main definitions
* `uniform_space X` is a uniform space structure on a type `X`
* `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces
is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r`
In this file we also define a complete lattice structure on the type `uniform_space X`
of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `set (X × X)`.
## Implementation notes
There is already a theory of relations in `data/rel.lean` where the main definition is
`def rel (α β : Type*) := α → β → Prop`.
The relations used in the current file involve only one type, but this is not the reason why
we don't reuse `data/rel.lean`. We use `set (α × α)`
instead of `rel α α` because we really need sets to use the filter library, and elements
of filters on `α × α` have type `set (α × α)`.
The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and
an assumption saying those are compatible. This may not seem mathematically reasonable at first,
but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance]
below.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
open set filter classical
open_locale classical topological_space filter
set_option eqn_compiler.zeta true
universes u
/-!
### Relations, seen as `set (α × α)`
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type*} := {p : α × α | p.1 = p.2}
@[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s :=
by simp [subset_def]; exact forall_congr (λ a, by simp)
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
localized "infix (name := uniformity.comp_rel) ` ○ `:55 := comp_rel" in uniformity
@[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)}
{x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl
@[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm
theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) :=
assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
@[mono]
lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k :=
λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ s ○ t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r :=
set.ext $ assume ⟨a, b⟩, by simp
lemma comp_rel_assoc {r s t : set (α×α)} :
(r ○ s) ○ t = r ○ (s ○ t) :=
by ext p; cases p; simp only [mem_comp_rel]; tauto
lemma left_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ t) : s ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨y, xy_in, h $ by exact rfl⟩
lemma right_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) : t ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨x, h $ by exact rfl, xy_in⟩
lemma subset_comp_self {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s :=
left_subset_comp_rel h
lemma subset_iterate_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) (n : ℕ) :
t ⊆ (((○) s) ^[n] t) :=
begin
induction n with n ihn generalizing t,
exacts [subset.rfl, (right_subset_comp_rel h).trans ihn]
end
/-- The relation is invariant under swapping factors. -/
def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V
/-- The maximal symmetric relation contained in a given relation. -/
def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V
lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) :=
by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp]
lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V :=
sep_subset _ _
@[mono]
lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W :=
inter_subset_inter h $ preimage_mono h
lemma symmetric_rel.mk_mem_comm {V : set (α × α)} (hV : symmetric_rel V) {x y : α} :
(x, y) ∈ V ↔ (y, x) ∈ V :=
set.ext_iff.1 hV (y, x)
lemma symmetric_rel.eq {U : set (α × α)} (hU : symmetric_rel U) : prod.swap ⁻¹' U = U := hU
lemma symmetric_rel.inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) :
symmetric_rel (U ∩ V) :=
by rw [symmetric_rel, preimage_inter, hU.eq, hV.eq]
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) :=
(uniformity : filter (α × α))
(refl : 𝓟 id_rel ≤ uniformity)
(symm : tendsto prod.swap uniformity uniformity)
(comp : uniformity.lift' (λs, s ○ s) ≤ uniformity)
/-- An alternative constructor for `uniform_space.core`. This version unfolds various
`filter`-related definitions. -/
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r ∈ U) x, (x, x) ∈ r)
(symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U)
(comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α :=
⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm,
begin
intros r ru,
rw [mem_lift'_sets],
exact comp _ ru,
apply monotone_comp_rel; exact monotone_id,
end⟩
/-- Defining an `uniform_space.core` from a filter basis satisfying some uniformity-like axioms. -/
def uniform_space.core.mk_of_basis {α : Type u} (B : filter_basis (α × α))
(refl : ∀ (r ∈ B) x, (x, x) ∈ r)
(symm : ∀ r ∈ B, ∃ t ∈ B, t ⊆ prod.swap ⁻¹' r)
(comp : ∀ r ∈ B, ∃ t ∈ B, t ○ t ⊆ r) : uniform_space.core α :=
{ uniformity := B.filter,
refl := B.has_basis.ge_iff.mpr (λ r ru, id_rel_subset.2 $ refl _ ru),
symm := (B.has_basis.tendsto_iff B.has_basis).mpr symm,
comp := (has_basis.le_basis_iff (B.has_basis.lift' (monotone_comp_rel monotone_id monotone_id))
B.has_basis).mpr comp }
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
{ is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity,
is_open_univ := by simp; intro; exact univ_mem,
is_open_inter :=
assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt},
is_open_sUnion :=
assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] with p ph h using ⟨t, ts, ph h⟩ }
lemma uniform_space.core_eq :
∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h }
-- the topological structure is embedded in the uniform structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends topological_space α, uniform_space.core α :=
(is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity))
/-- Alternative constructor for `uniform_space α` when a topology is already given. -/
@[pattern] def uniform_space.mk' {α} (t : topological_space α)
(c : uniform_space.core α)
(is_open_uniformity : ∀s:set α, t.is_open s ↔
(∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) :
uniform_space α := ⟨c, is_open_uniformity⟩
/-- Construct a `uniform_space` from a `uniform_space.core`. -/
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
{ to_core := u,
to_topological_space := u.to_topological_space,
is_open_uniformity := assume a, iff.rfl }
/-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure
that is equal to `u.to_topological_space`. -/
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = u.to_topological_space) : uniform_space α :=
{ to_core := u,
to_topological_space := t,
is_open_uniformity := assume a, h.symm ▸ iff.rfl }
lemma uniform_space.to_core_to_topological_space (u : uniform_space α) :
u.to_core.to_topological_space = u.to_topological_space :=
topological_space_eq $ funext $ assume s,
by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity]
@[ext]
lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h :=
have u₁ = u₂, from uniform_space.core_eq h,
have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this],
by simp [*]
lemma uniform_space.of_core_eq_to_core
(u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) :
uniform_space.of_core_eq u.to_core t h = u :=
uniform_space_eq rfl
/-- Replace topology in a `uniform_space` instance with a propositionally (but possibly not
definitionally) equal one. -/
@[reducible] def uniform_space.replace_topology {α : Type*} [i : topological_space α]
(u : uniform_space α) (h : i = u.to_topological_space) : uniform_space α :=
uniform_space.of_core_eq u.to_core i $ h.trans u.to_core_to_topological_space.symm
lemma uniform_space.replace_topology_eq {α : Type*} [i : topological_space α] (u : uniform_space α)
(h : i = u.to_topological_space) : u.replace_topology h = u :=
u.of_core_eq_to_core _ _
section uniform_space
variables [uniform_space α]
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
(@uniform_space.to_core α _).uniformity
localized "notation (name := uniformity) `𝓤` := uniformity" in uniformity
lemma is_open_uniformity {s : set α} :
is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) :=
uniform_space.is_open_uniformity s
lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α :=
(@uniform_space.to_core α _).refl
instance uniformity.ne_bot [nonempty α] : ne_bot (𝓤 α) :=
begin
inhabit α,
refine (principal_ne_bot_iff.2 _).mono refl_le_uniformity,
exact ⟨(default, default), rfl⟩
end
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma mem_uniformity_of_eq {x y : α} {s : set (α × α)} (h : s ∈ 𝓤 α) (hx : x = y) :
(x, y) ∈ s :=
hx ▸ refl_mem_uniformity h
lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) :=
(@uniform_space.to_core α _).symm
lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α :=
(@uniform_space.to_core α _).comp
lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) :=
symm_le_uniformity
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, t ○ t ⊆ s :=
have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t),
from comp_le_uniformity hs,
(mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ○ ... ○ t ⊆ s` (`n` compositions). -/
lemma eventually_uniformity_iterate_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) (n : ℕ) :
∀ᶠ t in (𝓤 α).small_sets, ((○) t) ^[n] t ⊆ s :=
begin
suffices : ∀ᶠ t in (𝓤 α).small_sets, t ⊆ s ∧ (((○) t) ^[n] t ⊆ s),
from (eventually_and.1 this).2,
induction n with n ihn generalizing s, { simpa },
rcases comp_mem_uniformity_sets hs with ⟨t, htU, hts⟩,
refine (ihn htU).mono (λ U hU, _),
rw [function.iterate_succ_apply'],
exact ⟨hU.1.trans $ (subset_comp_self $ refl_le_uniformity htU).trans hts,
(comp_rel_mono hU.1 hU.2).trans hts⟩
end
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ⊆ s`. -/
lemma eventually_uniformity_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∀ᶠ t in (𝓤 α).small_sets, t ○ t ⊆ s :=
eventually_uniformity_iterate_comp_subset hs 1
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/
lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α}
(h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) :
tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) :=
begin
refine le_trans (le_lift'.2 $ λ s hs, mem_map.2 _) comp_le_uniformity,
filter_upwards [h₁₂ hs, h₂₃ hs] with x hx₁₂ hx₂₃ using ⟨_, hx₁₂, hx₂₃⟩,
end
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/
lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α}
(h : tendsto f l (𝓤 α)) :
tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) :=
tendsto_swap_uniformity.comp h
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/
lemma tendsto_diag_uniformity (f : β → α) (l : filter β) :
tendsto (λ x, (f x, f x)) l (𝓤 α) :=
assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs
lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) :=
tendsto_diag_uniformity (λ _, a) f
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs,
⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α :=
by rw [map_swap_eq_comap_swap];
from map_le_iff_le_comap.1 tendsto_swap_uniformity
lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α :=
le_antisymm uniformity_le_symm symm_le_uniformity
@[simp] lemma comap_swap_uniformity : comap (@prod.swap α α) (𝓤 α) = 𝓤 α :=
(congr_arg _ uniformity_eq_symm).trans $ comap_map prod.swap_injective
lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α :=
begin
apply (𝓤 α).inter_sets h,
rw [← image_swap_eq_preimage_swap, uniformity_eq_symm],
exact image_mem_map h,
end
/-- Symmetric entourages form a basis of `𝓤 α` -/
lemma uniform_space.has_basis_symmetric :
(𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id :=
has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in,
symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩
theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f :=
calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g :
lift_mono uniformity_le_symm le_rfl
... ≤ _ :
by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) :
(𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f :=
calc (𝓤 α).lift (λs, f (s ○ s)) =
((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity le_rfl
lemma comp_le_uniformity3 :
(𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) :=
calc (𝓤 α).lift' (λd, d ○ (d ○ d)) =
(𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (assume x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) :
lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $
monotone_principal.comp (monotone_comp_rel monotone_const monotone_id)
... = (𝓤 α).lift' (λs:set(α×α), s ○ s) :
lift_lift'_same_eq_lift'
(assume s, monotone_comp_rel monotone_const monotone_id)
(assume s, monotone_comp_rel monotone_id monotone_const)
... ≤ (𝓤 α) : comp_le_uniformity
/-- See also `comp_open_symm_mem_uniformity_sets`. -/
lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs,
use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w],
have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w,
calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s :=
subset_comp_self (refl_le_uniformity h)
lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s :=
begin
rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩,
rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩,
use [t, t_in, t_symm],
have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in,
calc
t ○ t ○ t ⊆ w ○ t : by mono
... ⊆ w ○ (t ○ t) : by mono
... ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
/-!
### Balls in uniform spaces
-/
/-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be
used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the
notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/
def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V
open uniform_space (ball)
lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) :
x ∈ ball x V :=
refl_mem_uniformity hV
/-- The triangle inequality for `uniform_space.ball` -/
lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) :
z ∈ ball x (V ○ W) :=
prod_mk_mem_comp_rel h h'
lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) :
ball x W ⊆ ball y V :=
λ z z_in, h' (mem_ball_comp h z_in)
lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W :=
preimage_mono h
lemma ball_inter (x : β) (V W : set (β × β)) : ball x (V ∩ W) = ball x V ∩ ball x W :=
preimage_inter
lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V :=
ball_mono (inter_subset_left V W) x
lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W :=
ball_mono (inter_subset_right V W) x
lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} :
x ∈ ball y V ↔ y ∈ ball x V :=
show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV }
lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} :
ball x V = {y | (y, x) ∈ V} :=
by { ext y, rw mem_ball_symmetry hV, exact iff.rfl }
lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V)
(hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W :=
begin
rw mem_ball_symmetry hV at hx,
exact ⟨z, hx, hy⟩
end
lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) :
is_open (ball x V) :=
hV.preimage $ continuous_const.prod_mk continuous_id
lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} :
p ∈ V ○ M ○ W ↔ ((ball p.1 V ×ˢ ball p.2 W) ∩ M).nonempty :=
begin
cases p with x y,
split,
{ rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩,
exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, },
{ rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩,
rwa mem_ball_symmetry hW' at z_in,
use [z, w] ; tauto },
end
/-!
### Neighborhoods in uniform spaces
-/
lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α :=
begin
refine ⟨_, λ hs, _⟩,
{ simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib],
intros t ts ht xt,
filter_upwards [ht x xt] using λ y h eq, ts (h eq) },
{ refine mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, _, _, hs⟩,
{ exact λ y hy, refl_mem_uniformity hy rfl },
{ refine is_open_uniformity.mpr (λ y hy, _),
rcases comp_mem_uniformity_sets hy with ⟨t, ht, tr⟩,
filter_upwards [ht], rintro ⟨a, b⟩ hp' rfl,
filter_upwards [ht], rintro ⟨a', b'⟩ hp'' rfl,
exact @tr (a, b') ⟨a', hp', hp''⟩ rfl } }
end
lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α :=
by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl }
lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} :
{p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F :=
by rw mem_comap ; from iff.intro
(assume hs, ⟨_, hs, assume x hx, hx rfl⟩)
(assume ⟨t, h, ht⟩, F.sets_of_superset h $
assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp])
lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) :=
by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux }
/-- See also `is_open_iff_open_ball_subset`. -/
lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity],
exact iff.rfl,
end
lemma nhds_basis_uniformity' {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s)
{x : α} :
(𝓝 x).has_basis p (λ i, ball x (s i)) :=
by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) }
lemma nhds_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} :
(𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) :=
begin
replace h := h.comap prod.swap,
rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h,
exact nhds_basis_uniformity' h
end
lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
rw [nhds_eq_comap_uniformity, mem_comap],
exact iff.rfl,
end
lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x :=
begin
rw uniform_space.mem_nhds_iff,
exact ⟨V, V_in, subset.refl _⟩
end
lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} :
s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s :=
begin
rw uniform_space.mem_nhds_iff,
split,
{ rintros ⟨V, V_in, V_sub⟩,
use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V],
exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub },
{ rintros ⟨V, V_in, V_symm, V_sub⟩,
exact ⟨V, V_in, V_sub⟩ }
end
lemma uniform_space.has_basis_nhds (x : α) :
has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) :=
⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩
open uniform_space
lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty :=
by simp [mem_closure_iff_nhds_basis (has_basis_nhds x), set.nonempty]
lemma uniform_space.mem_closure_iff_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty :=
by simp [mem_closure_iff_nhds_basis' (nhds_basis_uniformity' (𝓤 α).basis_sets)]
lemma uniform_space.has_basis_nhds_prod (x y : α) :
has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, ball x s ×ˢ ball y s :=
begin
rw nhds_prod_eq,
apply (has_basis_nhds x).prod_same_index (has_basis_nhds y),
rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩,
exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, U_symm.inter V_symm⟩,
ball_inter_left x U V, ball_inter_right y U V⟩,
end
lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) :=
(nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi
lemma nhds_eq_uniformity' {x : α} : 𝓝 x = (𝓤 α).lift' (λ s, {y | (y, x) ∈ s}) :=
(nhds_basis_uniformity (𝓤 α).basis_sets).eq_binfi
lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{y : α | (x, y) ∈ s} ∈ 𝓝 x :=
ball_mem_nhds x h
lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{x : α | (x, y) ∈ s} ∈ 𝓝 y :=
mem_nhds_left _ (symm_le_uniformity h)
lemma exists_mem_nhds_ball_subset_of_mem_nhds {a : α} {U : set α} (h : U ∈ 𝓝 a) :
∃ (V ∈ 𝓝 a) (t ∈ 𝓤 α), ∀ a' ∈ V, uniform_space.ball a' t ⊆ U :=
let ⟨t, ht, htU⟩ := comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 h) in
⟨_, mem_nhds_left a ht, t, ht, λ a₁ h₁ a₂ h₂, @htU (a, a₂) ⟨a₁, h₁, h₂⟩ rfl⟩
lemma is_compact.nhds_set_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)}
(hU : (𝓤 α).has_basis p s) {K : set α} (hK : is_compact K) :
(𝓝ˢ K).has_basis p (λ i, ⋃ x ∈ K, ball x (s i)) :=
begin
refine ⟨λ U, _⟩,
simp only [mem_nhds_set_iff_forall, (nhds_basis_uniformity' hU).mem_iff, Union₂_subset_iff],
refine ⟨λ H, _, λ ⟨i, hpi, hi⟩ x hx, ⟨i, hpi, hi x hx⟩⟩,
replace H : ∀ x ∈ K, ∃ i : {i // p i}, ball x (s i ○ s i) ⊆ U,
{ intros x hx,
rcases H x hx with ⟨i, hpi, hi⟩,
rcases comp_mem_uniformity_sets (hU.mem_of_mem hpi) with ⟨t, ht_mem, ht⟩,
rcases hU.mem_iff.1 ht_mem with ⟨j, hpj, hj⟩,
exact ⟨⟨j, hpj⟩, subset.trans (ball_mono ((comp_rel_mono hj hj).trans ht) _) hi⟩ },
haveI : nonempty {a // p a}, from nonempty_subtype.2 hU.ex_mem,
choose! I hI using H,
rcases hK.elim_nhds_subcover (λ x, ball x $ s (I x))
(λ x hx, ball_mem_nhds _ $ hU.mem_of_mem (I x).2) with ⟨t, htK, ht⟩,
obtain ⟨i, hpi, hi⟩ : ∃ i (hpi : p i), s i ⊆ ⋂ x ∈ t, s (I x),
from hU.mem_iff.1 ((bInter_finset_mem t).2 (λ x hx, hU.mem_of_mem (I x).2)),
rw [subset_Inter₂_iff] at hi,
refine ⟨i, hpi, λ x hx, _⟩,
rcases mem_Union₂.1 (ht hx) with ⟨z, hzt : z ∈ t, hzx : x ∈ ball z (s (I z))⟩,
calc ball x (s i) ⊆ ball z (s (I z) ○ s (I z)) : λ y hy, ⟨x, hzx, hi z hzt hy⟩
... ⊆ U : hI z (htK z hzt),
end
lemma disjoint.exists_uniform_thickening {A B : set α}
(hA : is_compact A) (hB : is_closed B) (h : disjoint A B) :
∃ V ∈ 𝓤 α, disjoint (⋃ x ∈ A, ball x V) (⋃ x ∈ B, ball x V) :=
begin
have : Bᶜ ∈ 𝓝ˢ A := hB.is_open_compl.mem_nhds_set.mpr h.le_compl_right,
rw (hA.nhds_set_basis_uniformity (filter.basis_sets _)).mem_iff at this,
rcases this with ⟨U, hU, hUAB⟩,
rcases comp_symm_mem_uniformity_sets hU with ⟨V, hV, hVsymm, hVU⟩,
refine ⟨V, hV, set.disjoint_left.mpr $ λ x, _⟩,
simp only [mem_Union₂],
rintro ⟨a, ha, hxa⟩ ⟨b, hb, hxb⟩,
rw mem_ball_symmetry hVsymm at hxa hxb,
exact hUAB (mem_Union₂_of_mem ha $ hVU $ mem_comp_of_mem_ball hVsymm hxa hxb) hb
end
lemma disjoint.exists_uniform_thickening_of_basis {p : ι → Prop} {s : ι → set (α × α)}
(hU : (𝓤 α).has_basis p s) {A B : set α}
(hA : is_compact A) (hB : is_closed B) (h : disjoint A B) :
∃ i, p i ∧ disjoint (⋃ x ∈ A, ball x (s i)) (⋃ x ∈ B, ball x (s i)) :=
begin
rcases h.exists_uniform_thickening hA hB with ⟨V, hV, hVAB⟩,
rcases hU.mem_iff.1 hV with ⟨i, hi, hiV⟩,
exact ⟨i, hi, hVAB.mono
(Union₂_mono $ λ a _, ball_mono hiV a) (Union₂_mono $ λ b _, ball_mono hiV b)⟩,
end
lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_right a
lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_left a
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage )
end
(congr_arg _ $ funext $ assume s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :
by rw [←uniformity_eq_symm]
... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ hg.comp monotone_preimage
... = _ : by simp [image_swap_eq_preimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
𝓝 a ×ᶠ 𝓝 b =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α),
{y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ t})) :=
begin
rw [nhds_eq_uniformity', nhds_eq_uniformity, prod_lift'_lift'],
{ refl },
{ exact monotone_preimage },
{ exact monotone_preimage },
end
lemma nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' (λs:set (α×α), {y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_const.set_prod monotone_preimage },
{ intro t, exact monotone_preimage.set_prod monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) :
∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from
assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $
show cl_d ∈ 𝓝 (x, y),
begin
rw [nhds_eq_uniformity_prod, mem_lift'_sets],
exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_preimage.set_prod monotone_preimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left,
assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α :=
begin
intros V V_in,
rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩,
have : ball x w ×ˢ ball x w ∈ 𝓝 (x, x),
{ rw nhds_prod_eq,
exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) },
apply mem_of_superset this,
rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in)
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α :=
supr_le nhds_le_uniformity
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_set_diagonal_le_uniformity : 𝓝ˢ (diagonal α) ≤ 𝓤 α :=
(nhds_set_diagonal α).trans_le supr_nhds_le_uniformity
/-!
### Closure and interior in uniform spaces
-/
lemma closure_eq_uniformity (s : set $ α × α) :
closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V :=
begin
ext ⟨x, y⟩,
simp only [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter,
mem_set_of_eq, and_imp, mem_comp_comp, exists_prop, ← mem_inter_iff, inter_comm, set.nonempty]
{ contextual := tt }
end
lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id :=
begin
refine filter.has_basis_self.2 (λ t h, _),
rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩,
refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩,
refine subset.trans _ r,
rw closure_eq_uniformity,
apply Inter_subset_of_subset,
apply Inter_subset,
exact ⟨w_in, w_symm⟩
end
lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
eq.symm $ uniformity_has_basis_closed.lift'_closure_eq_self $ λ _, and.right
lemma filter.has_basis.uniformity_closure {p : ι → Prop} {U : ι → set (α × α)}
(h : (𝓤 α).has_basis p U) : (𝓤 α).has_basis p (λ i, closure (U i)) :=
(@uniformity_eq_uniformity_closure α _).symm ▸ h.lift'_closure
/-- Closed entourages form a basis of the uniformity filter. -/
lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure :=
(𝓤 α).basis_sets.uniformity_closure
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) :=
calc closure t = ⋂ V (hV : V ∈ 𝓤 α ∧ symmetric_rel V), V ○ t ○ V : closure_eq_uniformity t
... = ⋂ V ∈ 𝓤 α, V ○ t ○ V : eq.symm $ uniform_space.has_basis_symmetric.bInter_mem $
λ V₁ V₂ hV, comp_rel_mono (comp_rel_mono hV subset.rfl) hV
... = ⋂ V ∈ 𝓤 α, V ○ (t ○ V) : by simp only [comp_rel_assoc]
lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_infi $ assume d, le_infi $ assume hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp
(comp_le_uniformity3 hd) in
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : ht.subset_interior_iff.mpr $
λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ 𝓤 α, by filter_upwards [hs] using this,
by simp [this])
(assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
interior s ∈ 𝓤 α :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) :
∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s :=
let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in
⟨t, ht_mem, htc, hts⟩
lemma is_open_iff_open_ball_subset {s : set α} :
is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s :=
begin
rw is_open_iff_ball_subset,
split; intros h x hx,
{ obtain ⟨V, hV, hV'⟩ := h x hx,
exact ⟨interior V, interior_mem_uniformity hV, is_open_interior,
(ball_mono interior_subset x).trans hV'⟩, },
{ obtain ⟨V, hV, -, hV'⟩ := h x hx,
exact ⟨V, hV, hV'⟩, },
end
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) :
(⋃ x ∈ s, ball x U) = univ :=
begin
refine Union₂_eq_univ_iff.2 (λ y, _),
rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩,
exact ⟨x, hxs, hxy⟩
end
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id :=
has_basis_self.2 $ λ s hs,
⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩
lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)}
(h : (𝓤 α).has_basis p s) {t : set (α × α)} :
t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t :=
h.mem_iff.trans $ by simp only [prod.forall, subset_def]
/-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
lemma uniformity_has_basis_open_symmetric :
has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id :=
begin
simp only [← and_assoc],
refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩),
exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩,
symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩
end
lemma comp_open_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, is_open t ∧ symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs,
obtain ⟨u, ⟨hu₁, hu₂, hu₃⟩, hu₄ : u ⊆ t⟩ := uniformity_has_basis_open_symmetric.mem_iff.mp ht₁,
exact ⟨u, hu₁, hu₂, hu₃, (comp_rel_mono hu₄ hu₄).trans ht₂⟩,
end
section
variable (α)
lemma uniform_space.has_seq_basis [is_countably_generated $ 𝓤 α] :
∃ V : ℕ → set (α × α), has_antitone_basis (𝓤 α) V ∧ ∀ n, symmetric_rel (V n) :=
let ⟨U, hsym, hbasis⟩ := uniform_space.has_basis_symmetric.exists_antitone_subbasis
in ⟨U, hbasis, λ n, (hsym n).2⟩
end
lemma filter.has_basis.bInter_bUnion_ball {p : ι → Prop} {U : ι → set (α × α)}
(h : has_basis (𝓤 α) p U) (s : set α) :
(⋂ i (hi : p i), ⋃ x ∈ s, ball x (U i)) = closure s :=
begin
ext x,
simp [mem_closure_iff_nhds_basis (nhds_basis_uniformity h), ball]
end
/-! ### Uniform continuity -/
/-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal
as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then
`f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/
def uniform_continuous [uniform_space β] (f : α → β) :=
tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β)
/-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to
the diagonal as `(x, y)` tends to the diagonal while remaining in `s ×ˢ s`.
In other words, if `x` is sufficiently close to `y`, then `f x` is close to
`f y` no matter where `x` and `y` are located in `s`.-/
def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop :=
tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s ×ˢ s)) (𝓤 β)
theorem uniform_continuous_def [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α :=
iff.rfl
theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r :=
iff.rfl
theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} :
uniform_continuous_on f univ ↔ uniform_continuous f :=
by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq]
lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) :
uniform_continuous c :=
have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from
eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b,
le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity
lemma uniform_continuous_id : uniform_continuous (@id α) :=
by simp [uniform_continuous]; exact tendsto_id
lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) :=
uniform_continuous_of_const $ λ _ _, rfl
lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β}
(hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
hg.comp hf
lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)}
(ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t)
{f : α → β} :
uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i :=
(ha.tendsto_iff hb).trans $ by simp only [prod.forall]
lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop}
{s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)}
(hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} :
uniform_continuous_on f S ↔
∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i :=
((ha.inf_principal (S ×ˢ S)).tendsto_iff hb).trans $
by simp_rw [prod.forall, set.inter_comm (s _), ball_mem_comm, mem_inter_iff, mem_prod, and_imp]
end uniform_space
open_locale uniformity
section constructions
instance : partial_order (uniform_space α) :=
{ le := λt s, t.uniformity ≤ s.uniformity,
le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_rfl,
le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ }
instance : has_Inf (uniform_space α) :=
⟨assume s, uniform_space.of_core
{ uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ assume u, le_infi $ assume hu, u.refl,
symm := le_infi $ assume u, le_infi $ assume hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ assume u, le_infi $ assume hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_rfl) u.comp }⟩
private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
Inf tt ≤ t :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') :
t ≤ Inf tt :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ assume t', le_infi $ assume ht', h t' ht'
instance : has_top (uniform_space α) :=
⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_bot (uniform_space α) :=
⟨{ to_topological_space := ⊥,
uniformity := 𝓟 id_rel,
refl := le_rfl,
symm := by simp [tendsto]; apply subset.refl,
comp :=
begin
rw [lift'_principal], {simp},
exact monotone_comp_rel monotone_id monotone_id
end,
is_open_uniformity :=
assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩
instance : has_inf (uniform_space α) :=
⟨λ u₁ u₂,
@uniform_space.replace_topology _
(u₁.to_topological_space ⊓ u₂.to_topological_space) (uniform_space.of_core
{ uniformity := u₁.uniformity ⊓ u₂.uniformity,
refl := le_inf u₁.refl u₂.refl,
symm := u₁.symm.inf u₂.symm,
comp := (lift'_inf_le _ _ _).trans $ inf_le_inf u₁.comp u₂.comp }) $
eq_of_nhds_eq_nhds $ λ a,
by simpa only [nhds_inf, nhds_eq_comap_uniformity] using comap_inf.symm⟩
instance : complete_lattice (uniform_space α) :=
{ sup := λa b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h),
le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h),
sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c h₁ h₂, show a.uniformity ≤ _, from le_inf h₁ h₂,
inf_le_left := λ a b, show _ ≤ a.uniformity, from inf_le_left,
inf_le_right := λ a b, show _ ≤ b.uniformity, from inf_le_right,
top := ⊤,
le_top := λ a, show a.uniformity ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ u, u.refl,
Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t},
le_Sup := λ s u h, le_Inf (λ u' h', h' u h),
Sup_le := λ s u h, Inf_le h,
Inf := Inf,
le_Inf := λ s a hs, le_Inf hs,
Inf_le := λ s a ha, Inf_le ha,
..uniform_space.partial_order }
lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} :
(infi u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from
le_antisymm
(le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _)
lemma infi_uniformity' {ι : Sort*} {u : ι → uniform_space α} :
@uniformity α (infi u) = (⨅i, @uniformity α (u i)) :=
infi_uniformity
lemma inf_uniformity {u v : uniform_space α} :
(u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity :=
rfl
lemma inf_uniformity' {u v : uniform_space α} :
@uniformity α (u ⊓ v) = @uniformity α u ⊓ @uniformity α v :=
rfl
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩
instance inhabited_uniform_space_core : inhabited (uniform_space.core α) :=
⟨@uniform_space.to_core _ default⟩
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)),
to_topological_space := u.to_topological_space.induced f,
refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl),
symm := by simp [tendsto_comap_iff, prod.swap, (∘)];
exact tendsto_swap_uniformity.comp tendsto_comap,
comp := le_trans
begin
rw [comap_lift'_eq, comap_lift'_eq2],
exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
exact monotone_comp_rel monotone_id monotone_id
end
(comap_mono u.comp),
is_open_uniformity := λ s, begin
change (@is_open α (u.to_topological_space.induced f) s ↔ _),
simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm],
refine ball_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩,
rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) },
{ rintro ⟨t, ht, hts⟩,
exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl,
mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ }
end }
lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β}
(h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) :
𝓤 α = comap (prod.map f f) (𝓤 β) :=
by { rw h, refl }
lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id :=
by ext u ; dsimp only [uniform_space.comap, id] ; rw [prod.id_prod, filter.comap_id]
lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
by ext ; dsimp only [uniform_space.comap] ; rw filter.comap_comap
lemma uniform_space.comap_inf {α γ} {u₁ u₂ : uniform_space γ} {f : α → γ} :
(u₁ ⊓ u₂).comap f = u₁.comap f ⊓ u₂.comap f :=
uniform_space_eq comap_inf
lemma uniform_space.comap_infi {ι α γ} {u : ι → uniform_space γ} {f : α → γ} :
(⨅ i, u i).comap f = ⨅ i, (u i).comap f :=
begin
ext : 1,
change (𝓤 _) = (𝓤 _),
simp [uniformity_comap rfl, infi_uniformity']
end
lemma uniform_space.comap_mono {α γ} {f : α → γ} :
monotone (λ u : uniform_space γ, u.comap f) :=
begin
intros u₁ u₂ hu,
change (𝓤 _) ≤ (𝓤 _),
rw uniformity_comap rfl,
exact comap_mono hu
end
lemma uniform_continuous_iff {α β} {uα : uniform_space α} {uβ : uniform_space β} {f : α → β} :
uniform_continuous f ↔ uα ≤ uβ.comap f :=
filter.map_le_iff_le_comap
lemma le_iff_uniform_continuous_id {u v : uniform_space α} :
u ≤ v ↔ @uniform_continuous _ _ u v id :=
by rw [uniform_continuous_iff, uniform_space_comap_id, id]
lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] :
@uniform_continuous α β (uniform_space.comap f u) u f :=
tendsto_comap
theorem to_topological_space_comap {f : α → β} {u : uniform_space β} :
@uniform_space.to_topological_space _ (uniform_space.comap f u) =
topological_space.induced f (@uniform_space.to_topological_space β u) := rfl
lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α]
(h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g :=
tendsto_comap_iff.2 h
lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) :
@nhds _ (@uniform_space.to_topological_space _ u₁) a ≤
@nhds _ (@uniform_space.to_topological_space _ u₂) a :=
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl)
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
@uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ :=
le_of_nhds_le_nhds $ to_nhds_mono h
lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf
lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl
lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ :=
top_unique $ assume s hs, s.eq_empty_or_nonempty.elim
(assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤)
(assume ⟨x, hx⟩,
have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl,
this.symm ▸ @is_open_univ _ ⊤)
lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} :
(infi u).to_topological_space = ⨅i, (u i).to_topological_space :=
begin
refine (eq_of_nhds_eq_nhds $ assume a, _),
rw [nhds_infi, nhds_eq_uniformity],
change (infi u).uniformity.lift' (preimage $ prod.mk a) = _,
rw [infi_uniformity, lift'_infi_of_map_univ _ preimage_univ],
{ simp only [nhds_eq_uniformity], refl },
{ exact ball_inter _ }
end
lemma to_topological_space_Inf {s : set (uniform_space α)} :
(Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) :=
begin
rw [Inf_eq_infi],
simp only [← to_topological_space_infi],
end
lemma to_topological_space_inf {u v : uniform_space α} :
(u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space :=
rfl
/-- Uniform space structure on `ulift α`. -/
instance ulift.uniform_space [uniform_space α] : uniform_space (ulift α) :=
uniform_space.comap ulift.down ‹_›
section uniform_continuous_infi
lemma uniform_continuous_inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ u₃ : uniform_space β}
(h₁ : @@uniform_continuous u₁ u₂ f) (h₂ : @@uniform_continuous u₁ u₃ f) :
@@uniform_continuous u₁ (u₂ ⊓ u₃) f :=
tendsto_inf.mpr ⟨h₁, h₂⟩
lemma uniform_continuous_inf_dom_left {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₁ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_left hf
lemma uniform_continuous_inf_dom_right {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₂ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_right hf
lemma uniform_continuous_Inf_dom {f : α → β} {u₁ : set (uniform_space α)} {u₂ : uniform_space β}
{u : uniform_space α} (h₁ : u ∈ u₁) (hf : @@uniform_continuous u u₂ f) :
@@uniform_continuous (Inf u₁) u₂ f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi' ⟨u, h₁⟩ hf
end
lemma uniform_continuous_Inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ : set (uniform_space β)}
(h : ∀u∈u₂, @@uniform_continuous u₁ u f) : @@uniform_continuous u₁ (Inf u₂) f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi.mpr (λ ⟨u, hu⟩, h u hu)
end
lemma uniform_continuous_infi_dom {f : α → β} {u₁ : ι → uniform_space α} {u₂ : uniform_space β}
{i : ι} (hf : @@uniform_continuous (u₁ i) u₂ f) : @@uniform_continuous (infi u₁) u₂ f :=
begin
rw [uniform_continuous, infi_uniformity'],
exact tendsto_infi' i hf
end
lemma uniform_continuous_infi_rng {f : α → β} {u₁ : uniform_space α} {u₂ : ι → uniform_space β}
(h : ∀i, @@uniform_continuous u₁ (u₂ i) f) : @@uniform_continuous u₁ (infi u₂) f :=
by rwa [uniform_continuous, infi_uniformity', tendsto_infi]
end uniform_continuous_infi
/-- A uniform space with the discrete uniformity has the discrete topology. -/
lemma discrete_topology_of_discrete_uniformity [hα : uniform_space α]
(h : uniformity α = 𝓟 id_rel) :
discrete_topology α :=
⟨(uniform_space_eq h.symm : ⊥ = hα) ▸ rfl⟩
instance : uniform_space empty := ⊥
instance : uniform_space punit := ⊥
instance : uniform_space bool := ⊥
instance : uniform_space ℕ := ⊥
instance : uniform_space ℤ := ⊥
section
variables [uniform_space α]
open additive multiplicative
instance : uniform_space (additive α) := ‹uniform_space α›
instance : uniform_space (multiplicative α) := ‹uniform_space α›
lemma uniform_continuous_of_mul : uniform_continuous (of_mul : α → additive α) :=
uniform_continuous_id
lemma uniform_continuous_to_mul : uniform_continuous (to_mul : additive α → α) :=
uniform_continuous_id
lemma uniform_continuous_of_add : uniform_continuous (of_add : α → multiplicative α) :=
uniform_continuous_id
lemma uniform_continuous_to_add : uniform_continuous (to_add : multiplicative α → α) :=
uniform_continuous_id
lemma uniformity_additive : 𝓤 (additive α) = (𝓤 α).map (prod.map of_mul of_mul) :=
by { convert map_id.symm, exact prod.map_id }
lemma uniformity_multiplicative : 𝓤 (multiplicative α) = (𝓤 α).map (prod.map of_add of_add) :=
by { convert map_id.symm, exact prod.map_id }
end
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.comap subtype.val t
lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] :
𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) :=
rfl
lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] :
uniform_continuous (subtype.val : {a : α // p a} → α) :=
uniform_continuous_comap
lemma uniform_continuous_subtype_coe {p : α → Prop} [uniform_space α] :
uniform_continuous (coe : {a : α // p a} → α) :=
uniform_continuous_subtype_val
lemma uniform_continuous.subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β]
{f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) :
uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) :=
uniform_continuous_comap' hf
lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} :
uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) :=
begin
unfold uniform_continuous_on set.restrict uniform_continuous tendsto,
rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl,
uniformity_comap rfl,
show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl],
conv in (map _ (comap _ _)) { rw ← filter.map_map },
rw subtype_coe_map_comap_prod, refl,
end
lemma tendsto_of_uniform_continuous_subtype
[uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) :
tendsto f (𝓝 a) (𝓝 (f a)) :=
by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact
tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _)
lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} (h : uniform_continuous_on f s) : continuous_on f s :=
begin
rw uniform_continuous_on_iff_restrict at h,
rw continuous_on_iff_continuous_restrict,
exact h.continuous
end
@[to_additive]
instance [uniform_space α] : uniform_space (αᵐᵒᵖ) :=
uniform_space.comap mul_opposite.unop ‹_›
@[to_additive]
lemma uniformity_mul_opposite [uniform_space α] :
𝓤 (αᵐᵒᵖ) = comap (λ q : αᵐᵒᵖ × αᵐᵒᵖ, (q.1.unop, q.2.unop)) (𝓤 α) :=
rfl
@[simp, to_additive] lemma comap_uniformity_mul_opposite [uniform_space α] :
comap (λ p : α × α, (mul_opposite.op p.1, mul_opposite.op p.2)) (𝓤 αᵐᵒᵖ) = 𝓤 α :=
by simpa [uniformity_mul_opposite, comap_comap, (∘)] using comap_id
namespace mul_opposite
@[to_additive]
lemma uniform_continuous_unop [uniform_space α] : uniform_continuous (unop : αᵐᵒᵖ → α) :=
uniform_continuous_comap
@[to_additive]
lemma uniform_continuous_op [uniform_space α] : uniform_continuous (op : α → αᵐᵒᵖ) :=
uniform_continuous_comap' uniform_continuous_id
end mul_opposite
section prod
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) :=
u₁.comap prod.fst ⊓ u₂.comap prod.snd
-- check the above produces no diamond
example [u₁ : uniform_space α] [u₂ : uniform_space β] :
(prod.topological_space : topological_space (α × β)) = uniform_space.to_topological_space :=
rfl
theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) =
(𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓
(𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) :=
rfl
lemma uniformity_prod_eq_comap_prod [uniform_space α] [uniform_space β] :
𝓤 (α × β) = comap (λ p : (α × β) × (α × β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
by rw [uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap]
lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] :
𝓤 (α × β) = map (λ p : (α × α) × (β × β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
by rw [map_swap4_eq_comap, uniformity_prod_eq_comap_prod]
lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] [uniform_space β]
{s : set (β × β)} {f : α → α → β} (hf : uniform_continuous (λ p : α × α, f p.1 p.2))
(hs : s ∈ 𝓤 β) :
∃ u ∈ 𝓤 α, ∀ a b c, (a, b) ∈ u → (f a c, f b c) ∈ s :=
begin
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf,
rcases mem_prod_iff.1 (mem_map.1 $ hf hs) with ⟨u, hu, v, hv, huvt⟩,
exact ⟨u, hu, λ a b c hab, @huvt ((_, _), (_, _)) ⟨hab, refl_mem_uniformity hv⟩⟩
end
lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)}
{b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) :
{p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) :=
by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb)
lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono inf_le_left) map_comap_le
lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono inf_le_right) map_comap_le
lemma uniform_continuous_fst [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.1) :=
tendsto_prod_uniformity_fst
lemma uniform_continuous_snd [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.2) :=
tendsto_prod_uniformity_snd
variables [uniform_space α] [uniform_space β] [uniform_space γ]
lemma uniform_continuous.prod_mk
{f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) :
uniform_continuous (λa, (f₁ a, f₂ a)) :=
by rw [uniform_continuous, uniformity_prod]; exact
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) :
uniform_continuous (λ a, f (a,b)) :=
h.comp (uniform_continuous_id.prod_mk uniform_continuous_const)
lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) :
uniform_continuous (λ b, f (a,b)) :=
h.comp (uniform_continuous_const.prod_mk uniform_continuous_id)
lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (prod.map f g) :=
(hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd)
lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] :
@uniform_space.to_topological_space (α × β) prod.uniform_space =
@prod.topological_space α β u.to_topological_space v.to_topological_space := rfl
/-- A version of `uniform_continuous_inf_dom_left` for binary functions -/
lemma uniform_continuous_inf_dom_left₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua1; haveI := ub1; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_left₂`
have ha := @uniform_continuous_inf_dom_left _ _ id ua1 ua2 ua1 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_left _ _ id ub1 ub2 ub1 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (
ua1 ⊓ ua2) (ub1 ⊓ ub2) ua1 ub1 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_inf_dom_right` for binary functions -/
lemma uniform_continuous_inf_dom_right₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua2; haveI := ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_right₂`
have ha := @uniform_continuous_inf_dom_right _ _ id ua1 ua2 ua2 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_right _ _ id ub1 ub2 ub2 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _
(ua1 ⊓ ua2) (ub1 ⊓ ub2) ua2 ub2 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_Inf_dom` for binary functions -/
lemma uniform_continuous_Inf_dom₂ {α β γ} {f : α → β → γ}
{uas : set (uniform_space α)} {ubs : set (uniform_space β)}
{ua : uniform_space α} {ub : uniform_space β} {uc : uniform_space γ}
(ha : ua ∈ uas) (hb : ub ∈ ubs)
(hf : uniform_continuous (λ p : α × β, f p.1 p.2)):
by haveI := Inf uas; haveI := Inf ubs;
exact @uniform_continuous _ _ _ uc (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_Inf_dom`
let t : uniform_space (α × β) := prod.uniform_space,
have ha := uniform_continuous_Inf_dom ha uniform_continuous_id,
have hb := uniform_continuous_Inf_dom hb uniform_continuous_id,
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (Inf uas) (Inf ubs) ua ub _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_unif_cont_id,
end
end prod
section
open uniform_space function
variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
[uniform_space δ']
local notation f ` ∘₂ ` g := function.bicompr f g
/-- Uniform continuity for functions of two variables. -/
def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f)
lemma uniform_continuous₂_def (f : α → β → γ) :
uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl
lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) :
uniform_continuous (uncurry f) := h
lemma uniform_continuous₂_curry (f : α × β → γ) :
uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
by rw [uniform_continuous₂, uncurry_curry]
lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ}
(hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (g ∘₂ f) :=
hg.comp hf
lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β}
(hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) :
uniform_continuous₂ (bicompl f ga gb) :=
hf.uniform_continuous.comp (hga.prod_map hgb)
end
lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} :
@uniform_space.to_topological_space (subtype p) subtype.uniform_space =
@subtype.topological_space α p u.to_topological_space := rfl
section sum
variables [uniform_space α] [uniform_space β]
open sum
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum : uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β))
(λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂])
(λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩)
(λ r ⟨Hrα, Hrβ⟩, begin
rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩,
rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩,
refine ⟨_,
⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩,
rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩,
⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩,
{ have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩,
exact Htα A },
{ have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩,
exact Htβ A }
end)
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
lemma union_mem_uniformity_sum
{a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) :
((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈
(@uniform_space.core.sum α β _ _).uniformity :=
⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
{ p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity :=
begin
cases x,
{ refine mem_of_superset
(union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs))
univ_mem)
(union_subset _ _);
rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
{ refine mem_of_superset
(union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1
(is_open.mem_nhds hs.2 xs)))
(union_subset _ _);
rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
end
lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)}
(hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈
(@uniform_space.core.sum α β _ _).uniformity) :
is_open s :=
begin
split,
{ refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl },
{ refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }
end
/- We can now define the uniform structure on the disjoint union -/
instance sum.uniform_space : uniform_space (α ⊕ β) :=
{ to_core := uniform_space.core.sum,
is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ }
lemma sum.uniformity : 𝓤 (α ⊕ β) =
map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔
map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl
end sum
end constructions
-- For a version of the Lebesgue number lemma assuming only a sequentially compact space,
-- see topology/sequences.lean
/-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/
lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α}
(hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i :=
begin
let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i},
have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n),
{ refine λ n hn, is_open_uniformity.2 _,
rintro x ⟨i, m, hm, h⟩,
rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩,
apply (𝓤 α).sets_of_superset hm',
rintros ⟨x, y⟩ hp rfl,
refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩,
dsimp [-mem_comp_rel] at hz ⊢, rw comp_rel_assoc,
exact ⟨y, hp, hz⟩ },
have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n,
{ intros x hx,
rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩,
rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩,
exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ },
rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩,
refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩,
rcases mem_Union₂.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩,
refine ⟨i, λ y hy, h _⟩,
exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy)
end
/-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/
lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma hs (by simpa) hc₂
/-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an
open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of
`K` is contained in `U`. -/
lemma lebesgue_number_of_compact_open [uniform_space α]
{K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) :
∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U :=
begin
let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2,
have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U,
{ intros k,
obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)),
exact ⟨h₁, h₂, h₃⟩, },
let c : K → set α := λ k, uniform_space.ball k.1 (W k),
have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, },
have hc₂ : K ⊆ ⋃ i, c i,
{ intros k hk,
simp only [mem_Union, set_coe.exists],
exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, },
have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, },
obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂,
refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩,
intros k hk,
obtain ⟨k', hk'⟩ := hV' k hk,
exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'),
end
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace uniform
variables [uniform_space α]
theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) :=
⟨λ H, tendsto_left_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩
theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) :=
⟨λ H, tendsto_right_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩
theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_right]
theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_left]
theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) :=
⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _),
λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩
theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_right]
theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_left]
theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_right]
theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_left]
theorem continuous_iff'_right [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right
theorem continuous_iff'_left [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left
end uniform
lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto g l (𝓝 b) :=
uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg
lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) :=
⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
|
1033a8ded6fa7f338d22a8488b950cf3ff2d2eda | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/move_add.lean | fa37e265409df4683541bdde29e1f849028d3591 | [
"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 | 4,214 | lean | import tactic.move_add
import data.list.of_fn
import algebra.group.pi
variables {R : Type*} [add_comm_semigroup R] {a b c d e f g h : R}
example (e f g : R) (h : a + b + c = d) : b + (a + c) = d :=
begin
success_if_fail_with_msg {move_add [d] at *} "'d' is an unused variable",
move_add at *,
success_if_fail_with_msg {move_add at *} "nothing changed",
success_if_fail_with_msg {move_add [a, e, f, g] at h a b c ⊢}
"'[a, b, c]' did not change\n'[e, f, g]' are unused variables",
success_if_fail_with_msg {move_add [a, e, f, g] at h ⊢} "'[e, f, g]' are unused variables",
success_if_fail_with_msg {move_add at ⊢ h} "Goal did not change\n'[h]' did not change",
move_add ← a at *, -- `move_add` closes the goal, since, after rearranging, it tries `assumption`
end
example {R : Type*} [comm_semigroup R] (a b c d e f g : R) (h : a * b * c = d) : b * (a * c) = d :=
begin
success_if_fail_with_msg {move_mul [d] at *} "'d' is an unused variable",
move_mul at *,
success_if_fail_with_msg {move_mul at *} "nothing changed",
success_if_fail_with_msg {move_mul [a, e, f, g] at h a b c ⊢}
"'[a, b, c]' did not change\n'[e, f, g]' are unused variables",
success_if_fail_with_msg {move_mul [a, e, f, g] at h ⊢} "'[e, f, g]' are unused variables",
success_if_fail_with_msg {move_mul at ⊢ h} "Goal did not change\n'[h]' did not change",
success_if_fail_with_msg {move_mul at ⊢} "Goal did not change",
move_mul ← a at *, -- `move_mul` closes the goal, since, after rearranging, it tries `assumption`
end
example : let k := c + (a + b) in k = a + b + c :=
begin
move_add [← a, c],
simp only,
end
example (n : ℕ) : list.of_fn (λ i : fin (n + 3), (i : ℕ)) = list.of_fn (λ i : fin (3 + n), i) :=
begin
move_add [←n],
end
example (a b : ℕ) : a + max a b = max b a + a :=
begin
move_oper [max] ← a at *,
move_oper [(+)] a at *,
end
example (h : b + a = b + c + a) : a + b = a + b + c :=
by move_add [a]
example {R : Type*} [comm_semigroup R] {a b : R} :
∀ x : R, ∃ y : R, a * x * b * y = x * y * b * a :=
by { move_mul [a, b], exact λ x, ⟨x, rfl⟩ }
example {R : Type*} [has_add R] [comm_semigroup R] {a b c d e f g : R} :
a * (b * c * a) * ((d * e) * e) * f * g = (c * b * a) * (e * (e * d)) * g * f * a :=
by move_mul [a, a, b, c, d, e, f]
example [has_mul R] [has_neg R] : a + (b + c + a) * (- (d + e) + e) + f + g =
(c + b + a) * (e + - (e + d)) + g + f + a :=
by move_add [b, d, g, f, a, e]
example (h : d + b + a = b + a → d + c + a = c + a) : a + d + b = b + a → d + c + a = a + c :=
by move_add [a]
example [decidable_eq R] : if b + a = c + a then a + b = c + a else a + b ≠ c + a :=
begin
move_add [← a],
split_ifs; exact h,
end
example (r : R → R → Prop) (h : r (a + b) (c + b + a)) : r (a + b) (a + b + c) :=
by move_add [a, b, c] at h
example (h : a + c + b = a + d + b) : c + b + a = b + a + d :=
by move_add [← a, b] -- Goal before `exact h`: `a + c + b = a + d + b`
example [has_mul R] (h : a * c + c + b * c = a * d + d + b * d) :
c + b * c + a * c = a * d + d + b * d :=
begin
-- the first input `_ * c` unifies with `b * c` and moves to the right
-- the second input `_ * c` unifies with `a * c` and moves to the left
move_add [_ * c, ← _ * c], -- Goal before `exact h`: `a * c + c + b * c = a * d + d + b * d`
end
variables [has_mul R] [has_one R] {X r s t u : R} (C D E : R → R)
example (he : E (C r * D X + D X * h + 7 + 42 + f) = C r * D X + h * D X + 7 + 42 + g) :
E (7 + f + (C r * D X + 42) + D X * h) = C r * D X + h * D X + g + 7 + 42 :=
begin
-- move `7, 42, f, g` to the right of their respective sides
move_add [(7 : R), (42 : R), f, g],
end
example : true :=
begin
letI iacs : ∀ i, add_comm_semigroup (fin i → ℕ) := λ i, by apply_instance,
letI ia : ∀ i, has_add (fin i → ℕ) := λ i,
@add_semigroup.to_has_add _
(@add_comm_semigroup.to_add_semigroup _ (iacs i)),
-- move_add should work if there are unified metavariables
have : ∀ (a b : fin _ → ℕ), @has_add.add _ (ia _) a b = @has_add.add _ (ia _) b a,
{ intros a b,
move_add [a] },
trivial, -- close the outer goal
exact 37 -- resolve the metavariable
end
|
26f4165f2f32eb609ccdd0444f32090d40bc060e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/euclidean/triangle.lean | 7e8e292c870a9d6fba938328da44215151a9e9ca | [
"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,131 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import geometry.euclidean.angle.oriented.affine
import geometry.euclidean.angle.unoriented.affine
import tactic.interval_cases
/-!
# Triangles
This file proves basic geometrical results about distances and angles
in (possibly degenerate) triangles in real inner product spaces and
Euclidean affine spaces. More specialized results, and results
developed for simplices in general rather than just for triangles, are
in separate files. Definitions and results that make sense in more
general affine spaces rather than just in the Euclidean case go under
`linear_algebra.affine_space`.
## Implementation notes
Results in this file are generally given in a form with only those
non-degeneracy conditions needed for the particular result, rather
than requiring affine independence of the points of a triangle
unnecessarily.
## References
* https://en.wikipedia.org/wiki/Law_of_cosines
* https://en.wikipedia.org/wiki/Pons_asinorum
* https://en.wikipedia.org/wiki/Sum_of_angles_of_a_triangle
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace inner_product_geometry
/-!
### Geometrical results on triangles in real inner product spaces
This section develops some results on (possibly degenerate) triangles
in real inner product spaces, where those definitions and results can
most conveniently be developed in terms of vectors and then used to
deduce corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℝ V]
/-- Law of cosines (cosine rule), vector angle form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(x y : V) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - 2 * ‖x‖ * ‖y‖ * real.cos (angle x y) :=
by rw [(show 2 * ‖x‖ * ‖y‖ * real.cos (angle x y) =
2 * (real.cos (angle x y) * (‖x‖ * ‖y‖)), by ring),
cos_angle_mul_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm,
←real_inner_self_eq_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm,
real_inner_sub_sub_self, sub_add_eq_add_sub]
/-- Pons asinorum, vector angle form. -/
lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) :
angle x (x - y) = angle y (y - x) :=
begin
refine real.inj_on_cos ⟨angle_nonneg _ _, angle_le_pi _ _⟩ ⟨angle_nonneg _ _, angle_le_pi _ _⟩ _,
rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub,
inner_sub_right, inner_sub_right, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm, h, real_inner_comm x y]
end
/-- Converse of pons asinorum, vector angle form. -/
lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V}
(h : angle x (x - y) = angle y (y - x)) (hpi : angle x y ≠ π) : ‖x‖ = ‖y‖ :=
begin
replace h := real.arccos_inj_on
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x (x - y)))
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one y (y - x))) h,
by_cases hxy : x = y,
{ rw hxy },
{ rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm ‖y‖, div_eq_mul_inv, div_eq_mul_inv,
mul_inv_rev, mul_inv_rev, ←mul_assoc, ←mul_assoc] at h,
replace h :=
mul_right_cancel₀ (inv_ne_zero (λ hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h,
rw [inner_sub_right, inner_sub_right, real_inner_comm x y, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm, mul_sub_right_distrib, mul_sub_right_distrib,
mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub,
←mul_sub_left_distrib] at h,
by_cases hx0 : x = 0,
{ rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h,
rw [hx0, norm_zero, h] },
{ by_cases hy0 : y = 0,
{ rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h,
rw [hy0, norm_zero, h] },
{ rw [inv_sub_inv (λ hz, hx0 (norm_eq_zero.1 hz)) (λ hz, hy0 (norm_eq_zero.1 hz)),
←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h,
symmetry,
by_contradiction hyx,
replace h := (mul_left_cancel₀ (sub_ne_zero_of_ne hyx) h).symm,
rw [real_inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h,
exact hpi h } } }
end
/-- The cosine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.cos_add, cos_angle, cos_angle, cos_angle],
have hxn : ‖x‖ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ‖y‖ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ‖x - y‖ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel₀ hxn,
apply mul_right_cancel₀ hyn,
apply mul_right_cancel₀ hxyn,
apply mul_right_cancel₀ hxyn,
have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) *
‖x‖ * ‖y‖ * ‖x - y‖ * ‖x - y‖ =
(real.sin (angle x (x - y)) * (‖x‖ * ‖x - y‖)) *
(real.sin (angle y (y - x)) * (‖y‖ * ‖x - y‖)), { ring },
have H2 : ⟪x, x⟫ * (⟪x, x⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪y, y⟫)) -
(⟪x, x⟫ - ⟪x, y⟫) * (⟪x, x⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
have H3 : ⟪y, y⟫ * (⟪y, y⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪x, x⟫)) -
(⟪y, y⟫ - ⟪x, y⟫) * (⟪y, y⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib,
mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y,
sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left,
inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H2,
H3, real.mul_self_sqrt (sub_nonneg_of_le (real_inner_mul_inner_self_le x y)),
real_inner_self_eq_norm_mul_norm, real_inner_self_eq_norm_mul_norm,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The sine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.sin_add, cos_angle, cos_angle],
have hxn : ‖x‖ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ‖y‖ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ‖x - y‖ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel₀ hxn,
apply mul_right_cancel₀ hyn,
apply mul_right_cancel₀ hxyn,
apply mul_right_cancel₀ hxyn,
have H1 : real.sin (angle x (x - y)) * (⟪y, y - x⟫ / (‖y‖ * ‖y - x‖)) * ‖x‖ * ‖y‖ * ‖x - y‖ =
real.sin (angle x (x - y)) * (‖x‖ * ‖x - y‖) *
(⟪y, y - x⟫ / (‖y‖ * ‖y - x‖)) * ‖y‖, { ring },
have H2 : ⟪x, x - y⟫ / (‖x‖ * ‖y - x‖) * real.sin (angle y (y - x)) * ‖x‖ * ‖y‖ * ‖y - x‖ =
⟪x, x - y⟫ / (‖x‖ * ‖y - x‖) *
(real.sin (angle y (y - x)) * (‖y‖ * ‖y - x‖)) * ‖x‖, { ring },
have H3 : ⟪x, x⟫ * (⟪x, x⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪y, y⟫)) -
(⟪x, x⟫ - ⟪x, y⟫) * (⟪x, x⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
have H4 : ⟪y, y⟫ * (⟪y, y⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪x, x⟫)) -
(⟪y, y⟫ - ⟪x, y⟫) * (⟪y, y⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
rw [right_distrib, right_distrib, right_distrib, right_distrib, H1,
sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm,
norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm,
inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right,
inner_sub_right, real_inner_comm x y, H3, H4, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The cosine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 :=
by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, mul_neg, ←neg_add',
add_comm, ←sq, ←sq, real.sin_sq_add_cos_sq]
/-- The sine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 :=
begin
rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy],
ring
end
/-- The sum of the angles of a possibly degenerate triangle (where the
two given sides are nonzero), vector angle form. -/
lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
angle x y + angle x (x - y) + angle y (y - x) = π :=
begin
have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy,
have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy,
rw real.sin_eq_zero_iff at hsin,
cases hsin with n hn,
symmetry' at hn,
have h0 : 0 ≤ angle x y + angle x (x - y) + angle y (y - x) :=
add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _),
have h3 : angle x y + angle x (x - y) + angle y (y - x) ≤ π + π + π :=
add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _),
have h3lt : angle x y + angle x (x - y) + angle y (y - x) < π + π + π,
{ by_contradiction hnlt,
have hxy : angle x y = π,
{ by_contradiction hxy,
exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le
(lt_of_le_of_ne (angle_le_pi _ _) hxy)
(angle_le_pi _ _)) (angle_le_pi _ _)) },
rw hxy at hnlt,
rw angle_eq_pi_iff at hxy,
rcases hxy with ⟨hx, ⟨r, ⟨hr, hxr⟩⟩⟩,
rw [hxr, ←one_smul ℝ x, ←mul_smul, mul_one, ←sub_smul, one_smul, sub_eq_add_neg,
angle_smul_right_of_pos _ _ (add_pos zero_lt_one (neg_pos_of_neg hr)), angle_self hx,
add_zero] at hnlt,
apply hnlt,
rw add_assoc,
exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _)
(lt_add_of_pos_right π real.pi_pos)) _ },
have hn0 : 0 ≤ n,
{ rw [hn, mul_nonneg_iff_left_nonneg_of_pos real.pi_pos] at h0,
norm_cast at h0,
exact h0 },
have hn3 : n < 3,
{ rw [hn, (show π + π + π = 3 * π, by ring)] at h3lt,
replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos),
norm_cast at h3lt,
exact h3lt },
interval_cases n,
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
{ rw hn,
norm_num },
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on triangles in Euclidean affine spaces
This section develops some geometrical definitions and results on
(possible degenerate) triangles in Euclidean affine spaces.
-/
open inner_product_geometry
open_locale euclidean_geometry
variables {V : Type*} {P : Type*}
[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]
include V
/-- **Law of cosines** (cosine rule), angle-at-point form. -/
lemma dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle
(p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 =
dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 -
2 * dist p1 p2 * dist p3 p2 * real.cos (∠ p1 p2 p3) :=
begin
rw [dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p3 p2],
unfold angle,
convert norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(p1 -ᵥ p2 : V) (p3 -ᵥ p2 : V),
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm },
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm }
end
alias dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle ← law_cos
/-- **Isosceles Triangle Theorem**: Pons asinorum, angle-at-point form. -/
lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) :
∠ p1 p2 p3 = ∠ p1 p3 p2 :=
begin
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3] at h,
unfold angle,
convert angle_sub_eq_angle_sub_rev_of_norm_eq h,
{ exact (vsub_sub_vsub_cancel_left p3 p2 p1).symm },
{ exact (vsub_sub_vsub_cancel_left p2 p3 p1).symm }
end
/-- Converse of pons asinorum, angle-at-point form. -/
lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = ∠ p1 p3 p2)
(hpi : ∠ p2 p1 p3 ≠ π) : dist p1 p2 = dist p1 p3 :=
begin
unfold angle at h hpi,
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3],
rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi,
rw [←vsub_sub_vsub_cancel_left p3 p2 p1, ←vsub_sub_vsub_cancel_left p2 p3 p1] at h,
exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi
end
/-- The **sum of the angles of a triangle** (possibly degenerate, where the
given vertex is distinct from the others), angle-at-point. -/
lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 ≠ p1) (h3 : p3 ≠ p1) :
∠ p1 p2 p3 + ∠ p2 p3 p1 + ∠ p3 p1 p2 = π :=
begin
rw [add_assoc, add_comm, add_comm (∠ p2 p3 p1), angle_comm p2 p3 p1],
unfold angle,
rw [←angle_neg_neg (p1 -ᵥ p3), ←angle_neg_neg (p1 -ᵥ p2), neg_vsub_eq_vsub_rev,
neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev,
←vsub_sub_vsub_cancel_right p3 p2 p1, ←vsub_sub_vsub_cancel_right p2 p3 p1],
exact angle_add_angle_sub_add_angle_sub_eq_pi (λ he, h3 (vsub_eq_zero_iff_eq.1 he))
(λ he, h2 (vsub_eq_zero_iff_eq.1 he))
end
/-- The **sum of the angles of a triangle** (possibly degenerate, where the triangle is a line),
oriented angles at point. -/
lemma oangle_add_oangle_add_oangle_eq_pi
[module.oriented ℝ V (fin 2)] [fact (finite_dimensional.finrank ℝ V = 2)] {p1 p2 p3 : P}
(h21 : p2 ≠ p1) (h32 : p3 ≠ p2) (h13 : p1 ≠ p3) : ∡ p1 p2 p3 + ∡ p2 p3 p1 + ∡ p3 p1 p2 = π :=
by simpa only [neg_vsub_eq_vsub_rev] using
positive_orientation.oangle_add_cyc3_neg_left
(vsub_ne_zero.mpr h21) (vsub_ne_zero.mpr h32) (vsub_ne_zero.mpr h13)
/-- **Stewart's Theorem**. -/
theorem dist_sq_mul_dist_add_dist_sq_mul_dist (a b c p : P) (h : ∠ b p c = π) :
dist a b ^ 2 * dist c p + dist a c ^ 2 * dist b p =
dist b c * (dist a p ^ 2 + dist b p * dist c p) :=
begin
rw [pow_two, pow_two, law_cos a p b, law_cos a p c,
eq_sub_of_add_eq (angle_add_angle_eq_pi_of_angle_eq_pi a h), real.cos_pi_sub,
dist_eq_add_dist_of_angle_eq_pi h],
ring,
end
/-- **Apollonius's Theorem**. -/
theorem dist_sq_add_dist_sq_eq_two_mul_dist_midpoint_sq_add_half_dist_sq (a b c : P) :
dist a b ^ 2 + dist a c ^ 2 = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) :=
begin
by_cases hbc : b = c,
{ simp [hbc, midpoint_self, dist_self, two_mul] },
{ let m := midpoint ℝ b c,
have : dist b c ≠ 0 := (dist_pos.mpr hbc).ne',
have hm := dist_sq_mul_dist_add_dist_sq_mul_dist a b c m (angle_midpoint_eq_pi b c hbc),
simp only [dist_left_midpoint, dist_right_midpoint, real.norm_two] at hm,
calc dist a b ^ 2 + dist a c ^ 2
= 2 / dist b c * (dist a b ^ 2 * (2⁻¹ * dist b c) + dist a c ^ 2 * (2⁻¹ * dist b c)) :
by { field_simp, ring }
... = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) :
by { rw hm, field_simp, ring } },
end
lemma dist_mul_of_eq_angle_of_dist_mul (a b c a' b' c' : P) (r : ℝ) (h : ∠ a' b' c' = ∠ a b c)
(hab : dist a' b' = r * dist a b) (hcb : dist c' b' = r * dist c b) :
dist a' c' = r * dist a c :=
begin
have h' : dist a' c' ^ 2 = (r * dist a c) ^ 2,
calc dist a' c' ^ 2
= dist a' b' ^ 2 + dist c' b' ^ 2 - 2 * dist a' b' * dist c' b' * real.cos (∠ a' b' c') :
by { simp [pow_two, law_cos a' b' c'] }
... = r ^ 2 * (dist a b ^ 2 + dist c b ^ 2 - 2 * dist a b * dist c b * real.cos (∠ a b c)) :
by { rw [h, hab, hcb], ring }
... = (r * dist a c) ^ 2 : by simp [pow_two, ← law_cos a b c, mul_pow],
by_cases hab₁ : a = b,
{ have hab'₁ : a' = b', { rw [← dist_eq_zero, hab, dist_eq_zero.mpr hab₁, mul_zero r] },
rw [hab₁, hab'₁, dist_comm b' c', dist_comm b c, hcb] },
{ have h1 : 0 ≤ r * dist a b, { rw ← hab, exact dist_nonneg },
have h2 : 0 ≤ r := nonneg_of_mul_nonneg_left h1 (dist_pos.mpr hab₁),
exact (sq_eq_sq dist_nonneg (mul_nonneg h2 dist_nonneg)).mp h' },
end
end euclidean_geometry
|
36f5c717bd088e1b9fd47fd2b9a95609288d3d64 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/ind6.lean | ad1c594e9956b6e4d65cf2b8ba2978ecc446ae1b | [
"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 | 292 | lean | #exit
inductive tree.{u} (A : Type.{u}) : Type.{max u 1} :=
| node : A → forest.{u} A → tree.{u} A
with forest : Type.{max u 1} :=
| nil : forest.{u} A
| cons : tree.{u} A → forest.{u} A → forest.{u} A
#check tree.{1}
#check forest.{1}
#check tree.rec.{1 1}
#check forest.rec.{1 1}
|
7c75f7ffb6f2b89943489c22c3a4e2c2d493f00d | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/248.lean | f1816701438c6520a1055010775553b97c997bde | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 50 | lean | @[implementedBy foo] constant foo (x : Nat) : Nat
|
552fe000db293ef1518ed6498aa9f3a6a4650ebb | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /data/real/basic.lean | 966442820f3af80f2421994640f471347af647ef | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 26,935 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
The (classical) real numbers ℝ. This is a direct construction
from Cauchy sequences.
-/
import order.conditionally_complete_lattice data.real.cau_seq_completion
algebra.big_operators algebra.archimedean order.bounds
def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _
notation `ℝ` := real
local attribute [reducible] real
namespace real
open cau_seq cau_seq.completion
def of_rat (x : ℚ) : ℝ := of_rat x
instance : comm_ring ℝ := cau_seq.completion.comm_ring
/- Extra instances to short-circuit type class resolution -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := by apply_instance
instance : add_comm_group ℝ := by apply_instance
instance : add_group ℝ := by apply_instance
instance : add_comm_monoid ℝ := by apply_instance
instance : add_monoid ℝ := by apply_instance
instance : add_left_cancel_semigroup ℝ := by apply_instance
instance : add_right_cancel_semigroup ℝ := by apply_instance
instance : add_comm_semigroup ℝ := by apply_instance
instance : add_semigroup ℝ := by apply_instance
instance : comm_monoid ℝ := by apply_instance
instance : monoid ℝ := by apply_instance
instance : comm_semigroup ℝ := by apply_instance
instance : semigroup ℝ := by apply_instance
instance : inhabited ℝ := ⟨0⟩
theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y :=
congr_arg mk (const_sub _ _)
instance : has_lt ℝ :=
⟨λ x y, quotient.lift_on₂ x y (<) $
λ f₁ g₁ f₂ g₂ hf hg, propext $
⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg),
λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
iff_of_eq (congr_arg pos (sub_zero f))
instance : has_le ℝ := ⟨λ x y, x < y ∨ x = y⟩
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
or_congr iff.rfl quotient.eq
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
quotient.induction_on₃ a b c (λ f g h,
iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub))
instance : linear_order ℝ :=
{ le := (≤), lt := (<),
le_refl := λ a, or.inr rfl,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ f g h, by simpa using le_trans,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa using lt_iff_le_not_le,
le_antisymm := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ f g,
le_total := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa using le_total f g }
instance : partial_order ℝ := by apply_instance
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt
protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
quotient.induction_on₂ a b $ λ f g, by simpa using cau_seq.mul_pos
instance : linear_ordered_comm_ring ℝ :=
{ add_le_add_left := λ a b h c,
(le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h,
zero_ne_one := ne_of_lt real.zero_lt_one,
mul_nonneg := λ a b a0 b0,
match a0, b0 with
| or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0)
| or.inr a0, _ := by simp [a0.symm]
| _, or.inr b0 := by simp [b0.symm]
end,
mul_pos := @real.mul_pos,
zero_lt_one := real.zero_lt_one,
add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h,
..real.comm_ring, ..real.linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_ring ℝ := by apply_instance
instance : ordered_ring ℝ := by apply_instance
instance : linear_ordered_semiring ℝ := by apply_instance
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_comm_group ℝ := by apply_instance
instance : ordered_cancel_comm_monoid ℝ := by apply_instance
instance : ordered_comm_monoid ℝ := by apply_instance
instance : domain ℝ := by apply_instance
local attribute [instance] classical.prop_decidable
noncomputable instance : discrete_linear_ordered_field ℝ :=
{ inv := has_inv.inv,
inv_mul_cancel := @cau_seq.completion.inv_mul_cancel _ _ _ _ _ _,
mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0],
inv_zero := inv_zero,
decidable_le := by apply_instance,
..real.linear_ordered_comm_ring }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_field ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance
noncomputable instance real.discrete_field : discrete_field ℝ := by apply_instance
noncomputable instance : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : integral_domain ℝ := by apply_instance
noncomputable instance : nonzero_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_order ℝ := by apply_instance
noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice.lattice ℝ := by apply_instance
noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance
noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance
noncomputable instance : lattice.has_inf ℝ := by apply_instance
noncomputable instance : lattice.has_sup ℝ := by apply_instance
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
eq_cast of_rat rfl of_rat_add of_rat_mul
theorem le_mk_of_forall_le {x : ℝ} {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
quotient.induction_on x $ λ g h, le_of_not_lt $
λ ⟨K, K0, hK⟩,
let ⟨i, H⟩ := exists_forall_ge_and h $
exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in
begin
apply not_lt_of_le (H _ (le_refl _)).1,
rw ← of_rat_eq_cast,
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1),
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
end
theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} :
(∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x
| ⟨i, H⟩ := by rw [← neg_le_neg_iff, mk_neg]; exact
le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $
H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1,
sub_le.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f,
let ⟨M, M0, H⟩ := f.bounded' 0 in
⟨M, mk_le_of_forall_le ⟨0, λ i _,
rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩
noncomputable instance : floor_ring ℝ := archimedean.floor_ring _
theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) :=
⟨λ H ε ε0,
let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in
(H _ δ0).imp $ λ i hi j ij, lt_trans
(by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε,
λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $
λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩
theorem of_near (f : ℕ → ℚ) (x : ℝ)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) :
∃ h', cau_seq.completion.mk ⟨f, h'⟩ = x :=
⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h),
sub_eq_zero.1 $ abs_eq_zero.1 $
eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0,
mk_near_of_forall_near $
(h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩
theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧
∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩)
theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
| ⟨L, hL⟩ ⟨U, hU⟩ := begin
have,
{ refine λ d : ℕ, @int.exists_greatest_of_bdd
(λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _,
{ cases exists_int_gt U with k hk,
refine ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (le_trans hy _),
simp,
exact mul_le_mul_of_nonneg_right
(le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) },
{ exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } },
cases classical.axiom_of_choice this with f hf,
dsimp at f hf,
have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0,
let ⟨y, yS, hy⟩ := (hf n).1 in
⟨y, yS, by simpa using (div_le_iff (nat.cast_pos.2 n0)).2 hy⟩,
have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ),
{ intros n n0 y yS,
have := lt_of_lt_of_le (sub_one_lt_floor _)
(int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩),
simp [-sub_eq_add_neg],
rwa [lt_div_iff (nat.cast_pos.2 n0), sub_mul, _root_.inv_mul_cancel],
exact ne_of_gt (nat.cast_pos.2 n0) },
suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩,
{ refine le_of_forall_ge_of_dense (λ z xz, _),
cases exists_nat_gt (x - z)⁻¹ with K hK,
refine le_mk_of_forall_le ⟨K, λ n nK, _⟩,
replace xz := sub_pos.2 xz,
replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK),
refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS),
rwa [le_sub, inv_le (nat.cast_pos.2 n0) xz] },
{ exact mk_le_of_forall_le ⟨1, λ n n1,
let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ },
intros ε ε0,
suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩,
rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij },
intros j k ij ik,
replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij),
have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik),
rcases hf₁ _ j0 with ⟨y, yS, hy⟩,
refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _)
((inv_le ε0 (nat.cast_pos.2 k0)).1 ik),
simpa using sub_lt_iff_lt_add'.2
(lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS)
end
noncomputable def Sup (S : set ℝ) : ℝ :=
if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0
theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y :=
by simp [Sup, h₁, h₂]; exact
classical.some_spec (exists_sup S h₁ h₂) y
theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : y < Sup S ↔ ∃ z ∈ S, y < z :=
by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y)
theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S :=
(Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub :=
(Sup_le S h₁ ⟨_, h₂⟩).2 h₂
protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
is_lub s (Sup s) :=
⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S}
theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z :=
begin
refine le_neg.trans ((Sup_le _ _ _).trans _),
{ cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ },
{ cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ },
split; intros H z hz,
{ exact neg_le_neg_iff.1 (H _ $ by simp [hz]) },
{ exact le_neg.2 (H _ hz) }
end
theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : Inf S < y ↔ ∃ z ∈ S, z < y :=
by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y)
theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x :=
(le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S :=
(le_Inf S h₁ ⟨_, h₂⟩).2 h₂
open lattice
noncomputable instance lattice : lattice ℝ := by apply_instance
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := real.Sup,
Inf := real.Inf,
le_cSup :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s),
show a ≤ Sup s,
from le_Sup s ‹bdd_above s› ‹a ∈ s›,
cSup_le :=
assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a),
show Sup s ≤ a,
from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H,
cInf_le :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s),
show Inf s ≤ a,
from Inf_le s ‹bdd_below s› ‹a ∈ s›,
le_cInf :=
assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b),
show a ≤ Inf s,
from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H,
..real.linear_order, ..real.lattice}
theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 :=
show Inf ∅ = 0, by simp [Inf]; exact Sup_empty
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 :=
have bdd_above {x | -x ∈ s} → bdd_below s, from
assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb _ $ by simp [hxs]⟩,
have ¬ bdd_above {x | -x ∈ s}, from mt this hs,
neg_eq_zero.2 $ Sup_of_not_bdd_above $ this
theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x :=
begin
let S := {x : ℝ | const abs x < f},
have lb : ∃ x, x ∈ S := exists_lt f,
have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x :=
λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h,
have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub',
refine ⟨Sup S,
((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩,
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (Sup_le_ub S lb (ub' _ _))
((sub_lt_self_iff _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, sub_right_comm,
le_sub_iff_add_le, add_halves],
exact ih _ ij },
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (le_Sup S ub _)
((lt_add_iff_pos_left _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, add_comm, ← sub_sub,
le_sub_iff_add_le, add_halves],
exact ih _ ij }
end
section lim
open cau_seq
noncomputable def lim (f : ℕ → ℝ) : ℝ :=
if hf : is_cau_seq abs f then
classical.some (cau_seq_converges ⟨f, hf⟩)
else 0
theorem equiv_lim (f : cau_seq ℝ abs) : f ≈ const abs (lim f) :=
by simp [lim, f.is_cau]; cases f with f hf;
exact classical.some_spec (cau_seq_converges ⟨f, hf⟩)
lemma eq_lim_of_const_equiv {f : cau_seq ℝ abs} {x : ℝ} (h : cau_seq.const abs x ≈ f) : x = lim f :=
const_equiv.mp $ setoid.trans h $ equiv_lim f
lemma lim_eq_of_equiv_const {f : cau_seq ℝ abs} {x : ℝ} (h : f ≈ cau_seq.const abs x) : lim f = x :=
(eq_lim_of_const_equiv $ setoid.symm h).symm
lemma lim_eq_lim_of_equiv {f g : cau_seq ℝ abs} (h : f ≈ g) : lim f = lim g :=
lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g
@[simp] lemma lim_const (x : ℝ) : lim (const abs x) = x :=
lim_eq_of_equiv_const $ setoid.refl _
lemma lim_add (f g : cau_seq ℝ abs) : lim f + lim g = lim ⇑(f + g) :=
eq_lim_of_const_equiv $ show lim_zero (const abs (lim ⇑f + lim ⇑g) - (f + g)),
by rw [const_add, add_sub_comm];
exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g))
lemma lim_mul_lim (f g : cau_seq ℝ abs) : lim f * lim g = lim ⇑(f * g) :=
eq_lim_of_const_equiv $ show lim_zero (const abs (lim ⇑f * lim ⇑g) - f * g),
from have h : const abs (lim ⇑f * lim ⇑g) - f * g = g * (const abs (lim f) - f)
+ const abs (lim f) * (const abs (lim g) - g) :=
by simp [mul_sub, mul_comm, const_mul, mul_add],
by rw h; exact add_lim_zero (mul_lim_zero _ (setoid.symm (equiv_lim f)))
(mul_lim_zero _ (setoid.symm (equiv_lim g)))
lemma lim_mul (f : cau_seq ℝ abs) (x : ℝ) : lim f * x = lim ⇑(f * const abs x) :=
by rw [← lim_mul_lim, lim_const]
lemma lim_neg (f : cau_seq ℝ abs) : lim ⇑(-f) = -lim f :=
lim_eq_of_equiv_const (show lim_zero (-f - const abs (-lim ⇑f)),
by rw [const_neg, sub_neg_eq_add, add_comm];
exact setoid.symm (equiv_lim f))
lemma lim_eq_zero_iff (f : cau_seq ℝ abs) : lim f = 0 ↔ lim_zero f :=
⟨assume h,
by have hf := equiv_lim f;
rw h at hf;
exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl),
assume h,
have h₁ : f = (f - const abs 0) := ext (λ n, by simp [sub_apply, const_apply]),
by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩
lemma lim_inv {f : cau_seq ℝ abs} (hf : ¬ lim_zero f) : lim ⇑(inv f hf) = (lim f)⁻¹ :=
have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf,
lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abs (lim ⇑f)⁻¹),
from have h₁ : ∀ (g f : cau_seq ℝ abs) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) :=
λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f];
exact mul_lim_zero _ (setoid.symm (cau_seq.inv_mul_cancel _)),
have h₂ : lim_zero ((inv f hf - const abs (lim ⇑f)⁻¹) - (const abs (lim f) - f) *
(inv f hf * const abs (lim ⇑f)⁻¹)) :=
by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add];
exact show lim_zero (inv f hf - const abs (lim ⇑f) * (inv f hf * const abs (lim ⇑f)⁻¹)
- (const abs (lim ⇑f)⁻¹ - f * (inv f hf * const abs (lim ⇑f)⁻¹))),
from sub_lim_zero
(by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _)
(by rw [← mul_assoc]; exact h₁ _ _ _),
(lim_zero_congr h₂).mpr $ by rw mul_comm; exact mul_lim_zero _ (setoid.symm (equiv_lim f))
end lim
theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x :=
suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin
intros x x0, cases x0,
cases le_total x 1 with x1 x1,
{ rcases H x0 x1 with ⟨y, y0, hy⟩,
exact ⟨y, le_of_lt y0, hy⟩ },
{ have := (inv_le_inv x0 zero_lt_one).2 x1,
rw inv_one at this,
rcases H (inv_pos x0) this with ⟨y, y0, hy⟩,
refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] },
{ exact ⟨0, by simp [x0.symm]⟩ }
end,
λ x x0 x1, begin
let S := {y | 0 < y ∧ y * y ≤ x},
have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩,
have ub : ∀ y ∈ S, (y:ℝ) ≤ 1,
{ intros y yS, cases yS with y0 yx,
refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _,
simpa using le_trans yx x1 },
have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb),
refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩,
{ rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h,
rcases h with ⟨y, ⟨y0, yx⟩, hy⟩,
rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy,
rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩,
rw [div_lt_iff y0] at hz,
exact not_lt_of_lt
((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz))
((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) },
{ let s := Sup S, let y := s + (x - s * s) / 3,
replace h : 0 < x - s * s := sub_pos.2 h,
have _30 := bit1_pos zero_le_one,
have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30),
refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩),
rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul,
← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)],
apply add_le_add,
{ simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) },
{ rw [div_le_one_iff_le _30],
refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _),
exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } }
end
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div];
apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ rcases this with ⟨δ, δ0, hδ⟩,
intros,
}
end -/
noncomputable def sqrt (x : ℝ) : ℝ :=
classical.some (sqrt_exists (le_max_left 0 x))
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x :=
classical.some_spec (sqrt_exists (le_max_left 0 x))
/-quotient.induction_on x $ λ f,
by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/
theorem sqrt_eq_zero_of_nonpos {x : ℝ} (h : x ≤ 0) : sqrt x = 0 :=
eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1
@[simp] theorem mul_self_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x * sqrt x = x :=
(sqrt_prop x).2.trans (max_eq_right h)
@[simp] theorem sqrt_mul_self {x : ℝ} (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_iff_mul_self_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx],
λ h, by rw [← h, sqrt_mul_self hy]⟩
@[simp] theorem sqr_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x ^ 2 = x :=
by rw [pow_two, mul_self_sqrt h]
@[simp] theorem sqrt_sqr {x : ℝ} (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [pow_two, sqrt_mul_self h]
theorem sqrt_eq_iff_sqr_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x :=
(le_total 0 x).elim
(λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm)
(λ h, by rw [← neg_mul_neg,
sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h])
theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x :=
by rw [pow_two, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 :=
by simpa using sqrt_mul_self (le_refl _)
@[simp] theorem sqrt_one : sqrt 1 = 1 :=
by simpa using sqrt_mul_self zero_le_one
@[simp] theorem sqrt_le {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _),
mul_self_sqrt hx, mul_self_sqrt hy]
@[simp] theorem sqrt_lt {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y :=
le_iff_le_iff_lt_iff_lt.1 (sqrt_le hy hx)
@[simp] theorem sqrt_inj {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero {x : ℝ} (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h (le_refl _)
theorem sqrt_eq_zero' {x : ℝ} : sqrt x = 0 ↔ x ≤ 0 :=
(le_total x 0).elim
(λ h, by simp [h, sqrt_eq_zero_of_nonpos])
(λ h, by simp [h]; simp [le_antisymm_iff, h])
@[simp] theorem sqrt_pos {x : ℝ} : 0 < sqrt x ↔ 0 < x :=
le_iff_le_iff_lt_iff_lt.1 (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
begin
cases le_total 0 x with hx hx,
{ refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg},
rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc,
mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] },
{ rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy),
sqrt_eq_zero'.2 hx, zero_mul] }
end
@[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul' _ hx, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
(le_or_lt x 0).elim
(λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h])
(λ h, by rw [
← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h),
mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)])
@[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv]; refl
end real
|
fd60421813862dd43184db554afc6ea9af5fd45a | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean4/tests/JsonRoundtrip.lean | ec657ecd747313f85a39f736c6a7fd22feb17d04 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 1,446 | lean |
import ReoptVCG.Annotations
import Init.Lean.Data.Json
import Init.Lean.Data.Json.FromToJson
import Galois.Init.Json
namespace Test
namespace JsonRoundtrip
-- Parses the contents of the specified file first as a Json object
-- then as a ModuleAnnotation, which is then re-converted into a Json
-- string and reparsed as Json again. The initial and final Json
-- objects are checked for equivalence, returning "pass" if they
-- are equivalent or some error string if they are not.
def roundtripTest (annFile : String) : IO String := do
fileContents ← IO.FS.readFile annFile;
match Lean.Json.parse fileContents with
| Except.error errMsg => pure $ "Failed to parse json in `"++annFile++"`: " ++ errMsg
| Except.ok js =>
match ReoptVCG.parseAnnotations js with
| Except.error errMsg => pure $ "Failed to parse json as a module annotation: " ++ errMsg
| Except.ok modAnn =>
let str := toString $ modAnn.toJson;
match Lean.Json.parse str with
| Except.error errMsg => pure $ "Failed to re-parse json from `"++annFile++"`: "++errMsg
| Except.ok js' =>
if Lean.Json.isEqv js js'
then pure "pass"
else pure $ "The following are not equivalent Json values: \n"++str++"\n\nand\n\n"++(toString js')
def test : IO UInt32 := do
roundtripTest "../test-programs/test_fib_diet_reopt.ann" >>= IO.println;
roundtripTest "../test-programs/test_add_diet_reopt.ann" >>= IO.println;
pure 0
end JsonRoundtrip
end Test
|
47c07e99d86299ed1200a0e3d9b501551f024dda | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/measure_theory/measure_space.lean | 67a56e6208631c1a353e368bf3329db80d99143c | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 117,876 | 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 nnreal
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
/-- For every set there exists a measurable superset of the same measure. -/
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
/-- For every set `s` and a countable collection of measures `μ i` there exists a measurable
superset `t ⊇ s` such that each measure `μ i` takes the same value on `s` and `t`. -/
lemma exists_measurable_superset_forall_eq {ι} [encodable ι] (μ : ι → measure α) (s : set α) :
∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = μ i s :=
by simpa only [← measure_eq_trim]
using outer_measure.exists_measurable_superset_forall_eq_trim (λ i, (μ i).to_outer_measure) 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⟩
lemma measure_bUnion_null_iff {s : set ι} (hs : countable s) {t : ι → set α} :
μ (⋃ i ∈ s, t i) = 0 ↔ ∀ i ∈ s, μ (t i) = 0 :=
by { haveI := hs.to_encodable, rw [← Union_subtype, measure_Union_null_iff, set_coe.forall], refl }
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 `∃ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.frequently 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 frequently_ae_iff {p : α → Prop} : (∃ᵐ a ∂μ, p a) ↔ μ {a | p a} ≠ 0 :=
not_congr compl_mem_ae_iff
lemma frequently_ae_mem_iff {s : set α} : (∃ᵐ a ∂μ, a ∈ s) ↔ μ s ≠ 0 :=
not_congr compl_mem_ae_iff
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
/-- 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
notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P
(measure_theory.measure.ae measure_theory.measure_space.volume)) := r
notation `∃ᵐ` binders `, ` r:(scoped P, filter.frequently P
(measure_theory.measure.ae measure_theory.measure_space.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
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_add_measure_compl (h : measurable_set s) :
μ s + μ sᶜ = μ univ :=
by { rw [← union_compl_self s, measure_union _ h h.compl], exact disjoint_compl_right }
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_null' (h : μ (s₁ ∩ s₂) = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_congr $ diff_ae_eq_self.2 h
lemma measure_diff_null (h : μ s₂ = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_diff_null' $ measure_mono_null (inter_subset_right _ _) h
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 : module ℝ≥0∞ (measure α) :=
injective.module ℝ≥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_semilattice_Inf (measure α) :=
{ Inf_le := λ s a, measure_Inf_le,
le_Inf := λ s a, measure_le_Inf,
..(by apply_instance : partial_order (measure α)),
..(by apply_instance : has_Inf (measure α)), }
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_complete_semilattice_Inf (measure α) }
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]
theorem map_of_not_measurable {f : α → β} (hf : ¬measurable f) :
map f μ = 0 :=
by rw [map, dif_neg hf, linear_map.zero_apply]
@[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]
@[mono] lemma map_mono (f : α → β) (h : μ ≤ ν) : map f μ ≤ map f ν :=
if hf : measurable f then λ s hs, by simp only [map_apply hf hs, h _ (hf hs)]
else by simp only [map_of_not_measurable hf, le_rfl]
/-- 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
lemma tendsto_ae_map {f : α → β} (hf : measurable f) : tendsto f μ.ae (map f μ).ae :=
λ s hs, preimage_null_of_map_null hf 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, inter_eq_left_iff_subset.mpr 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 (set α) _ _) 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_of_le (h : μ ≤ ν) : μ ≪ ν :=
λ s hs, nonpos_iff_eq_zero.1 $ hs ▸ le_iff'.1 h s
alias absolutely_continuous_of_le ← has_le.le.absolutely_continuous
lemma absolutely_continuous_of_eq (h : μ = ν) : μ ≪ ν :=
h.le.absolutely_continuous
alias absolutely_continuous_of_eq ← eq.absolutely_continuous
namespace absolutely_continuous
lemma 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] protected lemma refl (μ : measure α) : μ ≪ μ := rfl.absolutely_continuous
protected lemma rfl : μ ≪ μ := λ s hs, hs
@[trans] protected lemma trans (h1 : μ₁ ≪ μ₂) (h2 : μ₂ ≪ μ₃) : μ₁ ≪ μ₃ :=
λ s hs, h1 $ h2 hs
@[mono] protected lemma map (h : μ ≪ ν) (f : α → β) : map f μ ≪ map f ν :=
if hf : measurable f then absolutely_continuous.mk $ λ s hs, by simpa [hf, hs] using @h _
else by simp only [map_of_not_measurable hf]
end absolutely_continuous
lemma ae_le_iff_absolutely_continuous : μ.ae ≤ ν.ae ↔ μ ≪ ν :=
⟨λ h s, by { rw [measure_zero_iff_ae_nmem, measure_zero_iff_ae_nmem], exact λ hs, h hs },
λ h s hs, h hs⟩
alias ae_le_iff_absolutely_continuous ↔ has_le.le.absolutely_continuous_of_ae
measure_theory.measure.absolutely_continuous.ae_le
alias absolutely_continuous.ae_le ← ae_mono'
lemma absolutely_continuous.ae_eq (h : μ ≪ ν) {f g : α → δ} (h' : f =ᵐ[ν] g) : f =ᵐ[μ] g :=
h.ae_le h'
/-! ### Quasi measure preserving maps (a.k.a. non-singular maps) -/
/-- A map `f : α → β` is said to be *quasi measure preserving* (a.k.a. non-singular) w.r.t. measures
`μa` and `μb` if it is measurable and `μb s = 0` implies `μa (f ⁻¹' s) = 0`. -/
@[protect_proj]
structure quasi_measure_preserving (f : α → β) (μa : measure α . volume_tac)
(μb : measure β . volume_tac) : Prop :=
(measurable : measurable f)
(absolutely_continuous : map f μa ≪ μb)
namespace quasi_measure_preserving
protected lemma id (μ : measure α) : quasi_measure_preserving id μ μ :=
⟨measurable_id, map_id.absolutely_continuous⟩
variables {μa μa' : measure α} {μb μb' : measure β} {μc : measure γ} {f : α → β}
lemma mono_left (h : quasi_measure_preserving f μa μb)
(ha : μa' ≪ μa) : quasi_measure_preserving f μa' μb :=
⟨h.1, (ha.map f).trans h.2⟩
lemma mono_right (h : quasi_measure_preserving f μa μb)
(ha : μb ≪ μb') : quasi_measure_preserving f μa μb' :=
⟨h.1, h.2.trans ha⟩
@[mono] lemma mono (ha : μa' ≪ μa) (hb : μb ≪ μb') (h : quasi_measure_preserving f μa μb) :
quasi_measure_preserving f μa' μb' :=
(h.mono_left ha).mono_right hb
protected lemma comp {g : β → γ} {f : α → β} (hg : quasi_measure_preserving g μb μc)
(hf : quasi_measure_preserving f μa μb) :
quasi_measure_preserving (g ∘ f) μa μc :=
⟨hg.measurable.comp hf.measurable, by { rw ← map_map hg.1 hf.1, exact (hf.2.map g).trans hg.2 }⟩
protected lemma iterate {f : α → α} (hf : quasi_measure_preserving f μa μa) :
∀ n, quasi_measure_preserving (f^[n]) μa μa
| 0 := quasi_measure_preserving.id μa
| (n + 1) := (iterate n).comp hf
lemma ae_map_le (h : quasi_measure_preserving f μa μb) : (map f μa).ae ≤ μb.ae :=
h.2.ae_le
lemma tendsto_ae (h : quasi_measure_preserving f μa μb) : tendsto f μa.ae μb.ae :=
(tendsto_ae_map h.1).mono_right h.ae_map_le
lemma ae (h : quasi_measure_preserving f μa μb) {p : β → Prop} (hg : ∀ᵐ x ∂μb, p x) :
∀ᵐ x ∂μa, p (f x) :=
h.tendsto_ae hg
lemma ae_eq (h : quasi_measure_preserving f μa μb) {g₁ g₂ : β → δ} (hg : g₁ =ᵐ[μb] g₂) :
g₁ ∘ f =ᵐ[μa] g₂ ∘ f :=
h.ae hg
end quasi_measure_preserving
/-! ### The `cofinite` filter -/
/-- 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_ne_bot : μ.ae.ne_bot ↔ μ ≠ 0 :=
ne_bot_iff.trans (not_congr ae_eq_bot)
@[simp] lemma ae_zero : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl
@[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae :=
h.absolutely_continuous.ae_le
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 mem_ae_of_mem_ae_map {f : α → β} (hf : measurable f) {s : set β} (hs : s ∈ (map f μ).ae) :
f ⁻¹' s ∈ μ.ae :=
begin
apply le_antisymm _ bot_le,
calc μ (f ⁻¹' sᶜ) ≤ (map f μ) sᶜ : le_map_apply hf sᶜ
... = 0 : hs
end
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_of_ae_map {f : α → β} (hf : measurable f) {p : β → Prop} (h : ∀ᵐ y ∂ (map f μ), p y) :
∀ᵐ x ∂ μ, p (f x) :=
mem_ae_of_mem_ae_map hf h
lemma ae_map_mem_range (f : α → β) (hf : measurable_set (range f)) (μ : measure α) :
∀ᵐ x ∂(map f μ), x ∈ range f :=
begin
by_cases h : measurable f,
{ change range f ∈ (map f μ).ae,
rw mem_ae_map_iff h hf,
apply eventually_of_forall,
exact mem_range_self },
{ simp [map_of_not_measurable h] }
end
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_restrict_of_ae {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
eventually.filter_mono (ae_mono measure.restrict_le_self) h
lemma ae_restrict_of_ae_restrict_of_subset {s t : set α} {p : α → Prop} (hst : s ⊆ t)
(h : ∀ᵐ x ∂(μ.restrict t), p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
h.filter_mono (ae_mono $ measure.restrict_mono hst (le_refl μ))
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 :=
(quasi_measure_preserving.mk hf h2).ae_eq 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)
/-- The measure of the whole space with respect to a finite measure, considered as `ℝ≥0`. -/
def measure_univ_nnreal (μ : measure α) : ℝ≥0 := (μ univ).to_nnreal
@[simp] lemma coe_measure_univ_nnreal (μ : measure α) [finite_measure μ] :
↑(measure_univ_nnreal μ) = μ univ :=
ennreal.coe_to_nnreal (measure_ne_top μ univ)
instance finite_measure_zero : finite_measure (0 : measure α) := ⟨by simp⟩
@[simp] lemma measure_univ_nnreal_zero : measure_univ_nnreal (0 : measure α) = 0 := rfl
@[simp] lemma measure_univ_nnreal_eq_zero [finite_measure μ] : measure_univ_nnreal μ = 0 ↔ μ = 0 :=
begin
rw [← measure_theory.measure.measure_univ_eq_zero, ← coe_measure_univ_nnreal],
norm_cast
end
lemma measure_univ_nnreal_pos [finite_measure μ] (hμ : μ ≠ 0) : 0 < measure_univ_nnreal μ :=
begin
contrapose! hμ,
simpa [measure_univ_nnreal_eq_zero, le_zero_iff] using hμ
end
/-- `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 μ]
instance (s : set α) : has_no_atoms (μ.restrict s) :=
begin
refine ⟨λ x, _⟩,
obtain ⟨t, hxt, ht1, ht2⟩ := exists_measurable_superset_of_null (measure_singleton x : μ {x} = 0),
apply measure_mono_null hxt,
rw measure.restrict_apply ht1,
apply measure_mono_null (inter_subset_left t s) ht2
end
lemma _root_.set.countable.measure_zero (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 _root_.set.finite.measure_zero (h : s.finite) : μ s = 0 :=
h.countable.measure_zero
lemma _root_.finset.measure_zero (s : finset α) : μ ↑s = 0 :=
s.finite_to_set.measure_zero
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 }
lemma sigma_finite.of_map (μ : measure α) {f : α → β} (hf : measurable f)
(h : sigma_finite (map f μ)) :
sigma_finite μ :=
⟨⟨⟨λ n, f ⁻¹' (spanning_sets (map f μ) n),
λ n, hf $ measurable_spanning_sets _ _,
λ n, by simp only [← map_apply hf, measurable_spanning_sets, measure_spanning_sets_lt_top],
by rw [← preimage_Union, Union_spanning_sets, preimage_univ]⟩⟩⟩
/-- 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_semilattice_Inf,
simp [le_refl, add_comm, h_measure_sub_add] },
apply @le_Inf (measure α) measure.complete_semilattice_Inf,
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,
exact le_self_add },
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},
refine 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] },
{ rw add_apply,
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
/-!
# 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_measure : 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⟩
protected 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, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ :=
measurable_one.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 _⟩
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
|
32a55b3e5ce948e8ddb7670679ab369b137f00a4 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/measure_theory/measure/measure_space_def.lean | b97720ef68375ed41dfbc1972b1ccefc3f2c275a | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,433 | 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.measure.outer_measure
import order.filter.countable_Inter
import data.set.accumulate
/-!
# Measure spaces
This file defines measure spaces, the almost-everywhere filter and ae_measurable functions.
See `measure_theory.measure_space` for their properties and for extended documentation.
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∞`.
## 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.
See the documentation of `measure_theory.measure_space` for ways to construct measures and proving
that two measure are equal.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
This file does not import `measure_theory.measurable_space`, but only `measurable_space_def`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space
-/
noncomputable theory
open classical set filter (hiding map) function measurable_space
open_locale classical topological_space big_operators filter ennreal nnreal
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
/-- For every set there exists a measurable superset of the same measure. -/
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
/-- For every set `s` and a countable collection of measures `μ i` there exists a measurable
superset `t ⊇ s` such that each measure `μ i` takes the same value on `s` and `t`. -/
lemma exists_measurable_superset_forall_eq {ι} [encodable ι] (μ : ι → measure α) (s : set α) :
∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = μ i s :=
by simpa only [← measure_eq_trim]
using outer_measure.exists_measurable_superset_forall_eq_trim (λ i, (μ i).to_outer_measure) 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_Union_fintype_le [fintype β] (f : β → set α) :
μ (⋃ b, f b) ≤ ∑ p, μ (f p) :=
by { convert measure_bUnion_finset_le finset.univ f, simp }
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⟩
lemma measure_bUnion_null_iff {s : set ι} (hs : countable s) {t : ι → set α} :
μ (⋃ i ∈ s, t i) = 0 ↔ ∀ i ∈ s, μ (t i) = 0 :=
by { haveI := hs.to_encodable, rw [← Union_subtype, measure_Union_null_iff, set_coe.forall], refl }
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⟩
lemma measure_union_lt_top (hs : μ s < ∞) (ht : μ t < ∞) : μ (s ∪ t) < ∞ :=
(measure_union_le s t).trans_lt (ennreal.add_lt_top.mpr ⟨hs, ht⟩)
lemma measure_union_lt_top_iff : μ (s ∪ t) < ∞ ↔ μ s < ∞ ∧ μ t < ∞ :=
begin
refine ⟨λ h, ⟨_, _⟩, λ h, measure_union_lt_top h.1 h.2⟩,
{ exact (measure_mono (set.subset_union_left s t)).trans_lt h, },
{ exact (measure_mono (set.subset_union_right s t)).trans_lt h, },
end
lemma measure_union_ne_top (hs : μ s ≠ ∞) (ht : μ t ≠ ∞) : μ (s ∪ t) ≠ ∞ :=
((measure_union_le s t).trans_lt (lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hs, ht⟩))).ne
lemma exists_measure_pos_of_not_measure_Union_null [encodable β] {s : β → set α}
(hs : μ (⋃ n, s n) ≠ 0) : ∃ n, 0 < μ (s n) :=
begin
by_contra, push_neg at h,
simp_rw nonpos_iff_eq_zero at h,
exact hs (measure_Union_null h),
end
lemma measure_inter_lt_top_of_left_ne_top (hs_finite : μ s ≠ ∞) : μ (s ∩ t) < ∞ :=
(measure_mono (set.inter_subset_left s t)).trans_lt hs_finite.lt_top
lemma measure_inter_lt_top_of_right_ne_top (ht_finite : μ t ≠ ∞) : μ (s ∩ t) < ∞ :=
inter_comm t s ▸ measure_inter_lt_top_of_left_ne_top ht_finite
lemma measure_inter_null_of_null_right (S : set α) {T : set α} (h : μ T = 0) : μ (S ∩ T) = 0 :=
measure_mono_null (inter_subset_right S T) h
lemma measure_inter_null_of_null_left {S : set α} (T : set α) (h : μ S = 0) : μ (S ∩ T) = 0 :=
measure_mono_null (inter_subset_left S T) h
/-! ### The almost everywhere filter -/
/-- The “almost everywhere” filter of co-null sets. -/
def measure.ae {α} {m : measurable_space α} (μ : 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 `∃ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.frequently 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 frequently_ae_iff {p : α → Prop} : (∃ᵐ a ∂μ, p a) ↔ μ {a | p a} ≠ 0 :=
not_congr compl_mem_ae_iff
lemma frequently_ae_mem_iff {s : set α} : (∃ᵐ a ∂μ, a ∈ s) ↔ μ s ≠ 0 :=
not_congr compl_mem_ae_iff
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₂
lemma ae_le_of_ae_lt {f g : α → ℝ≥0∞} (h : ∀ᵐ x ∂μ, f x < g x) : f ≤ᵐ[μ] g :=
begin
rw [filter.eventually_le, ae_iff],
rw ae_iff at h,
refine measure_mono_null (λ x hx, _) h,
exact not_lt.2 (le_of_lt (not_le.1 hx)),
end
@[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]
@[to_additive]
lemma _root_.set.mul_indicator_ae_eq_one {M : Type*} [has_one M] {f : α → M} {s : set α}
(h : s.mul_indicator f =ᵐ[μ] 1) : μ (s ∩ function.mul_support f) = 0 :=
begin
rw [filter.eventually_eq, ae_iff] at h,
convert h,
ext a,
rw ← set.mul_indicator_eq_one_iff,
refl
end
/-- 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
/-- 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
notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P
(measure_theory.measure.ae measure_theory.measure_space.volume)) := r
notation `∃ᵐ` binders `, ` r:(scoped P, filter.frequently P
(measure_theory.measure.ae measure_theory.measure_space.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
end measure_theory
section
open 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 μ`. It's properties are discussed in
`measure_theory.measure_space`.
-/
variables {m : 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 {m : measurable_space α} (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⟩
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⟩
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_const {b : β} : ae_measurable (λ a : α, b) μ :=
measurable_const.ae_measurable
lemma ae_measurable_id : ae_measurable id μ := measurable_id.ae_measurable
lemma ae_measurable_id' : ae_measurable (λ x, x) μ := measurable_id.ae_measurable
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 _⟩
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.